Coverage Report

Created: 2026-08-14 22:12

/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
0
int64_t packed_file_retry_sleep_ms() {
89
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
90
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
91
0
    thread_local std::mt19937_64 gen(std::random_device {}());
92
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
93
0
    return dist(gen);
94
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
95
96
0
void sleep_for_packed_file_retry() {
97
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
98
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
99
100
37
bool filter_out_instance(const std::string& instance_id) {
101
37
    if (config::recycle_whitelist.empty()) {
102
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
103
35
               config::recycle_blacklist.end();
104
35
    }
105
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
106
2
           config::recycle_whitelist.end();
107
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
100
37
bool filter_out_instance(const std::string& instance_id) {
101
37
    if (config::recycle_whitelist.empty()) {
102
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
103
35
               config::recycle_blacklist.end();
104
35
    }
105
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
106
2
           config::recycle_whitelist.end();
107
37
}
108
109
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
868k
    const auto& locations = rowset.packed_slice_locations();
111
868k
    auto it = locations.find(path);
112
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
113
868k
           !it->second.packed_file_path().empty();
114
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
109
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
7
    const auto& locations = rowset.packed_slice_locations();
111
7
    auto it = locations.find(path);
112
7
    return it != locations.end() && it->second.has_packed_file_path() &&
113
7
           !it->second.packed_file_path().empty();
114
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
109
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
110
868k
    const auto& locations = rowset.packed_slice_locations();
111
868k
    auto it = locations.find(path);
112
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
113
868k
           !it->second.packed_file_path().empty();
114
868k
}
115
116
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
117
                                      const std::string& path,
118
867k
                                      std::vector<std::string>* file_paths) {
119
867k
    if (!is_packed_slice_path(rowset, path)) {
120
867k
        file_paths->push_back(path);
121
867k
    }
122
867k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
118
7
                                      std::vector<std::string>* file_paths) {
119
7
    if (!is_packed_slice_path(rowset, path)) {
120
7
        file_paths->push_back(path);
121
7
    }
122
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
118
867k
                                      std::vector<std::string>* file_paths) {
119
867k
    if (!is_packed_slice_path(rowset, path)) {
120
867k
        file_paths->push_back(path);
121
867k
    }
122
867k
}
123
124
} // namespace
125
126
// return 0 for success get a key, 1 for key not found, negative for error
127
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
128
0
    std::unique_ptr<Transaction> txn;
129
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
130
0
    if (err != TxnErrorCode::TXN_OK) {
131
0
        return -1;
132
0
    }
133
0
    switch (txn->get(key, &val, true)) {
134
0
    case TxnErrorCode::TXN_OK:
135
0
        return 0;
136
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
137
0
        return 1;
138
0
    default:
139
0
        return -1;
140
0
    };
141
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
142
143
// 0 for success, negative for error
144
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
145
312
                   std::unique_ptr<RangeGetIterator>& it) {
146
312
    std::unique_ptr<Transaction> txn;
147
312
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
312
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
312
    switch (txn->get(begin, end, &it, true)) {
152
312
    case TxnErrorCode::TXN_OK:
153
312
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
312
    };
159
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
145
31
                   std::unique_ptr<RangeGetIterator>& it) {
146
31
    std::unique_ptr<Transaction> txn;
147
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
31
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
31
    switch (txn->get(begin, end, &it, true)) {
152
31
    case TxnErrorCode::TXN_OK:
153
31
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
31
    };
159
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
145
281
                   std::unique_ptr<RangeGetIterator>& it) {
146
281
    std::unique_ptr<Transaction> txn;
147
281
    TxnErrorCode err = txn_kv->create_txn(&txn);
148
281
    if (err != TxnErrorCode::TXN_OK) {
149
0
        return -1;
150
0
    }
151
281
    switch (txn->get(begin, end, &it, true)) {
152
281
    case TxnErrorCode::TXN_OK:
153
281
        return 0;
154
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
155
0
        return 1;
156
0
    default:
157
0
        return -1;
158
281
    };
159
0
}
160
161
// return 0 for success otherwise error
162
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
6
    std::unique_ptr<Transaction> txn;
164
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
6
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
10
    for (auto k : keys) {
169
10
        txn->remove(k);
170
10
    }
171
6
    switch (txn->commit()) {
172
6
    case TxnErrorCode::TXN_OK:
173
6
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
6
    }
179
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
162
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
1
    std::unique_ptr<Transaction> txn;
164
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
1
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
1
    for (auto k : keys) {
169
1
        txn->remove(k);
170
1
    }
171
1
    switch (txn->commit()) {
172
1
    case TxnErrorCode::TXN_OK:
173
1
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
1
    }
179
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
162
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
163
5
    std::unique_ptr<Transaction> txn;
164
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
165
5
    if (err != TxnErrorCode::TXN_OK) {
166
0
        return -1;
167
0
    }
168
9
    for (auto k : keys) {
169
9
        txn->remove(k);
170
9
    }
171
5
    switch (txn->commit()) {
172
5
    case TxnErrorCode::TXN_OK:
173
5
        return 0;
174
0
    case TxnErrorCode::TXN_CONFLICT:
175
0
        return -1;
176
0
    default:
177
0
        return -1;
178
5
    }
179
5
}
180
181
// return 0 for success otherwise error
182
101
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
101
    std::unique_ptr<Transaction> txn;
184
101
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
101
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
105k
    for (auto& k : keys) {
189
105k
        txn->remove(k);
190
105k
    }
191
101
    switch (txn->commit()) {
192
101
    case TxnErrorCode::TXN_OK:
193
101
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
101
    }
199
101
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
182
34
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
34
    std::unique_ptr<Transaction> txn;
184
34
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
34
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
34
    for (auto& k : keys) {
189
17
        txn->remove(k);
190
17
    }
191
34
    switch (txn->commit()) {
192
34
    case TxnErrorCode::TXN_OK:
193
34
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
34
    }
199
34
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
182
67
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
183
67
    std::unique_ptr<Transaction> txn;
184
67
    TxnErrorCode err = txn_kv->create_txn(&txn);
185
67
    if (err != TxnErrorCode::TXN_OK) {
186
0
        return -1;
187
0
    }
188
105k
    for (auto& k : keys) {
189
105k
        txn->remove(k);
190
105k
    }
191
67
    switch (txn->commit()) {
192
67
    case TxnErrorCode::TXN_OK:
193
67
        return 0;
194
0
    case TxnErrorCode::TXN_CONFLICT:
195
0
        return -1;
196
0
    default:
197
0
        return -1;
198
67
    }
199
67
}
200
201
// return 0 for success otherwise error
202
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
203
106k
                                       std::string_view end) {
204
106k
    std::unique_ptr<Transaction> txn;
205
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
106k
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
106k
    txn->remove(begin, end);
210
106k
    switch (txn->commit()) {
211
106k
    case TxnErrorCode::TXN_OK:
212
106k
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
106k
    }
218
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
203
17
                                       std::string_view end) {
204
17
    std::unique_ptr<Transaction> txn;
205
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
17
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
17
    txn->remove(begin, end);
210
17
    switch (txn->commit()) {
211
17
    case TxnErrorCode::TXN_OK:
212
17
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
17
    }
218
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
203
106k
                                       std::string_view end) {
204
106k
    std::unique_ptr<Transaction> txn;
205
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
206
106k
    if (err != TxnErrorCode::TXN_OK) {
207
0
        return -1;
208
0
    }
209
106k
    txn->remove(begin, end);
210
106k
    switch (txn->commit()) {
211
106k
    case TxnErrorCode::TXN_OK:
212
106k
        return 0;
213
0
    case TxnErrorCode::TXN_CONFLICT:
214
0
        return -1;
215
0
    default:
216
0
        return -1;
217
106k
    }
218
106k
}
219
220
void scan_restore_job_rowset(
221
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
222
        std::string& msg,
223
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
224
225
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
226
                                      int64_t num_scanned, int64_t num_recycled,
227
47
                                      int64_t start_time) {
228
47
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
47
    return;
240
47
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
227
2
                                      int64_t start_time) {
228
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
2
    return;
240
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
227
45
                                      int64_t start_time) {
228
45
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
229
0
        int64_t cost =
230
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
231
0
        if (cost > config::recycle_task_threshold_seconds) {
232
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
233
0
                    .tag("instance_id", instance_id)
234
0
                    .tag("task", task_name)
235
0
                    .tag("num_scanned", num_scanned)
236
0
                    .tag("num_recycled", num_recycled);
237
0
        }
238
0
    }
239
45
    return;
240
45
}
241
242
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
243
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
244
245
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
246
6
                                                               "s3_producer_pool");
247
6
    s3_producer_pool->start();
248
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
249
6
                                                                  "recycle_tablet_pool");
250
6
    recycle_tablet_pool->start();
251
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
252
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
253
6
    group_recycle_function_pool->start();
254
6
    _thread_pool_group =
255
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
256
6
                                    std::move(group_recycle_function_pool));
257
258
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
259
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
260
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
261
6
}
262
263
6
Recycler::~Recycler() {
264
6
    if (!stopped()) {
265
0
        stop();
266
0
    }
267
6
}
268
269
5
void Recycler::instance_scanner_callback() {
270
    // sleep 60 seconds before scheduling for the launch procedure to complete:
271
    // some bad hdfs connection may cause some log to stdout stderr
272
    // which may pollute .out file and affect the script to check success
273
5
    std::this_thread::sleep_for(
274
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
275
1.24k
    while (!stopped()) {
276
1.24k
        if (config::enable_recycler) {
277
3
            std::vector<InstanceInfoPB> instances;
278
3
            get_all_instances(txn_kv_.get(), instances);
279
            // TODO(plat1ko): delete job recycle kv of non-existent instances
280
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
281
3
                std::stringstream ss;
282
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
283
3
                return ss.str();
284
3
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
280
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
281
3
                std::stringstream ss;
282
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
283
3
                return ss.str();
284
3
            }();
285
3
            if (!instances.empty()) {
286
                // enqueue instances
287
3
                std::lock_guard lock(mtx_);
288
30
                for (auto& instance : instances) {
289
30
                    if (filter_out_instance(instance.instance_id())) continue;
290
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
291
                    // skip instance already in pending queue
292
30
                    if (success) {
293
30
                        pending_instance_queue_.push_back(std::move(instance));
294
30
                    }
295
30
                }
296
3
                pending_instance_cond_.notify_all();
297
3
            }
298
1.24k
        } else {
299
1.24k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
300
1.24k
        }
301
1.24k
        {
302
1.24k
            std::unique_lock lock(mtx_);
303
1.24k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
304
2.48k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
304
2.48k
                               [&]() { return stopped(); });
305
1.24k
        }
306
1.24k
    }
307
5
}
308
309
9
void Recycler::recycle_callback() {
310
40
    while (!stopped()) {
311
38
        InstanceInfoPB instance;
312
38
        {
313
38
            std::unique_lock lock(mtx_);
314
38
            pending_instance_cond_.wait(
315
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
315
50
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
316
38
            if (stopped()) {
317
7
                return;
318
7
            }
319
31
            instance = std::move(pending_instance_queue_.front());
320
31
            pending_instance_queue_.pop_front();
321
31
            pending_instance_set_.erase(instance.instance_id());
322
31
        }
323
0
        auto& instance_id = instance.instance_id();
324
31
        {
325
31
            std::lock_guard lock(mtx_);
326
            // skip instance in recycling
327
31
            if (recycling_instance_map_.count(instance_id)) continue;
328
31
        }
329
31
        if (!config::enable_recycler) {
330
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
331
1
                         << " since enable_recycler is false";
332
1
            continue;
333
1
        }
334
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
335
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
336
337
30
        if (int r = instance_recycler->init(); r != 0) {
338
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
339
0
                         << " ret=" << r;
340
0
            continue;
341
0
        }
342
30
        std::string recycle_job_key;
343
30
        job_recycle_key({instance_id}, &recycle_job_key);
344
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
345
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
346
30
        if (ret != 0) { // Prepare failed
347
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
348
20
                         << " ret=" << ret;
349
20
            continue;
350
20
        } else {
351
10
            std::lock_guard lock(mtx_);
352
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
353
10
        }
354
10
        if (stopped()) return;
355
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
356
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
357
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
358
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
359
10
        ret = instance_recycler->do_recycle();
360
        // If instance recycler has been aborted, don't finish this job
361
362
10
        if (!instance_recycler->stopped()) {
363
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
364
10
                                        ret == 0, ctime_ms);
365
10
        }
366
10
        if (instance_recycler->stopped() || ret != 0) {
367
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
368
0
        }
369
10
        {
370
10
            std::lock_guard lock(mtx_);
371
10
            recycling_instance_map_.erase(instance_id);
372
10
        }
373
374
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
375
10
        auto elpased_ms = now - ctime_ms;
376
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
377
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
378
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
379
10
                                             now + config::recycle_interval_seconds * 1000);
380
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
381
10
        LOG(INFO) << "recycle instance done, "
382
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
383
10
                  << " now: " << now;
384
385
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
386
387
10
        LOG_WARNING("finish recycle instance")
388
10
                .tag("instance_id", instance_id)
389
10
                .tag("cost_ms", elpased_ms);
390
10
    }
391
9
}
392
393
4
void Recycler::lease_recycle_jobs() {
394
54
    while (!stopped()) {
395
50
        std::vector<std::string> instances;
396
50
        instances.reserve(recycling_instance_map_.size());
397
50
        {
398
50
            std::lock_guard lock(mtx_);
399
50
            for (auto& [id, _] : recycling_instance_map_) {
400
30
                instances.push_back(id);
401
30
            }
402
50
        }
403
50
        for (auto& i : instances) {
404
30
            std::string recycle_job_key;
405
30
            job_recycle_key({i}, &recycle_job_key);
406
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
407
30
            if (ret == 1) {
408
0
                std::lock_guard lock(mtx_);
409
0
                if (auto it = recycling_instance_map_.find(i);
410
0
                    it != recycling_instance_map_.end()) {
411
0
                    it->second->stop();
412
0
                }
413
0
            }
414
30
        }
415
50
        {
416
50
            std::unique_lock lock(mtx_);
417
50
            notifier_.wait_for(lock,
418
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
419
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
419
100
                               [&]() { return stopped(); });
420
50
        }
421
50
    }
422
4
}
423
424
4
void Recycler::check_recycle_tasks() {
425
7
    while (!stopped()) {
426
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
427
3
        {
428
3
            std::lock_guard lock(mtx_);
429
3
            recycling_instance_map = recycling_instance_map_;
430
3
        }
431
3
        for (auto& entry : recycling_instance_map) {
432
0
            entry.second->check_recycle_tasks();
433
0
        }
434
435
3
        std::unique_lock lock(mtx_);
436
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
437
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
437
6
                           [&]() { return stopped(); });
438
3
    }
439
4
}
440
441
4
int Recycler::start(brpc::Server* server) {
442
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
443
4
    S3Environment::getInstance();
444
445
4
    if (config::enable_checker) {
446
0
        checker_ = std::make_unique<Checker>(txn_kv_);
447
0
        int ret = checker_->start();
448
0
        std::string msg;
449
0
        if (ret != 0) {
450
0
            msg = "failed to start checker";
451
0
            LOG(ERROR) << msg;
452
0
            std::cerr << msg << std::endl;
453
0
            return ret;
454
0
        }
455
0
        msg = "checker started";
456
0
        LOG(INFO) << msg;
457
0
        std::cout << msg << std::endl;
458
0
    }
459
460
4
    if (server) {
461
        // Add service
462
1
        auto recycler_service =
463
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
464
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
465
1
    }
466
467
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
467
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
468
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
469
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
469
8
        workers_.emplace_back([this] { recycle_callback(); });
470
8
    }
471
472
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
473
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
474
475
4
    if (config::enable_snapshot_data_migrator) {
476
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
477
0
        int ret = snapshot_data_migrator_->start();
478
0
        if (ret != 0) {
479
0
            LOG(ERROR) << "failed to start snapshot data migrator";
480
0
            return ret;
481
0
        }
482
0
        LOG(INFO) << "snapshot data migrator started";
483
0
    }
484
485
4
    if (config::enable_snapshot_chain_compactor) {
486
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
487
0
        int ret = snapshot_chain_compactor_->start();
488
0
        if (ret != 0) {
489
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
490
0
            return ret;
491
0
        }
492
0
        LOG(INFO) << "snapshot chain compactor started";
493
0
    }
494
495
4
    return 0;
496
4
}
497
498
4
void Recycler::stop() {
499
4
    stopped_ = true;
500
4
    notifier_.notify_all();
501
4
    pending_instance_cond_.notify_all();
502
4
    {
503
4
        std::lock_guard lock(mtx_);
504
4
        for (auto& [_, recycler] : recycling_instance_map_) {
505
0
            recycler->stop();
506
0
        }
507
4
    }
508
20
    for (auto& w : workers_) {
509
20
        if (w.joinable()) w.join();
510
20
    }
511
4
    if (checker_) {
512
0
        checker_->stop();
513
0
    }
514
4
    if (snapshot_data_migrator_) {
515
0
        snapshot_data_migrator_->stop();
516
0
    }
517
4
    if (snapshot_chain_compactor_) {
518
0
        snapshot_chain_compactor_->stop();
519
0
    }
520
4
}
521
522
class InstanceRecycler::InvertedIndexIdCache {
523
public:
524
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
525
139
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
526
527
    // Return 0 if success, 1 if schema kv not found, negative for error
528
    // For the same index_id, schema_version, res, since `get` is not completely atomic
529
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
530
    // resulting in repeated addition and inaccuracy.
531
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
532
    // repeated addition does not affect correctness.
533
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
534
28.4k
        {
535
28.4k
            std::lock_guard lock(mtx_);
536
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
537
3.91k
                return 0;
538
3.91k
            }
539
24.4k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
540
24.4k
                it != inverted_index_id_map_.end()) {
541
17.9k
                res = it->second;
542
17.9k
                return 0;
543
17.9k
            }
544
24.4k
        }
545
        // Get schema from kv
546
        // TODO(plat1ko): Single flight
547
6.54k
        std::unique_ptr<Transaction> txn;
548
6.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
549
6.54k
        if (err != TxnErrorCode::TXN_OK) {
550
0
            LOG(WARNING) << "failed to create txn, err=" << err;
551
0
            return -1;
552
0
        }
553
6.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
554
6.54k
        ValueBuf val_buf;
555
6.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
556
6.54k
        if (err != TxnErrorCode::TXN_OK) {
557
500
            LOG(WARNING) << "failed to get schema, err=" << err;
558
500
            return static_cast<int>(err);
559
500
        }
560
6.04k
        doris::TabletSchemaCloudPB schema;
561
6.04k
        if (!parse_schema_value(val_buf, &schema)) {
562
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
563
0
            return -1;
564
0
        }
565
6.04k
        if (schema.index_size() > 0) {
566
4.25k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
567
4.25k
            if (schema.has_inverted_index_storage_format()) {
568
4.24k
                index_format = schema.inverted_index_storage_format();
569
4.24k
            }
570
4.25k
            res.first = index_format;
571
4.25k
            res.second.reserve(schema.index_size());
572
10.7k
            for (auto& i : schema.index()) {
573
10.7k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
574
10.7k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
575
10.7k
                }
576
10.7k
            }
577
4.25k
        }
578
6.04k
        insert(index_id, schema_version, res);
579
6.04k
        return 0;
580
6.04k
    }
581
582
    // Empty `ids` means this schema has no inverted index
583
6.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
584
6.04k
        if (index_info.second.empty()) {
585
1.79k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
586
1.79k
            std::lock_guard lock(mtx_);
587
1.79k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
588
4.25k
        } else {
589
4.25k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
590
4.25k
            std::lock_guard lock(mtx_);
591
4.25k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
592
4.25k
        }
593
6.04k
    }
594
595
private:
596
    std::string instance_id_;
597
    std::shared_ptr<TxnKv> txn_kv_;
598
599
    std::mutex mtx_;
600
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
601
    struct HashOfKey {
602
58.9k
        size_t operator()(const Key& key) const {
603
58.9k
            size_t seed = 0;
604
58.9k
            seed = std::hash<int64_t> {}(key.first);
605
58.9k
            seed = std::hash<int32_t> {}(key.second);
606
58.9k
            return seed;
607
58.9k
        }
608
    };
609
    // <index_id, schema_version> -> inverted_index_ids
610
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
611
    // Store <index_id, schema_version> of schema which doesn't have inverted index
612
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
613
};
614
615
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
616
                                   RecyclerThreadPoolGroup thread_pool_group,
617
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
618
        : txn_kv_(std::move(txn_kv)),
619
          instance_id_(instance.instance_id()),
620
          instance_info_(instance),
621
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
622
          _thread_pool_group(std::move(thread_pool_group)),
623
          txn_lazy_committer_(std::move(txn_lazy_committer)),
624
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
625
139
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
626
139
    delete_bitmap_lock_white_list_->init();
627
139
    resource_mgr_->init();
628
629
139
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
630
631
    // Since the recycler's resource manager could not be notified when instance info changes,
632
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
633
139
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
634
139
};
635
636
139
InstanceRecycler::~InstanceRecycler() = default;
637
638
121
int InstanceRecycler::init_obj_store_accessors() {
639
121
    for (const auto& obj_info : instance_info_.obj_info()) {
640
79
#ifdef UNIT_TEST
641
79
        auto accessor = std::make_shared<MockAccessor>();
642
#else
643
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
644
        if (!s3_conf) {
645
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
646
            return -1;
647
        }
648
649
        std::shared_ptr<S3Accessor> accessor;
650
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
651
        if (ret != 0) {
652
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
653
                         << " resource_id=" << obj_info.id();
654
            return ret;
655
        }
656
#endif
657
79
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
658
79
    }
659
660
121
    return 0;
661
121
}
662
663
121
int InstanceRecycler::init_storage_vault_accessors() {
664
121
    if (instance_info_.resource_ids().empty()) {
665
114
        return 0;
666
114
    }
667
668
7
    FullRangeGetOptions opts(txn_kv_);
669
7
    opts.prefetch = true;
670
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
671
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
672
673
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
674
18
        auto [k, v] = *kv;
675
18
        StorageVaultPB vault;
676
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
677
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
678
0
            return -1;
679
0
        }
680
18
        std::string recycler_storage_vault_white_list = accumulate(
681
18
                config::recycler_storage_vault_white_list.begin(),
682
18
                config::recycler_storage_vault_white_list.end(), std::string(),
683
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
683
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
684
18
        LOG_INFO("config::recycler_storage_vault_white_list")
685
18
                .tag("", recycler_storage_vault_white_list);
686
18
        if (!config::recycler_storage_vault_white_list.empty()) {
687
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
688
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
689
8
                it == config::recycler_storage_vault_white_list.end()) {
690
2
                LOG_WARNING(
691
2
                        "failed to init accessor for vault because this vault is not in "
692
2
                        "config::recycler_storage_vault_white_list. ")
693
2
                        .tag(" vault name:", vault.name())
694
2
                        .tag(" config::recycler_storage_vault_white_list:",
695
2
                             recycler_storage_vault_white_list);
696
2
                continue;
697
2
            }
698
8
        }
699
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
700
16
                                 &accessor_map_, &vault);
701
16
        if (vault.has_hdfs_info()) {
702
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
703
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
704
9
            int ret = accessor->init();
705
9
            if (ret != 0) {
706
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
707
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
708
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
709
4
                continue;
710
4
            }
711
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
712
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
713
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
714
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
715
#else
716
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
717
                       << "but HDFS storage vaults were detected";
718
#endif
719
7
        } else if (vault.has_obj_info()) {
720
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
721
7
            if (!s3_conf) {
722
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
723
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
724
1
                continue;
725
1
            }
726
727
6
            std::shared_ptr<S3Accessor> accessor;
728
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
729
6
            if (ret != 0) {
730
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
731
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
732
0
                             << " ret=" << ret
733
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
734
0
                continue;
735
0
            }
736
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
737
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
738
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
739
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
740
6
        }
741
16
    }
742
743
7
    if (!it->is_valid()) {
744
0
        LOG_WARNING("failed to get storage vault kv");
745
0
        return -1;
746
0
    }
747
748
7
    if (accessor_map_.empty()) {
749
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
750
1
        return -2;
751
1
    }
752
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
753
6
             instance_id_);
754
755
6
    return 0;
756
7
}
757
758
122
int InstanceRecycler::init() {
759
122
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
760
122
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
761
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
762
1
        return 0;
763
1
    }
764
765
121
    int ret = init_obj_store_accessors();
766
121
    if (ret != 0) {
767
0
        return ret;
768
0
    }
769
770
121
    return init_storage_vault_accessors();
771
121
}
772
773
template <typename... Func>
774
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
120
    return [funcs...]() {
776
120
        return [](std::initializer_list<int> ret_vals) {
777
120
            int i = 0;
778
140
            for (int ret : ret_vals) {
779
140
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
140
            }
783
120
            return i;
784
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
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
20
            for (int ret : ret_vals) {
779
20
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
20
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
20
            for (int ret : ret_vals) {
779
20
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
20
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
0
                    i = ret;
781
0
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
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
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
774
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
775
10
    return [funcs...]() {
776
10
        return [](std::initializer_list<int> ret_vals) {
777
10
            int i = 0;
778
10
            for (int ret : ret_vals) {
779
10
                if (ret != 0) {
780
10
                    i = ret;
781
10
                }
782
10
            }
783
10
            return i;
784
10
        }({funcs()...});
785
10
    };
786
10
}
787
788
11
int InstanceRecycler::do_recycle() {
789
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
790
11
    tablet_metrics_context_.reset();
791
11
    segment_metrics_context_.reset();
792
11
    DORIS_CLOUD_DEFER {
793
11
        tablet_metrics_context_.finish_report();
794
11
        segment_metrics_context_.finish_report();
795
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
792
11
    DORIS_CLOUD_DEFER {
793
11
        tablet_metrics_context_.finish_report();
794
11
        segment_metrics_context_.finish_report();
795
11
    };
796
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
797
1
        int res = recycle_cluster_snapshots();
798
1
        if (res != 0) {
799
0
            return -1;
800
0
        }
801
1
        return recycle_deleted_instance();
802
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
803
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
804
10
                                        fmt::format("instance id {}", instance_id_),
805
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
805
120
                                        [](int r) { return r != 0; });
806
10
        sync_executor
807
10
                .add(task_wrapper(
808
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
808
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
809
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
809
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
810
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
811
                                   // becase they may both recycle the same set of tablets
812
                        // recycle dropped table or idexes(mv, rollup)
813
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
813
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
814
                        // recycle dropped partitions
815
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
815
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
816
10
                .add(task_wrapper(
817
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
817
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
818
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
818
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
819
10
                .add(task_wrapper(
820
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
820
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
822
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
823
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
823
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
824
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
824
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
825
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
825
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
826
10
                .add(task_wrapper(
827
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
827
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
828
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
828
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
829
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
829
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
830
10
        bool finished = true;
831
10
        std::vector<int> rets = sync_executor.when_all(&finished);
832
120
        for (int ret : rets) {
833
120
            if (ret != 0) {
834
0
                return ret;
835
0
            }
836
120
        }
837
10
        return finished ? 0 : -1;
838
10
    } else {
839
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
840
0
                     << " instance_id=" << instance_id_;
841
0
        return -1;
842
0
    }
843
11
}
844
845
/**
846
* 1. delete all remote data
847
* 2. delete all kv
848
* 3. remove instance kv
849
*/
850
13
int InstanceRecycler::recycle_deleted_instance() {
851
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
852
853
13
    int ret = 0;
854
13
    auto start_time = steady_clock::now();
855
13
    const auto recycle_state = instance_info_.recycle_state();
856
857
13
    DORIS_CLOUD_DEFER {
858
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
859
13
        if (ret != 0) {
860
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
861
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
862
0
                         << "s, instance_id=" << instance_id_;
863
13
        } else if (recycle_state ==
864
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
865
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
866
4
                      << "s, instance_id=" << instance_id_;
867
9
        } else {
868
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
869
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
870
9
                      << "s, instance_id=" << instance_id_;
871
9
        }
872
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
857
13
    DORIS_CLOUD_DEFER {
858
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
859
13
        if (ret != 0) {
860
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
861
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
862
0
                         << "s, instance_id=" << instance_id_;
863
13
        } else if (recycle_state ==
864
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
865
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
866
4
                      << "s, instance_id=" << instance_id_;
867
9
        } else {
868
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
869
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
870
9
                      << "s, instance_id=" << instance_id_;
871
9
        }
872
13
    };
873
874
13
    switch (recycle_state) {
875
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
876
6
        ret = recycle_deleted_instance_data();
877
6
        break;
878
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
879
3
        ret = recycle_deleted_instance_metadata();
880
3
        break;
881
4
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
882
4
        ret = remove_instance_key();
883
4
        break;
884
0
    default:
885
0
        LOG_WARNING("invalid instance recycle state")
886
0
                .tag("instance_id", instance_id_)
887
0
                .tag("recycle_state", instance_info_.recycle_state());
888
0
        ret = -1;
889
0
        break;
890
13
    }
891
892
13
    return ret;
893
13
}
894
895
6
int InstanceRecycler::recycle_deleted_instance_data() {
896
6
    int ret = 0;
897
898
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
899
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
900
6
        int res = recycle_tmp_rowsets();
901
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
902
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
903
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
904
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
905
            // and cannot be recycled.
906
0
            res = recycle_tmp_rowsets();
907
0
        }
908
6
        return res;
909
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
899
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
900
6
        int res = recycle_tmp_rowsets();
901
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
902
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
903
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
904
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
905
            // and cannot be recycled.
906
0
            res = recycle_tmp_rowsets();
907
0
        }
908
6
        return res;
909
6
    };
910
911
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
912
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
913
0
        return -1;
914
0
    }
915
916
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
917
6
    if (recycle_versioned_rowsets() != 0) {
918
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
919
0
        return -1;
920
0
    }
921
922
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
923
6
    if (recycle_operation_logs() != 0) {
924
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
925
0
        return -1;
926
0
    }
927
928
    // Step 4: Check if there are still cluster snapshots
929
6
    bool has_snapshots = false;
930
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
931
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
932
0
        return -1;
933
6
    } else if (has_snapshots) {
934
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
935
1
        return 0;
936
1
    }
937
938
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
939
5
                            instance_info().snapshot_switch_status() !=
940
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
941
5
    if (snapshot_enabled) {
942
1
        bool has_unrecycled_rowsets = false;
943
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
944
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
945
0
            return -1;
946
1
        } else if (has_unrecycled_rowsets) {
947
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
948
0
                    .tag("instance_id", instance_id_);
949
0
            return ret;
950
0
        }
951
4
    } else { // delete all remote data if snapshot is disabled
952
4
        for (auto& [_, accessor] : accessor_map_) {
953
4
            if (stopped()) {
954
0
                return ret;
955
0
            }
956
957
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
958
4
            int del_ret = accessor->delete_all();
959
4
            if (del_ret == 0) {
960
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
961
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
962
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
963
                // so the recycling has been successful.
964
0
                ret = -1;
965
0
            }
966
4
        }
967
968
4
        if (ret != 0) {
969
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
970
0
            return ret;
971
0
        }
972
4
    }
973
974
5
    if (update_instance_recycle_state(
975
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
976
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
977
0
        return -1;
978
0
    }
979
980
5
    return 0;
981
5
}
982
983
3
int InstanceRecycler::recycle_deleted_instance_metadata() {
984
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
985
3
    if (instance_info_.has_successor_instance_id() &&
986
3
        !instance_info_.successor_instance_id().empty()) {
987
0
        std::string key = instance_key(instance_info_.successor_instance_id());
988
0
        std::unique_ptr<Transaction> txn;
989
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
990
0
        if (err != TxnErrorCode::TXN_OK) {
991
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
992
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
993
0
                         << " err=" << err;
994
0
            return -1;
995
0
        }
996
997
0
        std::string value;
998
0
        err = txn->get(key, &value);
999
0
        if (err == TxnErrorCode::TXN_OK) {
1000
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
1001
0
                      << " instance_id=" << instance_id_
1002
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
1003
0
            return 0;
1004
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1005
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1006
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1007
0
                         << " err=" << err;
1008
0
            return -1;
1009
0
        }
1010
0
    }
1011
1012
    // delete all kv
1013
3
    std::unique_ptr<Transaction> txn;
1014
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1015
3
    if (err != TxnErrorCode::TXN_OK) {
1016
0
        LOG(WARNING) << "failed to create txn";
1017
0
        return -1;
1018
0
    }
1019
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1020
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1021
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
1022
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1023
3
    txn->remove(start_txn_key, end_txn_key);
1024
3
    std::string start_version_key = version_key_prefix(instance_id_);
1025
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1026
3
    txn->remove(start_version_key, end_version_key);
1027
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
1028
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1029
3
    txn->remove(start_meta_key, end_meta_key);
1030
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1031
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1032
3
    txn->remove(start_recycle_key, end_recycle_key);
1033
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1034
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1035
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1036
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
1037
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1038
3
    txn->remove(start_copy_key, end_copy_key);
1039
    // should not remove job key range, because we need to reserve job recycle kv
1040
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1041
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1042
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1043
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1044
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1045
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1046
3
    std::string start_vault_key = storage_vault_key(key_info0);
1047
3
    std::string end_vault_key = storage_vault_key(key_info1);
1048
3
    txn->remove(start_vault_key, end_vault_key);
1049
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1050
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1051
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1052
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1053
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1054
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1055
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1056
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1057
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1058
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1059
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1060
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1061
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1062
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1063
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1064
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1065
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1066
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1067
1068
    // Updating the recycle state also commits this transaction, making the metadata deletions
1069
    // and state transition atomic.
1070
3
    if (update_instance_recycle_state(
1071
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1072
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1073
0
        return -1;
1074
0
    }
1075
1076
3
    return 0;
1077
3
}
1078
1079
4
int InstanceRecycler::remove_instance_key() {
1080
4
    std::unique_ptr<Transaction> txn;
1081
4
    std::string key = instance_key(instance_info_.instance_id());
1082
4
    std::string value;
1083
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1084
4
    if (err != TxnErrorCode::TXN_OK) {
1085
0
        LOG(WARNING) << "failed to create txn";
1086
0
        return -1;
1087
0
    }
1088
1089
4
    err = txn->get(key, &value);
1090
4
    if (err != TxnErrorCode::TXN_OK) {
1091
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1092
0
                     << ", err=" << err;
1093
0
        return -1;
1094
0
    }
1095
1096
4
    InstanceInfoPB instance;
1097
4
    if (!instance.ParseFromString(value)) {
1098
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1099
0
        return -1;
1100
0
    }
1101
1102
4
    if (instance.status() != InstanceInfoPB::DELETED) {
1103
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1104
0
                     << instance_id_ << ", status=" << instance.status();
1105
0
        return -1;
1106
0
    }
1107
1108
4
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1109
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1110
0
                     << instance_id_
1111
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1112
0
                     << ", expected_state="
1113
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1114
0
        return -1;
1115
0
    }
1116
1117
4
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1118
4
    txn->remove(key);
1119
4
    err = txn->commit();
1120
4
    if (err != TxnErrorCode::TXN_OK) {
1121
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1122
0
                     << " err=" << err;
1123
0
        return -1;
1124
0
    }
1125
4
    return 0;
1126
4
}
1127
1128
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1129
7
                                                    InstanceRecycleState target_state) {
1130
7
    std::unique_ptr<Transaction> txn;
1131
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1132
7
    if (err != TxnErrorCode::TXN_OK) {
1133
0
        LOG(WARNING) << "failed to create txn";
1134
0
        return -1;
1135
0
    }
1136
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1137
7
}
1138
1139
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1140
                                                    InstanceRecycleState target_state,
1141
10
                                                    Transaction* txn) {
1142
10
    const bool valid_transition =
1143
10
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1144
10
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1145
10
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1146
4
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1147
1148
10
    if (!valid_transition) {
1149
1
        LOG_WARNING("invalid instance recycled state transition")
1150
1
                .tag("instance_id", instance_id_)
1151
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1152
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1153
1
        return -1;
1154
1
    }
1155
1156
9
    std::string key = instance_key({instance_id_});
1157
9
    std::string value;
1158
9
    TxnErrorCode err = txn->get(key, &value);
1159
9
    if (err != TxnErrorCode::TXN_OK) {
1160
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1161
0
                .tag("instance_id", instance_id_)
1162
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1163
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1164
0
                .tag("err", err);
1165
0
        return -1;
1166
0
    }
1167
1168
9
    InstanceInfoPB instance;
1169
9
    if (!instance.ParseFromString(value)) {
1170
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1171
0
                .tag("instance_id", instance_id_)
1172
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1173
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1174
0
        return -1;
1175
0
    }
1176
9
    if (instance.status() != InstanceInfoPB::DELETED) {
1177
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1178
0
                .tag("instance_id", instance_id_)
1179
0
                .tag("status", instance.status())
1180
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1181
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1182
0
        return -1;
1183
0
    }
1184
9
    if (instance.recycle_state() != current_state) {
1185
1
        LOG_WARNING("instance recycled state changed before update")
1186
1
                .tag("instance_id", instance_id_)
1187
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1188
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1189
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1190
1
        return -1;
1191
1
    }
1192
1193
8
    instance.set_recycle_state(target_state);
1194
8
    instance.set_recycle_state_update_time_ms(
1195
8
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1196
8
    if (!instance.SerializeToString(&value)) {
1197
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1198
0
                .tag("instance_id", instance_id_)
1199
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1200
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1201
0
        return -1;
1202
0
    }
1203
1204
8
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1205
8
    txn->put(key, value);
1206
8
    err = txn->commit();
1207
8
    if (err != TxnErrorCode::TXN_OK) {
1208
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1209
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1210
0
        return -1;
1211
0
    }
1212
1213
8
    instance_info_.Swap(&instance);
1214
8
    LOG_INFO("updated instance recycled state")
1215
8
            .tag("instance_id", instance_id_)
1216
8
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1217
8
    return 0;
1218
8
}
1219
1220
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1221
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1222
9
    if (exists == nullptr) {
1223
0
        return -1;
1224
0
    }
1225
9
    *exists = false;
1226
1227
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1228
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1229
9
    std::string scan_begin = begin;
1230
1231
9
    while (true) {
1232
9
        std::unique_ptr<RangeGetIterator> it_range;
1233
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1234
9
        if (get_ret < 0) {
1235
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1236
0
                    .tag("instance_id", instance_id_)
1237
0
                    .tag("tablet_id", tablet_id)
1238
0
                    .tag("ret", get_ret);
1239
0
            return -1;
1240
0
        }
1241
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1242
6
            return 0;
1243
6
        }
1244
1245
3
        std::string last_key;
1246
3
        while (it_range->has_next()) {
1247
3
            auto [k, v] = it_range->next();
1248
3
            last_key.assign(k.data(), k.size());
1249
3
            doris::RowsetMetaCloudPB rowset_meta;
1250
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1251
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1252
0
                        .tag("instance_id", instance_id_)
1253
0
                        .tag("tablet_id", tablet_id)
1254
0
                        .tag("key", hex(k));
1255
0
                continue;
1256
0
            }
1257
3
            if (stats) {
1258
3
                ++stats->rowset_scan_count;
1259
3
            }
1260
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1261
3
                *exists = true;
1262
3
                return 0;
1263
3
            }
1264
3
        }
1265
1266
0
        if (!it_range->more()) {
1267
0
            return 0;
1268
0
        }
1269
1270
        // Continue scanning from the next key to keep each transaction short.
1271
0
        scan_begin = std::move(last_key);
1272
0
        scan_begin.push_back('\x00');
1273
0
    }
1274
9
}
1275
1276
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1277
                                                          const std::string& rowset_id,
1278
                                                          int64_t txn_id, bool* recycle_exists,
1279
11
                                                          bool* tmp_exists) {
1280
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1281
0
        return -1;
1282
0
    }
1283
11
    *recycle_exists = false;
1284
11
    *tmp_exists = false;
1285
1286
11
    if (txn_id <= 0) {
1287
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1288
0
                .tag("instance_id", instance_id_)
1289
0
                .tag("tablet_id", tablet_id)
1290
0
                .tag("rowset_id", rowset_id)
1291
0
                .tag("txn_id", txn_id);
1292
0
        return -1;
1293
0
    }
1294
1295
11
    std::unique_ptr<Transaction> txn;
1296
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1297
11
    if (err != TxnErrorCode::TXN_OK) {
1298
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1299
0
                .tag("instance_id", instance_id_)
1300
0
                .tag("tablet_id", tablet_id)
1301
0
                .tag("rowset_id", rowset_id)
1302
0
                .tag("txn_id", txn_id)
1303
0
                .tag("err", err);
1304
0
        return -1;
1305
0
    }
1306
1307
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1308
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1309
11
    if (ret == TxnErrorCode::TXN_OK) {
1310
1
        *recycle_exists = true;
1311
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1312
0
        LOG_WARNING("failed to check recycle rowset existence")
1313
0
                .tag("instance_id", instance_id_)
1314
0
                .tag("tablet_id", tablet_id)
1315
0
                .tag("rowset_id", rowset_id)
1316
0
                .tag("key", hex(recycle_key))
1317
0
                .tag("err", ret);
1318
0
        return -1;
1319
0
    }
1320
1321
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1322
11
    ret = key_exists(txn.get(), tmp_key, true);
1323
11
    if (ret == TxnErrorCode::TXN_OK) {
1324
1
        *tmp_exists = true;
1325
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1326
0
        LOG_WARNING("failed to check tmp rowset existence")
1327
0
                .tag("instance_id", instance_id_)
1328
0
                .tag("tablet_id", tablet_id)
1329
0
                .tag("txn_id", txn_id)
1330
0
                .tag("key", hex(tmp_key))
1331
0
                .tag("err", ret);
1332
0
        return -1;
1333
0
    }
1334
1335
11
    return 0;
1336
11
}
1337
1338
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1339
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1340
8
    if (!hint.empty()) {
1341
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1342
8
            return {hint, it->second};
1343
8
        }
1344
8
    }
1345
1346
0
    return {"", nullptr};
1347
8
}
1348
1349
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1350
                                               const std::string& packed_file_path,
1351
3
                                               PackedFileRecycleStats* stats) {
1352
3
    bool local_changed = false;
1353
3
    int64_t left_num = 0;
1354
3
    int64_t left_bytes = 0;
1355
3
    bool all_small_files_confirmed = true;
1356
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1357
1358
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1359
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1360
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1361
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1362
14
        LOG_INFO("packed slice correction status")
1363
14
                .tag("instance_id", instance_id_)
1364
14
                .tag("packed_file_path", packed_file_path)
1365
14
                .tag("small_file_path", file.path())
1366
14
                .tag("tablet_id", tablet_id)
1367
14
                .tag("rowset_id", rowset_id)
1368
14
                .tag("txn_id", txn_id)
1369
14
                .tag("size", file.size())
1370
14
                .tag("deleted", file.deleted())
1371
14
                .tag("corrected", file.corrected())
1372
14
                .tag("confirmed_this_round", confirmed_this_round);
1373
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
1358
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1359
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1360
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1361
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1362
14
        LOG_INFO("packed slice correction status")
1363
14
                .tag("instance_id", instance_id_)
1364
14
                .tag("packed_file_path", packed_file_path)
1365
14
                .tag("small_file_path", file.path())
1366
14
                .tag("tablet_id", tablet_id)
1367
14
                .tag("rowset_id", rowset_id)
1368
14
                .tag("txn_id", txn_id)
1369
14
                .tag("size", file.size())
1370
14
                .tag("deleted", file.deleted())
1371
14
                .tag("corrected", file.corrected())
1372
14
                .tag("confirmed_this_round", confirmed_this_round);
1373
14
    };
1374
1375
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1376
14
        auto* small_file = packed_info->mutable_slices(i);
1377
14
        if (small_file->deleted()) {
1378
3
            log_small_file_status(*small_file, small_file->corrected());
1379
3
            continue;
1380
3
        }
1381
1382
11
        if (small_file->corrected()) {
1383
0
            left_num++;
1384
0
            left_bytes += small_file->size();
1385
0
            log_small_file_status(*small_file, true);
1386
0
            continue;
1387
0
        }
1388
1389
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1390
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1391
0
                    .tag("instance_id", instance_id_)
1392
0
                    .tag("small_file_path", small_file->path())
1393
0
                    .tag("index", i);
1394
0
            return -1;
1395
0
        }
1396
1397
11
        int64_t tablet_id = small_file->tablet_id();
1398
11
        const std::string& rowset_id = small_file->rowset_id();
1399
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1400
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1401
0
                    .tag("instance_id", instance_id_)
1402
0
                    .tag("small_file_path", small_file->path())
1403
0
                    .tag("index", i)
1404
0
                    .tag("tablet_id", tablet_id)
1405
0
                    .tag("rowset_id", rowset_id)
1406
0
                    .tag("has_txn_id", small_file->has_txn_id())
1407
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1408
0
            return -1;
1409
0
        }
1410
11
        int64_t txn_id = small_file->txn_id();
1411
11
        bool recycle_exists = false;
1412
11
        bool tmp_exists = false;
1413
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1414
11
                                                &tmp_exists) != 0) {
1415
0
            return -1;
1416
0
        }
1417
1418
11
        bool small_file_confirmed = false;
1419
11
        if (tmp_exists) {
1420
1
            left_num++;
1421
1
            left_bytes += small_file->size();
1422
1
            small_file_confirmed = true;
1423
10
        } else if (recycle_exists) {
1424
1
            left_num++;
1425
1
            left_bytes += small_file->size();
1426
            // keep small_file_confirmed=false so the packed file remains uncorrected
1427
9
        } else {
1428
9
            bool rowset_exists = false;
1429
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1430
0
                return -1;
1431
0
            }
1432
1433
9
            if (!rowset_exists) {
1434
6
                if (!small_file->deleted()) {
1435
6
                    small_file->set_deleted(true);
1436
6
                    local_changed = true;
1437
6
                }
1438
6
                if (!small_file->corrected()) {
1439
6
                    small_file->set_corrected(true);
1440
6
                    local_changed = true;
1441
6
                }
1442
6
                small_file_confirmed = true;
1443
6
            } else {
1444
3
                left_num++;
1445
3
                left_bytes += small_file->size();
1446
3
                small_file_confirmed = true;
1447
3
            }
1448
9
        }
1449
1450
11
        if (!small_file_confirmed) {
1451
1
            all_small_files_confirmed = false;
1452
1
        }
1453
1454
11
        if (small_file->corrected() != small_file_confirmed) {
1455
4
            small_file->set_corrected(small_file_confirmed);
1456
4
            local_changed = true;
1457
4
        }
1458
1459
11
        log_small_file_status(*small_file, small_file_confirmed);
1460
11
    }
1461
1462
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1463
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1464
3
        local_changed = true;
1465
3
    }
1466
3
    if (packed_info->ref_cnt() != left_num) {
1467
3
        auto old_ref_cnt = packed_info->ref_cnt();
1468
3
        packed_info->set_ref_cnt(left_num);
1469
3
        LOG_INFO("corrected packed file ref count")
1470
3
                .tag("instance_id", instance_id_)
1471
3
                .tag("resource_id", packed_info->resource_id())
1472
3
                .tag("packed_file_path", packed_file_path)
1473
3
                .tag("old_ref_cnt", old_ref_cnt)
1474
3
                .tag("new_ref_cnt", left_num);
1475
3
        local_changed = true;
1476
3
    }
1477
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1478
2
        packed_info->set_corrected(all_small_files_confirmed);
1479
2
        local_changed = true;
1480
2
    }
1481
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1482
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1483
1
        local_changed = true;
1484
1
    }
1485
1486
3
    if (changed != nullptr) {
1487
3
        *changed = local_changed;
1488
3
    }
1489
3
    return 0;
1490
3
}
1491
1492
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1493
                                                 const std::string& packed_file_path,
1494
4
                                                 PackedFileRecycleStats* stats) {
1495
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1496
4
    bool correction_ok = false;
1497
4
    cloud::PackedFileInfoPB packed_info;
1498
1499
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1500
4
        if (stopped()) {
1501
0
            LOG_WARNING("recycler stopped before processing packed file")
1502
0
                    .tag("instance_id", instance_id_)
1503
0
                    .tag("packed_file_path", packed_file_path)
1504
0
                    .tag("attempt", attempt);
1505
0
            return -1;
1506
0
        }
1507
1508
4
        std::unique_ptr<Transaction> txn;
1509
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1510
4
        if (err != TxnErrorCode::TXN_OK) {
1511
0
            LOG_WARNING("failed to create txn when processing packed file")
1512
0
                    .tag("instance_id", instance_id_)
1513
0
                    .tag("packed_file_path", packed_file_path)
1514
0
                    .tag("attempt", attempt)
1515
0
                    .tag("err", err);
1516
0
            return -1;
1517
0
        }
1518
1519
4
        std::string packed_val;
1520
4
        err = txn->get(packed_key, &packed_val);
1521
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1522
0
            return 0;
1523
0
        }
1524
4
        if (err != TxnErrorCode::TXN_OK) {
1525
0
            LOG_WARNING("failed to get packed file kv")
1526
0
                    .tag("instance_id", instance_id_)
1527
0
                    .tag("packed_file_path", packed_file_path)
1528
0
                    .tag("attempt", attempt)
1529
0
                    .tag("err", err);
1530
0
            return -1;
1531
0
        }
1532
1533
4
        if (!packed_info.ParseFromString(packed_val)) {
1534
0
            LOG_WARNING("failed to parse packed file info")
1535
0
                    .tag("instance_id", instance_id_)
1536
0
                    .tag("packed_file_path", packed_file_path)
1537
0
                    .tag("attempt", attempt);
1538
0
            return -1;
1539
0
        }
1540
1541
4
        int64_t now_sec = ::time(nullptr);
1542
4
        bool corrected = packed_info.corrected();
1543
4
        bool due = config::force_immediate_recycle ||
1544
4
                   now_sec - packed_info.created_at_sec() >=
1545
4
                           config::packed_file_correction_delay_seconds;
1546
1547
4
        if (!corrected && due) {
1548
3
            bool changed = false;
1549
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1550
0
                LOG_WARNING("correct_packed_file_info failed")
1551
0
                        .tag("instance_id", instance_id_)
1552
0
                        .tag("packed_file_path", packed_file_path)
1553
0
                        .tag("attempt", attempt);
1554
0
                return -1;
1555
0
            }
1556
3
            if (changed) {
1557
3
                std::string updated;
1558
3
                if (!packed_info.SerializeToString(&updated)) {
1559
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1560
0
                            .tag("instance_id", instance_id_)
1561
0
                            .tag("packed_file_path", packed_file_path)
1562
0
                            .tag("attempt", attempt);
1563
0
                    return -1;
1564
0
                }
1565
3
                txn->put(packed_key, updated);
1566
3
                err = txn->commit();
1567
3
                if (err == TxnErrorCode::TXN_OK) {
1568
3
                    if (stats) {
1569
3
                        ++stats->num_corrected;
1570
3
                    }
1571
3
                } else {
1572
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1573
0
                        LOG_WARNING(
1574
0
                                "failed to commit correction for packed file due to conflict, "
1575
0
                                "retrying")
1576
0
                                .tag("instance_id", instance_id_)
1577
0
                                .tag("packed_file_path", packed_file_path)
1578
0
                                .tag("attempt", attempt);
1579
0
                        sleep_for_packed_file_retry();
1580
0
                        packed_info.Clear();
1581
0
                        continue;
1582
0
                    }
1583
0
                    LOG_WARNING("failed to commit correction for packed file")
1584
0
                            .tag("instance_id", instance_id_)
1585
0
                            .tag("packed_file_path", packed_file_path)
1586
0
                            .tag("attempt", attempt)
1587
0
                            .tag("err", err);
1588
0
                    return -1;
1589
0
                }
1590
3
            }
1591
3
        }
1592
1593
4
        correction_ok = true;
1594
4
        break;
1595
4
    }
1596
1597
4
    if (!correction_ok) {
1598
0
        return -1;
1599
0
    }
1600
1601
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1602
4
          packed_info.ref_cnt() == 0)) {
1603
3
        return 0;
1604
3
    }
1605
1606
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1607
0
        LOG_WARNING("packed file missing resource id when recycling")
1608
0
                .tag("instance_id", instance_id_)
1609
0
                .tag("packed_file_path", packed_file_path);
1610
0
        return -1;
1611
0
    }
1612
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1613
1
    if (!accessor) {
1614
0
        LOG_WARNING("no accessor available to delete packed file")
1615
0
                .tag("instance_id", instance_id_)
1616
0
                .tag("packed_file_path", packed_file_path)
1617
0
                .tag("resource_id", packed_info.resource_id());
1618
0
        return -1;
1619
0
    }
1620
1
    int del_ret = accessor->delete_file(packed_file_path);
1621
1
    if (del_ret != 0 && del_ret != 1) {
1622
0
        LOG_WARNING("failed to delete packed file")
1623
0
                .tag("instance_id", instance_id_)
1624
0
                .tag("packed_file_path", packed_file_path)
1625
0
                .tag("resource_id", resource_id)
1626
0
                .tag("ret", del_ret);
1627
0
        return -1;
1628
0
    }
1629
1
    if (del_ret == 1) {
1630
0
        LOG_INFO("packed file already removed")
1631
0
                .tag("instance_id", instance_id_)
1632
0
                .tag("packed_file_path", packed_file_path)
1633
0
                .tag("resource_id", resource_id);
1634
1
    } else {
1635
1
        LOG_INFO("deleted packed file")
1636
1
                .tag("instance_id", instance_id_)
1637
1
                .tag("packed_file_path", packed_file_path)
1638
1
                .tag("resource_id", resource_id);
1639
1
    }
1640
1641
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1642
1
        std::unique_ptr<Transaction> del_txn;
1643
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1644
1
        if (err != TxnErrorCode::TXN_OK) {
1645
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1646
0
                    .tag("instance_id", instance_id_)
1647
0
                    .tag("packed_file_path", packed_file_path)
1648
0
                    .tag("del_attempt", del_attempt)
1649
0
                    .tag("err", err);
1650
0
            return -1;
1651
0
        }
1652
1653
1
        std::string latest_val;
1654
1
        err = del_txn->get(packed_key, &latest_val);
1655
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1656
0
            return 0;
1657
0
        }
1658
1
        if (err != TxnErrorCode::TXN_OK) {
1659
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1660
0
                    .tag("instance_id", instance_id_)
1661
0
                    .tag("packed_file_path", packed_file_path)
1662
0
                    .tag("del_attempt", del_attempt)
1663
0
                    .tag("err", err);
1664
0
            return -1;
1665
0
        }
1666
1667
1
        cloud::PackedFileInfoPB latest_info;
1668
1
        if (!latest_info.ParseFromString(latest_val)) {
1669
0
            LOG_WARNING("failed to parse packed file info before removal")
1670
0
                    .tag("instance_id", instance_id_)
1671
0
                    .tag("packed_file_path", packed_file_path)
1672
0
                    .tag("del_attempt", del_attempt);
1673
0
            return -1;
1674
0
        }
1675
1676
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1677
1
              latest_info.ref_cnt() == 0)) {
1678
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1679
0
                    .tag("instance_id", instance_id_)
1680
0
                    .tag("packed_file_path", packed_file_path)
1681
0
                    .tag("del_attempt", del_attempt);
1682
0
            return 0;
1683
0
        }
1684
1685
1
        del_txn->remove(packed_key);
1686
1
        err = del_txn->commit();
1687
1
        if (err == TxnErrorCode::TXN_OK) {
1688
1
            if (stats) {
1689
1
                ++stats->num_deleted;
1690
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1691
1
                                        static_cast<int64_t>(latest_val.size());
1692
1
                if (del_ret == 0 || del_ret == 1) {
1693
1
                    ++stats->num_object_deleted;
1694
1
                    int64_t object_size = latest_info.total_slice_bytes();
1695
1
                    if (object_size <= 0) {
1696
0
                        object_size = packed_info.total_slice_bytes();
1697
0
                    }
1698
1
                    stats->bytes_object_deleted += object_size;
1699
1
                }
1700
1
            }
1701
1
            LOG_INFO("removed packed file metadata")
1702
1
                    .tag("instance_id", instance_id_)
1703
1
                    .tag("packed_file_path", packed_file_path);
1704
1
            return 0;
1705
1
        }
1706
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1707
0
            if (del_attempt >= max_retry_times) {
1708
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1709
0
                        .tag("instance_id", instance_id_)
1710
0
                        .tag("packed_file_path", packed_file_path)
1711
0
                        .tag("del_attempt", del_attempt);
1712
0
                return -1;
1713
0
            }
1714
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1715
0
                    .tag("instance_id", instance_id_)
1716
0
                    .tag("packed_file_path", packed_file_path)
1717
0
                    .tag("del_attempt", del_attempt);
1718
0
            sleep_for_packed_file_retry();
1719
0
            continue;
1720
0
        }
1721
0
        LOG_WARNING("failed to remove packed file kv")
1722
0
                .tag("instance_id", instance_id_)
1723
0
                .tag("packed_file_path", packed_file_path)
1724
0
                .tag("del_attempt", del_attempt)
1725
0
                .tag("err", err);
1726
0
        return -1;
1727
0
    }
1728
1729
0
    return -1;
1730
1
}
1731
1732
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1733
4
                                            PackedFileRecycleStats* stats, int* ret) {
1734
4
    if (stats) {
1735
4
        ++stats->num_scanned;
1736
4
    }
1737
4
    std::string packed_file_path;
1738
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1739
0
        LOG_WARNING("failed to decode packed file key")
1740
0
                .tag("instance_id", instance_id_)
1741
0
                .tag("key", hex(key));
1742
0
        if (stats) {
1743
0
            ++stats->num_failed;
1744
0
        }
1745
0
        if (ret) {
1746
0
            *ret = -1;
1747
0
        }
1748
0
        return 0;
1749
0
    }
1750
1751
4
    std::string packed_key(key);
1752
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1753
4
    if (process_ret != 0) {
1754
0
        if (stats) {
1755
0
            ++stats->num_failed;
1756
0
        }
1757
0
        if (ret) {
1758
0
            *ret = -1;
1759
0
        }
1760
0
    }
1761
4
    return 0;
1762
4
}
1763
1764
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1765
6.02k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1766
6.02k
    if (config::force_immediate_recycle) {
1767
15
        return 0L;
1768
15
    }
1769
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1770
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1771
6.00k
    int64_t retention_seconds = config::retention_seconds;
1772
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1773
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1774
4.70k
    }
1775
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1776
6.00k
    if (*earlest_ts > final_expiration) {
1777
5
        *earlest_ts = final_expiration;
1778
5
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1779
5
    }
1780
6.00k
    return final_expiration;
1781
6.02k
}
1782
1783
int64_t calculate_partition_expired_time(
1784
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1785
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1786
9
    if (config::force_immediate_recycle) {
1787
3
        return 0L;
1788
3
    }
1789
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1790
6
                                                            : partition_meta_pb.creation_time();
1791
6
    int64_t retention_seconds = config::retention_seconds;
1792
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1793
6
        retention_seconds =
1794
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1795
6
    }
1796
6
    int64_t final_expiration = expiration + retention_seconds;
1797
6
    if (*earlest_ts > final_expiration) {
1798
2
        *earlest_ts = final_expiration;
1799
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1800
2
    }
1801
6
    return final_expiration;
1802
9
}
1803
1804
int64_t calculate_index_expired_time(const std::string& instance_id_,
1805
                                     const RecycleIndexPB& index_meta_pb,
1806
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1807
10
    if (config::force_immediate_recycle) {
1808
4
        return 0L;
1809
4
    }
1810
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1811
6
                                                        : index_meta_pb.creation_time();
1812
6
    int64_t retention_seconds = config::retention_seconds;
1813
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1814
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1815
6
    }
1816
6
    int64_t final_expiration = expiration + retention_seconds;
1817
6
    if (*earlest_ts > final_expiration) {
1818
2
        *earlest_ts = final_expiration;
1819
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1820
2
    }
1821
6
    return final_expiration;
1822
10
}
1823
1824
int64_t calculate_tmp_rowset_expired_time(
1825
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1826
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1827
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1828
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1829
    //  duration or timeout always < `retention_time` in practice.
1830
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1831
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1832
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1833
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1834
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1835
53.0k
    if (*earlest_ts > final_expiration) {
1836
18
        *earlest_ts = final_expiration;
1837
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1838
18
    }
1839
53.0k
    return final_expiration;
1840
53.0k
}
1841
1842
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1843
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1844
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1845
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1846
8
        *earlest_ts = final_expiration / 1000;
1847
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1848
8
    }
1849
30.0k
    return final_expiration;
1850
30.0k
}
1851
1852
int64_t calculate_restore_job_expired_time(
1853
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1854
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1855
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1856
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1857
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1858
        // final state, recycle immediately
1859
41
        return 0L;
1860
41
    }
1861
    // not final state, wait much longer than the FE's timeout(1 day)
1862
0
    int64_t last_modified_s =
1863
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1864
0
    int64_t expiration = restore_job.expired_at_s() > 0
1865
0
                                 ? last_modified_s + restore_job.expired_at_s()
1866
0
                                 : last_modified_s;
1867
0
    int64_t final_expiration = expiration + config::retention_seconds;
1868
0
    if (*earlest_ts > final_expiration) {
1869
0
        *earlest_ts = final_expiration;
1870
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1871
0
    }
1872
0
    return final_expiration;
1873
41
}
1874
1875
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1876
2
    AbortTxnRequest req;
1877
2
    TxnInfoPB txn_info;
1878
2
    MetaServiceCode code = MetaServiceCode::OK;
1879
2
    std::string msg;
1880
2
    std::stringstream ss;
1881
2
    std::unique_ptr<Transaction> txn;
1882
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1883
2
    if (err != TxnErrorCode::TXN_OK) {
1884
0
        LOG_WARNING("failed to create txn").tag("err", err);
1885
0
        return -1;
1886
0
    }
1887
1888
    // get txn index
1889
2
    TxnIndexPB txn_idx_pb;
1890
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1891
2
    std::string index_val;
1892
2
    err = txn->get(index_key, &index_val);
1893
2
    if (err != TxnErrorCode::TXN_OK) {
1894
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1895
            // maybe recycled
1896
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1897
0
                    .tag("key", hex(index_key))
1898
0
                    .tag("txn_id", txn_id);
1899
0
            return 0;
1900
0
        }
1901
0
        LOG_WARNING("failed to get txn index")
1902
0
                .tag("err", err)
1903
0
                .tag("key", hex(index_key))
1904
0
                .tag("txn_id", txn_id);
1905
0
        return -1;
1906
0
    }
1907
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1908
0
        LOG_WARNING("failed to parse txn index")
1909
0
                .tag("err", err)
1910
0
                .tag("key", hex(index_key))
1911
0
                .tag("txn_id", txn_id);
1912
0
        return -1;
1913
0
    }
1914
1915
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1916
2
    std::string info_val;
1917
2
    err = txn->get(info_key, &info_val);
1918
2
    if (err != TxnErrorCode::TXN_OK) {
1919
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1920
            // maybe recycled
1921
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1922
0
                    .tag("key", hex(info_key))
1923
0
                    .tag("txn_id", txn_id);
1924
0
            return 0;
1925
0
        }
1926
0
        LOG_WARNING("failed to get txn info")
1927
0
                .tag("err", err)
1928
0
                .tag("key", hex(info_key))
1929
0
                .tag("txn_id", txn_id);
1930
0
        return -1;
1931
0
    }
1932
2
    if (!txn_info.ParseFromString(info_val)) {
1933
0
        LOG_WARNING("failed to parse txn info")
1934
0
                .tag("err", err)
1935
0
                .tag("key", hex(info_key))
1936
0
                .tag("txn_id", txn_id);
1937
0
        return -1;
1938
0
    }
1939
1940
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1941
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1942
0
                .tag("key", hex(info_key))
1943
0
                .tag("txn_id", txn_id);
1944
0
        return 0;
1945
0
    }
1946
1947
2
    req.set_txn_id(txn_id);
1948
1949
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1950
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1951
1952
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1953
2
    err = txn->commit();
1954
2
    if (err != TxnErrorCode::TXN_OK) {
1955
0
        code = cast_as<ErrCategory::COMMIT>(err);
1956
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1957
0
        msg = ss.str();
1958
0
        return -1;
1959
0
    }
1960
1961
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1962
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1963
2
              << " code=" << code << " msg=" << msg;
1964
1965
2
    return 0;
1966
2
}
1967
1968
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1969
4
    FinishTabletJobRequest req;
1970
4
    FinishTabletJobResponse res;
1971
4
    req.set_action(FinishTabletJobRequest::ABORT);
1972
4
    MetaServiceCode code = MetaServiceCode::OK;
1973
4
    std::string msg;
1974
4
    std::stringstream ss;
1975
1976
4
    TabletIndexPB tablet_idx;
1977
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1978
4
    if (ret == 1) {
1979
        // tablet maybe recycled, directly return 0
1980
1
        return 0;
1981
3
    } else if (ret != 0) {
1982
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1983
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1984
0
        return ret;
1985
0
    }
1986
1987
3
    std::unique_ptr<Transaction> txn;
1988
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1989
3
    if (err != TxnErrorCode::TXN_OK) {
1990
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1991
0
        return -1;
1992
0
    }
1993
1994
3
    std::string job_key =
1995
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1996
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1997
3
    std::string job_val;
1998
3
    err = txn->get(job_key, &job_val);
1999
3
    if (err != TxnErrorCode::TXN_OK) {
2000
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2001
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2002
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2003
0
            return 0;
2004
0
        }
2005
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2006
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2007
0
                     << " key=" << hex(job_key);
2008
0
        return -1;
2009
0
    }
2010
2011
3
    TabletJobInfoPB job_pb;
2012
3
    if (!job_pb.ParseFromString(job_val)) {
2013
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2014
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2015
0
        return -1;
2016
0
    }
2017
2018
3
    std::string job_id {};
2019
3
    if (!job_pb.compaction().empty()) {
2020
2
        for (const auto& c : job_pb.compaction()) {
2021
2
            if (c.id() == rowset_meta.job_id()) {
2022
2
                job_id = c.id();
2023
2
                break;
2024
2
            }
2025
2
        }
2026
2
    } else if (job_pb.has_schema_change()) {
2027
1
        job_id = job_pb.schema_change().id();
2028
1
    }
2029
2030
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
2031
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
2032
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2033
3
        req.mutable_job()->CopyFrom(job_pb);
2034
3
        req.set_action(FinishTabletJobRequest::ABORT);
2035
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2036
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2037
3
                           ss);
2038
3
        if (code != MetaServiceCode::OK) {
2039
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2040
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2041
0
                         << " msg=" << msg;
2042
0
            return -1;
2043
0
        }
2044
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
2045
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2046
3
                  << " code=" << code << " msg=" << msg;
2047
3
    } else {
2048
        // clang-format off
2049
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
2050
0
                  << ", instance_id=" << instance_id_ 
2051
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2052
0
                  << ", job_id=" << job_id
2053
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
2054
        // clang-format on
2055
0
    }
2056
2057
3
    return 0;
2058
3
}
2059
2060
template <typename T>
2061
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2062
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2063
9
        return rowset_meta_pb.mutable_rowset_meta();
2064
9
    } else {
2065
9
        return &rowset_meta_pb;
2066
9
    }
2067
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2061
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2062
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2063
4
        return rowset_meta_pb.mutable_rowset_meta();
2064
4
    } else {
2065
4
        return &rowset_meta_pb;
2066
4
    }
2067
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2061
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2062
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2063
9
        return rowset_meta_pb.mutable_rowset_meta();
2064
9
    } else {
2065
9
        return &rowset_meta_pb;
2066
9
    }
2067
9
}
2068
2069
template <typename T>
2070
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2071
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2072
35
        return rowset_meta_pb.rowset_meta();
2073
35
    } else {
2074
35
        return rowset_meta_pb;
2075
35
    }
2076
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2070
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2071
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2072
16
        return rowset_meta_pb.rowset_meta();
2073
16
    } else {
2074
16
        return rowset_meta_pb;
2075
16
    }
2076
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2070
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2071
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2072
35
        return rowset_meta_pb.rowset_meta();
2073
35
    } else {
2074
35
        return rowset_meta_pb;
2075
35
    }
2076
35
}
2077
2078
struct DeferredRecycleAbortTask {
2079
    enum class Type : uint8_t {
2080
        TXN,
2081
        JOB,
2082
    };
2083
2084
    Type type = Type::TXN;
2085
    int64_t txn_id = 0;
2086
    int64_t tablet_id = 0;
2087
    int64_t start_version = 0;
2088
    int64_t end_version = 0;
2089
    std::string rowset_id;
2090
    std::string job_id;
2091
};
2092
2093
struct DeferredRecyclePrepareDeleteTask {
2094
    std::string key;
2095
    std::string resource_id;
2096
    std::string rowset_id;
2097
    int64_t tablet_id = 0;
2098
};
2099
2100
template <typename T>
2101
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2102
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2103
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2104
0
            return std::nullopt;
2105
0
        }
2106
4
    }
2107
2108
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2109
4
    DeferredRecycleAbortTask task;
2110
4
    task.tablet_id = rs_meta.tablet_id();
2111
4
    task.start_version = rs_meta.start_version();
2112
4
    task.end_version = rs_meta.end_version();
2113
14
    if (rs_meta.has_load_id()) {
2114
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
2115
4
        task.txn_id = rs_meta.txn_id();
2116
4
        return task;
2117
4
    }
2118
10
    if (rs_meta.has_job_id()) {
2119
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
2120
6
        task.rowset_id = rs_meta.rowset_id_v2();
2121
6
        task.job_id = rs_meta.job_id();
2122
6
        return task;
2123
6
    }
2124
4
    return std::nullopt;
2125
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2101
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2102
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2103
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2104
0
            return std::nullopt;
2105
0
        }
2106
4
    }
2107
2108
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2109
4
    DeferredRecycleAbortTask task;
2110
4
    task.tablet_id = rs_meta.tablet_id();
2111
4
    task.start_version = rs_meta.start_version();
2112
4
    task.end_version = rs_meta.end_version();
2113
4
    if (rs_meta.has_load_id()) {
2114
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2115
2
        task.txn_id = rs_meta.txn_id();
2116
2
        return task;
2117
2
    }
2118
2
    if (rs_meta.has_job_id()) {
2119
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
2120
2
        task.rowset_id = rs_meta.rowset_id_v2();
2121
2
        task.job_id = rs_meta.job_id();
2122
2
        return task;
2123
2
    }
2124
0
    return std::nullopt;
2125
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2101
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2102
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2103
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2104
10
            return std::nullopt;
2105
10
        }
2106
10
    }
2107
2108
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2109
10
    DeferredRecycleAbortTask task;
2110
10
    task.tablet_id = rs_meta.tablet_id();
2111
10
    task.start_version = rs_meta.start_version();
2112
10
    task.end_version = rs_meta.end_version();
2113
10
    if (rs_meta.has_load_id()) {
2114
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2115
2
        task.txn_id = rs_meta.txn_id();
2116
2
        return task;
2117
2
    }
2118
8
    if (rs_meta.has_job_id()) {
2119
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
2120
4
        task.rowset_id = rs_meta.rowset_id_v2();
2121
4
        task.job_id = rs_meta.job_id();
2122
4
        return task;
2123
4
    }
2124
4
    return std::nullopt;
2125
8
}
2126
2127
template <typename T>
2128
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2129
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2130
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2131
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
2128
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2129
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2130
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2131
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
2128
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2129
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2130
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2131
25
}
2132
2133
template <typename T>
2134
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2135
11
                                   const std::vector<std::string>& keys) {
2136
11
    std::unique_ptr<Transaction> txn;
2137
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
2138
11
    if (err != TxnErrorCode::TXN_OK) {
2139
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2140
0
        return -1;
2141
0
    }
2142
11
    std::vector<std::optional<std::string>> values;
2143
11
    err = txn->batch_get(&values, keys);
2144
11
    if (err != TxnErrorCode::TXN_OK) {
2145
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2146
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2147
0
        return -1;
2148
0
    }
2149
11
    size_t total_keys = keys.size();
2150
24
    for (size_t i = 0; i < total_keys; i++) {
2151
13
        if (!values[i].has_value()) {
2152
            // has already been removed by commit_rowset
2153
0
            continue;
2154
0
        }
2155
13
        auto key = keys[i];
2156
13
        auto val = values[i].value();
2157
13
        T rowset_meta_pb;
2158
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2159
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2160
0
                         << " key=" << hex(key);
2161
0
            return -1;
2162
0
        }
2163
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2164
0
            continue;
2165
0
        }
2166
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2167
13
        val.clear();
2168
13
        rowset_meta_pb.SerializeToString(&val);
2169
13
        txn->put(key, val);
2170
13
    }
2171
11
    err = txn->commit();
2172
11
    if (err != TxnErrorCode::TXN_OK) {
2173
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2174
0
        return -1;
2175
0
    }
2176
2177
11
    return 0;
2178
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2135
4
                                   const std::vector<std::string>& keys) {
2136
4
    std::unique_ptr<Transaction> txn;
2137
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
2138
4
    if (err != TxnErrorCode::TXN_OK) {
2139
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2140
0
        return -1;
2141
0
    }
2142
4
    std::vector<std::optional<std::string>> values;
2143
4
    err = txn->batch_get(&values, keys);
2144
4
    if (err != TxnErrorCode::TXN_OK) {
2145
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2146
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2147
0
        return -1;
2148
0
    }
2149
4
    size_t total_keys = keys.size();
2150
8
    for (size_t i = 0; i < total_keys; i++) {
2151
4
        if (!values[i].has_value()) {
2152
            // has already been removed by commit_rowset
2153
0
            continue;
2154
0
        }
2155
4
        auto key = keys[i];
2156
4
        auto val = values[i].value();
2157
4
        T rowset_meta_pb;
2158
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2159
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2160
0
                         << " key=" << hex(key);
2161
0
            return -1;
2162
0
        }
2163
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2164
0
            continue;
2165
0
        }
2166
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2167
4
        val.clear();
2168
4
        rowset_meta_pb.SerializeToString(&val);
2169
4
        txn->put(key, val);
2170
4
    }
2171
4
    err = txn->commit();
2172
4
    if (err != TxnErrorCode::TXN_OK) {
2173
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2174
0
        return -1;
2175
0
    }
2176
2177
4
    return 0;
2178
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2135
7
                                   const std::vector<std::string>& keys) {
2136
7
    std::unique_ptr<Transaction> txn;
2137
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
2138
7
    if (err != TxnErrorCode::TXN_OK) {
2139
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2140
0
        return -1;
2141
0
    }
2142
7
    std::vector<std::optional<std::string>> values;
2143
7
    err = txn->batch_get(&values, keys);
2144
7
    if (err != TxnErrorCode::TXN_OK) {
2145
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2146
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2147
0
        return -1;
2148
0
    }
2149
7
    size_t total_keys = keys.size();
2150
16
    for (size_t i = 0; i < total_keys; i++) {
2151
9
        if (!values[i].has_value()) {
2152
            // has already been removed by commit_rowset
2153
0
            continue;
2154
0
        }
2155
9
        auto key = keys[i];
2156
9
        auto val = values[i].value();
2157
9
        T rowset_meta_pb;
2158
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2159
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2160
0
                         << " key=" << hex(key);
2161
0
            return -1;
2162
0
        }
2163
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2164
0
            continue;
2165
0
        }
2166
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2167
9
        val.clear();
2168
9
        rowset_meta_pb.SerializeToString(&val);
2169
9
        txn->put(key, val);
2170
9
    }
2171
7
    err = txn->commit();
2172
7
    if (err != TxnErrorCode::TXN_OK) {
2173
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2174
0
        return -1;
2175
0
    }
2176
2177
7
    return 0;
2178
7
}
2179
2180
template <typename T>
2181
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2182
                                 const std::vector<std::string>& keys,
2183
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2184
5
                                 bool skip_base_version) {
2185
5
    constexpr size_t kAbortCheckBatchSize = 256;
2186
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2187
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2188
5
        std::unique_ptr<Transaction> txn;
2189
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2190
5
        if (err != TxnErrorCode::TXN_OK) {
2191
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2192
0
            return -1;
2193
0
        }
2194
10
        for (size_t idx = offset; idx < limit; ++idx) {
2195
5
            const std::string& key = keys[idx];
2196
5
            std::string val;
2197
5
            err = txn->get(key, &val);
2198
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2199
                // has already been removed
2200
0
                continue;
2201
0
            }
2202
5
            if (err != TxnErrorCode::TXN_OK) {
2203
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2204
0
                             << " key=" << hex(key);
2205
0
                return -1;
2206
0
            }
2207
5
            T rowset_meta_pb;
2208
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2209
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2210
0
                             << " key=" << hex(key);
2211
0
                return -1;
2212
0
            }
2213
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2214
0
                continue;
2215
0
            }
2216
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2217
5
                abort_task.has_value()) {
2218
5
                abort_tasks->emplace_back(std::move(*abort_task));
2219
5
            }
2220
5
        }
2221
5
    }
2222
5
    return 0;
2223
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2184
2
                                 bool skip_base_version) {
2185
2
    constexpr size_t kAbortCheckBatchSize = 256;
2186
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2187
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2188
2
        std::unique_ptr<Transaction> txn;
2189
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2190
2
        if (err != TxnErrorCode::TXN_OK) {
2191
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2192
0
            return -1;
2193
0
        }
2194
4
        for (size_t idx = offset; idx < limit; ++idx) {
2195
2
            const std::string& key = keys[idx];
2196
2
            std::string val;
2197
2
            err = txn->get(key, &val);
2198
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2199
                // has already been removed
2200
0
                continue;
2201
0
            }
2202
2
            if (err != TxnErrorCode::TXN_OK) {
2203
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2204
0
                             << " key=" << hex(key);
2205
0
                return -1;
2206
0
            }
2207
2
            T rowset_meta_pb;
2208
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2209
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2210
0
                             << " key=" << hex(key);
2211
0
                return -1;
2212
0
            }
2213
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2214
0
                continue;
2215
0
            }
2216
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2217
2
                abort_task.has_value()) {
2218
2
                abort_tasks->emplace_back(std::move(*abort_task));
2219
2
            }
2220
2
        }
2221
2
    }
2222
2
    return 0;
2223
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2184
3
                                 bool skip_base_version) {
2185
3
    constexpr size_t kAbortCheckBatchSize = 256;
2186
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2187
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2188
3
        std::unique_ptr<Transaction> txn;
2189
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2190
3
        if (err != TxnErrorCode::TXN_OK) {
2191
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2192
0
            return -1;
2193
0
        }
2194
6
        for (size_t idx = offset; idx < limit; ++idx) {
2195
3
            const std::string& key = keys[idx];
2196
3
            std::string val;
2197
3
            err = txn->get(key, &val);
2198
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2199
                // has already been removed
2200
0
                continue;
2201
0
            }
2202
3
            if (err != TxnErrorCode::TXN_OK) {
2203
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2204
0
                             << " key=" << hex(key);
2205
0
                return -1;
2206
0
            }
2207
3
            T rowset_meta_pb;
2208
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2209
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2210
0
                             << " key=" << hex(key);
2211
0
                return -1;
2212
0
            }
2213
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2214
0
                continue;
2215
0
            }
2216
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2217
3
                abort_task.has_value()) {
2218
3
                abort_tasks->emplace_back(std::move(*abort_task));
2219
3
            }
2220
3
        }
2221
3
    }
2222
3
    return 0;
2223
3
}
2224
2225
template <typename T>
2226
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2227
5
                                                         bool skip_base_version) {
2228
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2229
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2230
5
                                        skip_base_version) != 0) {
2231
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2232
0
        return -1;
2233
0
    }
2234
5
    for (const auto& abort_task : abort_tasks) {
2235
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2236
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2237
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2238
5
        int abort_ret = 0;
2239
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2240
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2241
3
        } else {
2242
3
            RowsetMetaCloudPB rowset_meta;
2243
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2244
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2245
3
            rowset_meta.set_job_id(abort_task.job_id);
2246
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2247
3
        }
2248
5
        if (abort_ret != 0) {
2249
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2250
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2251
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2252
0
            return abort_ret;
2253
0
        }
2254
5
    }
2255
5
    return 0;
2256
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2227
2
                                                         bool skip_base_version) {
2228
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2229
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2230
2
                                        skip_base_version) != 0) {
2231
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2232
0
        return -1;
2233
0
    }
2234
2
    for (const auto& abort_task : abort_tasks) {
2235
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2236
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2237
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2238
2
        int abort_ret = 0;
2239
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2240
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2241
1
        } else {
2242
1
            RowsetMetaCloudPB rowset_meta;
2243
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2244
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2245
1
            rowset_meta.set_job_id(abort_task.job_id);
2246
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2247
1
        }
2248
2
        if (abort_ret != 0) {
2249
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2250
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2251
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2252
0
            return abort_ret;
2253
0
        }
2254
2
    }
2255
2
    return 0;
2256
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2227
3
                                                         bool skip_base_version) {
2228
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2229
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2230
3
                                        skip_base_version) != 0) {
2231
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2232
0
        return -1;
2233
0
    }
2234
3
    for (const auto& abort_task : abort_tasks) {
2235
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2236
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2237
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2238
3
        int abort_ret = 0;
2239
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2240
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2241
2
        } else {
2242
2
            RowsetMetaCloudPB rowset_meta;
2243
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2244
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2245
2
            rowset_meta.set_job_id(abort_task.job_id);
2246
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2247
2
        }
2248
3
        if (abort_ret != 0) {
2249
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2250
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2251
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2252
0
            return abort_ret;
2253
0
        }
2254
3
    }
2255
3
    return 0;
2256
3
}
2257
2258
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2259
                                 const std::vector<std::string>& keys,
2260
24
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2261
24
    constexpr size_t kPrepareCheckBatchSize = 256;
2262
48
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2263
24
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2264
24
        std::unique_ptr<Transaction> txn;
2265
24
        TxnErrorCode err = txn_kv->create_txn(&txn);
2266
24
        if (err != TxnErrorCode::TXN_OK) {
2267
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2268
0
            return -1;
2269
0
        }
2270
677
        for (size_t idx = offset; idx < limit; ++idx) {
2271
653
            const std::string& key = keys[idx];
2272
653
            std::string val;
2273
653
            err = txn->get(key, &val);
2274
653
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2275
                // has already been removed
2276
0
                continue;
2277
0
            }
2278
653
            if (err != TxnErrorCode::TXN_OK) {
2279
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2280
0
                             << " key=" << hex(key);
2281
0
                return -1;
2282
0
            }
2283
653
            RecycleRowsetPB rowset;
2284
653
            if (!rowset.ParseFromString(val)) {
2285
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2286
0
                             << " key=" << hex(key);
2287
0
                return -1;
2288
0
            }
2289
653
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2290
0
                continue;
2291
0
            }
2292
653
            const auto& rs_meta = rowset.rowset_meta();
2293
653
            delete_tasks->push_back(
2294
653
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2295
653
        }
2296
24
    }
2297
24
    return 0;
2298
24
}
2299
2300
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2301
1
    const std::string task_name = "recycle_ref_rowsets";
2302
1
    *has_unrecycled_rowsets = false;
2303
2304
1
    std::string data_rowset_ref_count_key_start =
2305
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2306
1
    std::string data_rowset_ref_count_key_end =
2307
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2308
2309
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2310
2311
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2312
1
    register_recycle_task(task_name, start_time);
2313
2314
1
    DORIS_CLOUD_DEFER {
2315
1
        unregister_recycle_task(task_name);
2316
1
        int64_t cost =
2317
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2318
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2319
1
                .tag("instance_id", instance_id_);
2320
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2314
1
    DORIS_CLOUD_DEFER {
2315
1
        unregister_recycle_task(task_name);
2316
1
        int64_t cost =
2317
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2318
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2319
1
                .tag("instance_id", instance_id_);
2320
1
    };
2321
2322
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2323
1
    std::set<int64_t> tablets_with_refs;
2324
1
    int64_t num_scanned = 0;
2325
2326
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2327
0
        ++num_scanned;
2328
0
        int64_t tablet_id;
2329
0
        std::string rowset_id;
2330
0
        std::string_view key(k);
2331
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2332
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2333
0
            return 0; // Continue scanning
2334
0
        }
2335
2336
0
        tablets_with_refs.insert(tablet_id);
2337
0
        return 0;
2338
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2339
2340
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2341
1
                         std::move(scan_func)) != 0) {
2342
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2343
0
        return -1;
2344
0
    }
2345
2346
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2347
1
             tablets_with_refs.size(), num_scanned)
2348
1
            .tag("instance_id", instance_id_);
2349
2350
    // Phase 2: Recycle each tablet
2351
1
    int64_t num_recycled_tablets = 0;
2352
1
    for (int64_t tablet_id : tablets_with_refs) {
2353
0
        if (stopped()) {
2354
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2355
0
                    .tag("instance_id", instance_id_)
2356
0
                    .tag("tablets_processed", num_recycled_tablets)
2357
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2358
0
            break;
2359
0
        }
2360
2361
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2362
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2363
0
            LOG_WARNING("failed to recycle tablet")
2364
0
                    .tag("instance_id", instance_id_)
2365
0
                    .tag("tablet_id", tablet_id);
2366
0
            return -1;
2367
0
        }
2368
0
        ++num_recycled_tablets;
2369
0
    }
2370
2371
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2372
1
            .tag("instance_id", instance_id_)
2373
1
            .tag("total_tablets", tablets_with_refs.size());
2374
2375
    // Phase 3: Scan again to check if any ref count keys still exist
2376
1
    std::unique_ptr<Transaction> txn;
2377
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2378
1
    if (err != TxnErrorCode::TXN_OK) {
2379
0
        LOG_WARNING("failed to create txn for final check")
2380
0
                .tag("instance_id", instance_id_)
2381
0
                .tag("err", err);
2382
0
        return -1;
2383
0
    }
2384
2385
1
    std::unique_ptr<RangeGetIterator> iter;
2386
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2387
1
    if (err != TxnErrorCode::TXN_OK) {
2388
0
        LOG_WARNING("failed to create range iterator for final check")
2389
0
                .tag("instance_id", instance_id_)
2390
0
                .tag("err", err);
2391
0
        return -1;
2392
0
    }
2393
2394
1
    *has_unrecycled_rowsets = iter->has_next();
2395
1
    if (*has_unrecycled_rowsets) {
2396
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2397
0
                .tag("instance_id", instance_id_);
2398
0
    }
2399
2400
1
    return 0;
2401
1
}
2402
2403
17
int InstanceRecycler::recycle_indexes() {
2404
17
    const std::string task_name = "recycle_indexes";
2405
17
    int64_t num_scanned = 0;
2406
17
    int64_t num_expired = 0;
2407
17
    int64_t num_recycled = 0;
2408
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2409
2410
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2411
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2412
17
    std::string index_key0;
2413
17
    std::string index_key1;
2414
17
    recycle_index_key(index_key_info0, &index_key0);
2415
17
    recycle_index_key(index_key_info1, &index_key1);
2416
2417
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2418
2419
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2420
17
    register_recycle_task(task_name, start_time);
2421
2422
17
    DORIS_CLOUD_DEFER {
2423
17
        unregister_recycle_task(task_name);
2424
17
        int64_t cost =
2425
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2426
17
        metrics_context.finish_report();
2427
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2428
17
                .tag("instance_id", instance_id_)
2429
17
                .tag("num_scanned", num_scanned)
2430
17
                .tag("num_expired", num_expired)
2431
17
                .tag("num_recycled", num_recycled);
2432
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2422
2
    DORIS_CLOUD_DEFER {
2423
2
        unregister_recycle_task(task_name);
2424
2
        int64_t cost =
2425
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2426
2
        metrics_context.finish_report();
2427
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2428
2
                .tag("instance_id", instance_id_)
2429
2
                .tag("num_scanned", num_scanned)
2430
2
                .tag("num_expired", num_expired)
2431
2
                .tag("num_recycled", num_recycled);
2432
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2422
15
    DORIS_CLOUD_DEFER {
2423
15
        unregister_recycle_task(task_name);
2424
15
        int64_t cost =
2425
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2426
15
        metrics_context.finish_report();
2427
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2428
15
                .tag("instance_id", instance_id_)
2429
15
                .tag("num_scanned", num_scanned)
2430
15
                .tag("num_expired", num_expired)
2431
15
                .tag("num_recycled", num_recycled);
2432
15
    };
2433
2434
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2435
2436
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2437
17
    std::vector<std::string_view> index_keys;
2438
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2439
10
        ++num_scanned;
2440
10
        RecycleIndexPB index_pb;
2441
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2442
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2443
0
            return -1;
2444
0
        }
2445
10
        int64_t current_time = ::time(nullptr);
2446
10
        if (current_time <
2447
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2448
0
            return 0;
2449
0
        }
2450
10
        ++num_expired;
2451
        // decode index_id
2452
10
        auto k1 = k;
2453
10
        k1.remove_prefix(1);
2454
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2455
10
        decode_key(&k1, &out);
2456
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2457
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2458
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2459
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2460
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2461
        // Change state to RECYCLING
2462
10
        std::unique_ptr<Transaction> txn;
2463
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2464
10
        if (err != TxnErrorCode::TXN_OK) {
2465
0
            LOG_WARNING("failed to create txn").tag("err", err);
2466
0
            return -1;
2467
0
        }
2468
10
        std::string val;
2469
10
        err = txn->get(k, &val);
2470
10
        if (err ==
2471
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2472
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2473
0
            return 0;
2474
0
        }
2475
10
        if (err != TxnErrorCode::TXN_OK) {
2476
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2477
0
            return -1;
2478
0
        }
2479
10
        index_pb.Clear();
2480
10
        if (!index_pb.ParseFromString(val)) {
2481
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2482
0
            return -1;
2483
0
        }
2484
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2485
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2486
9
            txn->put(k, index_pb.SerializeAsString());
2487
9
            err = txn->commit();
2488
9
            if (err != TxnErrorCode::TXN_OK) {
2489
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2490
0
                return -1;
2491
0
            }
2492
9
        }
2493
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2494
1
            LOG_WARNING("failed to recycle tablets under index")
2495
1
                    .tag("table_id", index_pb.table_id())
2496
1
                    .tag("instance_id", instance_id_)
2497
1
                    .tag("index_id", index_id);
2498
1
            return -1;
2499
1
        }
2500
2501
9
        if (index_pb.has_db_id()) {
2502
            // Recycle the versioned keys
2503
3
            std::unique_ptr<Transaction> txn;
2504
3
            err = txn_kv_->create_txn(&txn);
2505
3
            if (err != TxnErrorCode::TXN_OK) {
2506
0
                LOG_WARNING("failed to create txn").tag("err", err);
2507
0
                return -1;
2508
0
            }
2509
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2510
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2511
3
            std::string index_inverted_key = versioned::index_inverted_key(
2512
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2513
3
            versioned_remove_all(txn.get(), meta_key);
2514
3
            txn->remove(index_key);
2515
3
            txn->remove(index_inverted_key);
2516
3
            err = txn->commit();
2517
3
            if (err != TxnErrorCode::TXN_OK) {
2518
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2519
0
                return -1;
2520
0
            }
2521
3
        }
2522
2523
9
        metrics_context.total_recycled_num = ++num_recycled;
2524
9
        metrics_context.report();
2525
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2526
9
        index_keys.push_back(k);
2527
9
        return 0;
2528
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2438
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2439
2
        ++num_scanned;
2440
2
        RecycleIndexPB index_pb;
2441
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2442
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2443
0
            return -1;
2444
0
        }
2445
2
        int64_t current_time = ::time(nullptr);
2446
2
        if (current_time <
2447
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2448
0
            return 0;
2449
0
        }
2450
2
        ++num_expired;
2451
        // decode index_id
2452
2
        auto k1 = k;
2453
2
        k1.remove_prefix(1);
2454
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2455
2
        decode_key(&k1, &out);
2456
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2457
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2458
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2459
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2460
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2461
        // Change state to RECYCLING
2462
2
        std::unique_ptr<Transaction> txn;
2463
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2464
2
        if (err != TxnErrorCode::TXN_OK) {
2465
0
            LOG_WARNING("failed to create txn").tag("err", err);
2466
0
            return -1;
2467
0
        }
2468
2
        std::string val;
2469
2
        err = txn->get(k, &val);
2470
2
        if (err ==
2471
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2472
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2473
0
            return 0;
2474
0
        }
2475
2
        if (err != TxnErrorCode::TXN_OK) {
2476
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2477
0
            return -1;
2478
0
        }
2479
2
        index_pb.Clear();
2480
2
        if (!index_pb.ParseFromString(val)) {
2481
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2482
0
            return -1;
2483
0
        }
2484
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2485
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2486
1
            txn->put(k, index_pb.SerializeAsString());
2487
1
            err = txn->commit();
2488
1
            if (err != TxnErrorCode::TXN_OK) {
2489
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2490
0
                return -1;
2491
0
            }
2492
1
        }
2493
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2494
1
            LOG_WARNING("failed to recycle tablets under index")
2495
1
                    .tag("table_id", index_pb.table_id())
2496
1
                    .tag("instance_id", instance_id_)
2497
1
                    .tag("index_id", index_id);
2498
1
            return -1;
2499
1
        }
2500
2501
1
        if (index_pb.has_db_id()) {
2502
            // Recycle the versioned keys
2503
1
            std::unique_ptr<Transaction> txn;
2504
1
            err = txn_kv_->create_txn(&txn);
2505
1
            if (err != TxnErrorCode::TXN_OK) {
2506
0
                LOG_WARNING("failed to create txn").tag("err", err);
2507
0
                return -1;
2508
0
            }
2509
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2510
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2511
1
            std::string index_inverted_key = versioned::index_inverted_key(
2512
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2513
1
            versioned_remove_all(txn.get(), meta_key);
2514
1
            txn->remove(index_key);
2515
1
            txn->remove(index_inverted_key);
2516
1
            err = txn->commit();
2517
1
            if (err != TxnErrorCode::TXN_OK) {
2518
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2519
0
                return -1;
2520
0
            }
2521
1
        }
2522
2523
1
        metrics_context.total_recycled_num = ++num_recycled;
2524
1
        metrics_context.report();
2525
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2526
1
        index_keys.push_back(k);
2527
1
        return 0;
2528
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2438
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2439
8
        ++num_scanned;
2440
8
        RecycleIndexPB index_pb;
2441
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2442
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2443
0
            return -1;
2444
0
        }
2445
8
        int64_t current_time = ::time(nullptr);
2446
8
        if (current_time <
2447
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2448
0
            return 0;
2449
0
        }
2450
8
        ++num_expired;
2451
        // decode index_id
2452
8
        auto k1 = k;
2453
8
        k1.remove_prefix(1);
2454
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2455
8
        decode_key(&k1, &out);
2456
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2457
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2458
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2459
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2460
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2461
        // Change state to RECYCLING
2462
8
        std::unique_ptr<Transaction> txn;
2463
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2464
8
        if (err != TxnErrorCode::TXN_OK) {
2465
0
            LOG_WARNING("failed to create txn").tag("err", err);
2466
0
            return -1;
2467
0
        }
2468
8
        std::string val;
2469
8
        err = txn->get(k, &val);
2470
8
        if (err ==
2471
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2472
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2473
0
            return 0;
2474
0
        }
2475
8
        if (err != TxnErrorCode::TXN_OK) {
2476
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2477
0
            return -1;
2478
0
        }
2479
8
        index_pb.Clear();
2480
8
        if (!index_pb.ParseFromString(val)) {
2481
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2482
0
            return -1;
2483
0
        }
2484
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2485
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2486
8
            txn->put(k, index_pb.SerializeAsString());
2487
8
            err = txn->commit();
2488
8
            if (err != TxnErrorCode::TXN_OK) {
2489
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2490
0
                return -1;
2491
0
            }
2492
8
        }
2493
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2494
0
            LOG_WARNING("failed to recycle tablets under index")
2495
0
                    .tag("table_id", index_pb.table_id())
2496
0
                    .tag("instance_id", instance_id_)
2497
0
                    .tag("index_id", index_id);
2498
0
            return -1;
2499
0
        }
2500
2501
8
        if (index_pb.has_db_id()) {
2502
            // Recycle the versioned keys
2503
2
            std::unique_ptr<Transaction> txn;
2504
2
            err = txn_kv_->create_txn(&txn);
2505
2
            if (err != TxnErrorCode::TXN_OK) {
2506
0
                LOG_WARNING("failed to create txn").tag("err", err);
2507
0
                return -1;
2508
0
            }
2509
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2510
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2511
2
            std::string index_inverted_key = versioned::index_inverted_key(
2512
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2513
2
            versioned_remove_all(txn.get(), meta_key);
2514
2
            txn->remove(index_key);
2515
2
            txn->remove(index_inverted_key);
2516
2
            err = txn->commit();
2517
2
            if (err != TxnErrorCode::TXN_OK) {
2518
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2519
0
                return -1;
2520
0
            }
2521
2
        }
2522
2523
8
        metrics_context.total_recycled_num = ++num_recycled;
2524
8
        metrics_context.report();
2525
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2526
8
        index_keys.push_back(k);
2527
8
        return 0;
2528
8
    };
2529
2530
17
    auto loop_done = [&index_keys, this]() -> int {
2531
6
        if (index_keys.empty()) return 0;
2532
5
        DORIS_CLOUD_DEFER {
2533
5
            index_keys.clear();
2534
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2532
1
        DORIS_CLOUD_DEFER {
2533
1
            index_keys.clear();
2534
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2532
4
        DORIS_CLOUD_DEFER {
2533
4
            index_keys.clear();
2534
4
        };
2535
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2536
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2537
0
            return -1;
2538
0
        }
2539
5
        return 0;
2540
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2530
2
    auto loop_done = [&index_keys, this]() -> int {
2531
2
        if (index_keys.empty()) return 0;
2532
1
        DORIS_CLOUD_DEFER {
2533
1
            index_keys.clear();
2534
1
        };
2535
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2536
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2537
0
            return -1;
2538
0
        }
2539
1
        return 0;
2540
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2530
4
    auto loop_done = [&index_keys, this]() -> int {
2531
4
        if (index_keys.empty()) return 0;
2532
4
        DORIS_CLOUD_DEFER {
2533
4
            index_keys.clear();
2534
4
        };
2535
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2536
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2537
0
            return -1;
2538
0
        }
2539
4
        return 0;
2540
4
    };
2541
2542
17
    if (config::enable_recycler_stats_metrics) {
2543
0
        scan_and_statistics_indexes();
2544
0
    }
2545
    // recycle_func and loop_done for scan and recycle
2546
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2547
17
}
2548
2549
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2550
8.25k
                             int64_t tablet_id) {
2551
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2552
2553
8.25k
    std::unique_ptr<Transaction> txn;
2554
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2555
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2556
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2557
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2558
0
        return false;
2559
0
    }
2560
2561
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2562
8.25k
    std::string tablet_idx_val;
2563
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2564
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2565
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2566
0
                     << " tablet_id=" << tablet_id << " err=" << err
2567
0
                     << " key=" << hex(tablet_idx_key);
2568
0
        return false;
2569
0
    }
2570
2571
8.25k
    TabletIndexPB tablet_idx_pb;
2572
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2573
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2574
0
                     << " tablet_id=" << tablet_id;
2575
0
        return false;
2576
0
    }
2577
2578
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2579
        // In the previous version, the db_id was not set in the index_pb.
2580
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2581
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2582
0
                  << " instance_id=" << instance_id
2583
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2584
0
        return true;
2585
0
    }
2586
2587
8.25k
    std::string ver_val;
2588
8.25k
    std::string ver_key =
2589
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2590
8.25k
                                   tablet_idx_pb.partition_id()});
2591
8.25k
    err = txn->get(ver_key, &ver_val);
2592
2593
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2594
214
        LOG(INFO) << ""
2595
214
                     "partition version not found, instance_id="
2596
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2597
214
                  << " table_id=" << tablet_idx_pb.table_id()
2598
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2599
214
                  << " key=" << hex(ver_key);
2600
214
        return true;
2601
214
    }
2602
2603
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2604
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2605
0
                     << " db_id=" << tablet_idx_pb.db_id()
2606
0
                     << " table_id=" << tablet_idx_pb.table_id()
2607
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2608
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2609
0
        return false;
2610
0
    }
2611
2612
8.03k
    VersionPB version_pb;
2613
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2614
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2615
0
                     << " db_id=" << tablet_idx_pb.db_id()
2616
0
                     << " table_id=" << tablet_idx_pb.table_id()
2617
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2618
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2619
0
        return false;
2620
0
    }
2621
2622
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2623
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2624
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2625
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2626
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2627
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2628
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2629
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2630
4.00k
                     << " key=" << hex(ver_key);
2631
4.00k
        return false;
2632
4.00k
    }
2633
4.03k
    return true;
2634
8.03k
}
2635
2636
15
int InstanceRecycler::recycle_partitions() {
2637
15
    const std::string task_name = "recycle_partitions";
2638
15
    int64_t num_scanned = 0;
2639
15
    int64_t num_expired = 0;
2640
15
    int64_t num_recycled = 0;
2641
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2642
2643
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2644
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2645
15
    std::string part_key0;
2646
15
    std::string part_key1;
2647
15
    recycle_partition_key(part_key_info0, &part_key0);
2648
15
    recycle_partition_key(part_key_info1, &part_key1);
2649
2650
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2651
2652
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2653
15
    register_recycle_task(task_name, start_time);
2654
2655
15
    DORIS_CLOUD_DEFER {
2656
15
        unregister_recycle_task(task_name);
2657
15
        int64_t cost =
2658
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
15
        metrics_context.finish_report();
2660
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2661
15
                .tag("instance_id", instance_id_)
2662
15
                .tag("num_scanned", num_scanned)
2663
15
                .tag("num_expired", num_expired)
2664
15
                .tag("num_recycled", num_recycled);
2665
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2655
2
    DORIS_CLOUD_DEFER {
2656
2
        unregister_recycle_task(task_name);
2657
2
        int64_t cost =
2658
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
2
        metrics_context.finish_report();
2660
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2661
2
                .tag("instance_id", instance_id_)
2662
2
                .tag("num_scanned", num_scanned)
2663
2
                .tag("num_expired", num_expired)
2664
2
                .tag("num_recycled", num_recycled);
2665
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2655
13
    DORIS_CLOUD_DEFER {
2656
13
        unregister_recycle_task(task_name);
2657
13
        int64_t cost =
2658
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
13
        metrics_context.finish_report();
2660
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2661
13
                .tag("instance_id", instance_id_)
2662
13
                .tag("num_scanned", num_scanned)
2663
13
                .tag("num_expired", num_expired)
2664
13
                .tag("num_recycled", num_recycled);
2665
13
    };
2666
2667
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2668
2669
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2670
15
    std::vector<std::string_view> partition_keys;
2671
15
    std::vector<std::string> partition_version_keys;
2672
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2673
9
        ++num_scanned;
2674
9
        RecyclePartitionPB part_pb;
2675
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2676
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2677
0
            return -1;
2678
0
        }
2679
9
        int64_t current_time = ::time(nullptr);
2680
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2681
9
                                                            &earlest_ts)) { // not expired
2682
0
            return 0;
2683
0
        }
2684
9
        ++num_expired;
2685
        // decode partition_id
2686
9
        auto k1 = k;
2687
9
        k1.remove_prefix(1);
2688
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2689
9
        decode_key(&k1, &out);
2690
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2691
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2692
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2693
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2694
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2695
        // Change state to RECYCLING
2696
9
        std::unique_ptr<Transaction> txn;
2697
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2698
9
        if (err != TxnErrorCode::TXN_OK) {
2699
0
            LOG_WARNING("failed to create txn").tag("err", err);
2700
0
            return -1;
2701
0
        }
2702
9
        std::string val;
2703
9
        err = txn->get(k, &val);
2704
9
        if (err ==
2705
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2706
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2707
0
            return 0;
2708
0
        }
2709
9
        if (err != TxnErrorCode::TXN_OK) {
2710
0
            LOG_WARNING("failed to get kv");
2711
0
            return -1;
2712
0
        }
2713
9
        part_pb.Clear();
2714
9
        if (!part_pb.ParseFromString(val)) {
2715
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2716
0
            return -1;
2717
0
        }
2718
        // Partitions with PREPARED state MUST have no data
2719
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2720
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2721
8
            txn->put(k, part_pb.SerializeAsString());
2722
8
            err = txn->commit();
2723
8
            if (err != TxnErrorCode::TXN_OK) {
2724
0
                LOG_WARNING("failed to commit txn: {}", err);
2725
0
                return -1;
2726
0
            }
2727
8
        }
2728
2729
9
        int ret = 0;
2730
33
        for (int64_t index_id : part_pb.index_id()) {
2731
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2732
1
                LOG_WARNING("failed to recycle tablets under partition")
2733
1
                        .tag("table_id", part_pb.table_id())
2734
1
                        .tag("instance_id", instance_id_)
2735
1
                        .tag("index_id", index_id)
2736
1
                        .tag("partition_id", partition_id);
2737
1
                ret = -1;
2738
1
            }
2739
33
        }
2740
9
        if (ret == 0 && part_pb.has_db_id()) {
2741
            // Recycle the versioned keys
2742
8
            std::unique_ptr<Transaction> txn;
2743
8
            err = txn_kv_->create_txn(&txn);
2744
8
            if (err != TxnErrorCode::TXN_OK) {
2745
0
                LOG_WARNING("failed to create txn").tag("err", err);
2746
0
                return -1;
2747
0
            }
2748
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2749
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2750
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2751
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2752
8
            std::string partition_version_key =
2753
8
                    versioned::partition_version_key({instance_id_, partition_id});
2754
8
            versioned_remove_all(txn.get(), meta_key);
2755
8
            txn->remove(index_key);
2756
8
            txn->remove(inverted_index_key);
2757
8
            versioned_remove_all(txn.get(), partition_version_key);
2758
8
            err = txn->commit();
2759
8
            if (err != TxnErrorCode::TXN_OK) {
2760
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2761
0
                return -1;
2762
0
            }
2763
8
        }
2764
2765
9
        if (ret == 0) {
2766
8
            ++num_recycled;
2767
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2768
8
            partition_keys.push_back(k);
2769
8
            if (part_pb.db_id() > 0) {
2770
8
                partition_version_keys.push_back(partition_version_key(
2771
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2772
8
            }
2773
8
            metrics_context.total_recycled_num = num_recycled;
2774
8
            metrics_context.report();
2775
8
        }
2776
9
        return ret;
2777
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2672
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2673
2
        ++num_scanned;
2674
2
        RecyclePartitionPB part_pb;
2675
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2676
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2677
0
            return -1;
2678
0
        }
2679
2
        int64_t current_time = ::time(nullptr);
2680
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2681
2
                                                            &earlest_ts)) { // not expired
2682
0
            return 0;
2683
0
        }
2684
2
        ++num_expired;
2685
        // decode partition_id
2686
2
        auto k1 = k;
2687
2
        k1.remove_prefix(1);
2688
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2689
2
        decode_key(&k1, &out);
2690
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2691
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2692
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2693
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2694
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2695
        // Change state to RECYCLING
2696
2
        std::unique_ptr<Transaction> txn;
2697
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2698
2
        if (err != TxnErrorCode::TXN_OK) {
2699
0
            LOG_WARNING("failed to create txn").tag("err", err);
2700
0
            return -1;
2701
0
        }
2702
2
        std::string val;
2703
2
        err = txn->get(k, &val);
2704
2
        if (err ==
2705
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2706
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2707
0
            return 0;
2708
0
        }
2709
2
        if (err != TxnErrorCode::TXN_OK) {
2710
0
            LOG_WARNING("failed to get kv");
2711
0
            return -1;
2712
0
        }
2713
2
        part_pb.Clear();
2714
2
        if (!part_pb.ParseFromString(val)) {
2715
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2716
0
            return -1;
2717
0
        }
2718
        // Partitions with PREPARED state MUST have no data
2719
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2720
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2721
1
            txn->put(k, part_pb.SerializeAsString());
2722
1
            err = txn->commit();
2723
1
            if (err != TxnErrorCode::TXN_OK) {
2724
0
                LOG_WARNING("failed to commit txn: {}", err);
2725
0
                return -1;
2726
0
            }
2727
1
        }
2728
2729
2
        int ret = 0;
2730
2
        for (int64_t index_id : part_pb.index_id()) {
2731
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2732
1
                LOG_WARNING("failed to recycle tablets under partition")
2733
1
                        .tag("table_id", part_pb.table_id())
2734
1
                        .tag("instance_id", instance_id_)
2735
1
                        .tag("index_id", index_id)
2736
1
                        .tag("partition_id", partition_id);
2737
1
                ret = -1;
2738
1
            }
2739
2
        }
2740
2
        if (ret == 0 && part_pb.has_db_id()) {
2741
            // Recycle the versioned keys
2742
1
            std::unique_ptr<Transaction> txn;
2743
1
            err = txn_kv_->create_txn(&txn);
2744
1
            if (err != TxnErrorCode::TXN_OK) {
2745
0
                LOG_WARNING("failed to create txn").tag("err", err);
2746
0
                return -1;
2747
0
            }
2748
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2749
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2750
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2751
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2752
1
            std::string partition_version_key =
2753
1
                    versioned::partition_version_key({instance_id_, partition_id});
2754
1
            versioned_remove_all(txn.get(), meta_key);
2755
1
            txn->remove(index_key);
2756
1
            txn->remove(inverted_index_key);
2757
1
            versioned_remove_all(txn.get(), partition_version_key);
2758
1
            err = txn->commit();
2759
1
            if (err != TxnErrorCode::TXN_OK) {
2760
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2761
0
                return -1;
2762
0
            }
2763
1
        }
2764
2765
2
        if (ret == 0) {
2766
1
            ++num_recycled;
2767
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2768
1
            partition_keys.push_back(k);
2769
1
            if (part_pb.db_id() > 0) {
2770
1
                partition_version_keys.push_back(partition_version_key(
2771
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2772
1
            }
2773
1
            metrics_context.total_recycled_num = num_recycled;
2774
1
            metrics_context.report();
2775
1
        }
2776
2
        return ret;
2777
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2672
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2673
7
        ++num_scanned;
2674
7
        RecyclePartitionPB part_pb;
2675
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2676
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2677
0
            return -1;
2678
0
        }
2679
7
        int64_t current_time = ::time(nullptr);
2680
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2681
7
                                                            &earlest_ts)) { // not expired
2682
0
            return 0;
2683
0
        }
2684
7
        ++num_expired;
2685
        // decode partition_id
2686
7
        auto k1 = k;
2687
7
        k1.remove_prefix(1);
2688
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2689
7
        decode_key(&k1, &out);
2690
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2691
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2692
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2693
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2694
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2695
        // Change state to RECYCLING
2696
7
        std::unique_ptr<Transaction> txn;
2697
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2698
7
        if (err != TxnErrorCode::TXN_OK) {
2699
0
            LOG_WARNING("failed to create txn").tag("err", err);
2700
0
            return -1;
2701
0
        }
2702
7
        std::string val;
2703
7
        err = txn->get(k, &val);
2704
7
        if (err ==
2705
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2706
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2707
0
            return 0;
2708
0
        }
2709
7
        if (err != TxnErrorCode::TXN_OK) {
2710
0
            LOG_WARNING("failed to get kv");
2711
0
            return -1;
2712
0
        }
2713
7
        part_pb.Clear();
2714
7
        if (!part_pb.ParseFromString(val)) {
2715
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2716
0
            return -1;
2717
0
        }
2718
        // Partitions with PREPARED state MUST have no data
2719
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2720
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2721
7
            txn->put(k, part_pb.SerializeAsString());
2722
7
            err = txn->commit();
2723
7
            if (err != TxnErrorCode::TXN_OK) {
2724
0
                LOG_WARNING("failed to commit txn: {}", err);
2725
0
                return -1;
2726
0
            }
2727
7
        }
2728
2729
7
        int ret = 0;
2730
31
        for (int64_t index_id : part_pb.index_id()) {
2731
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2732
0
                LOG_WARNING("failed to recycle tablets under partition")
2733
0
                        .tag("table_id", part_pb.table_id())
2734
0
                        .tag("instance_id", instance_id_)
2735
0
                        .tag("index_id", index_id)
2736
0
                        .tag("partition_id", partition_id);
2737
0
                ret = -1;
2738
0
            }
2739
31
        }
2740
7
        if (ret == 0 && part_pb.has_db_id()) {
2741
            // Recycle the versioned keys
2742
7
            std::unique_ptr<Transaction> txn;
2743
7
            err = txn_kv_->create_txn(&txn);
2744
7
            if (err != TxnErrorCode::TXN_OK) {
2745
0
                LOG_WARNING("failed to create txn").tag("err", err);
2746
0
                return -1;
2747
0
            }
2748
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2749
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2750
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2751
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2752
7
            std::string partition_version_key =
2753
7
                    versioned::partition_version_key({instance_id_, partition_id});
2754
7
            versioned_remove_all(txn.get(), meta_key);
2755
7
            txn->remove(index_key);
2756
7
            txn->remove(inverted_index_key);
2757
7
            versioned_remove_all(txn.get(), partition_version_key);
2758
7
            err = txn->commit();
2759
7
            if (err != TxnErrorCode::TXN_OK) {
2760
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2761
0
                return -1;
2762
0
            }
2763
7
        }
2764
2765
7
        if (ret == 0) {
2766
7
            ++num_recycled;
2767
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2768
7
            partition_keys.push_back(k);
2769
7
            if (part_pb.db_id() > 0) {
2770
7
                partition_version_keys.push_back(partition_version_key(
2771
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2772
7
            }
2773
7
            metrics_context.total_recycled_num = num_recycled;
2774
7
            metrics_context.report();
2775
7
        }
2776
7
        return ret;
2777
7
    };
2778
2779
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2780
5
        if (partition_keys.empty()) return 0;
2781
4
        DORIS_CLOUD_DEFER {
2782
4
            partition_keys.clear();
2783
4
            partition_version_keys.clear();
2784
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2781
1
        DORIS_CLOUD_DEFER {
2782
1
            partition_keys.clear();
2783
1
            partition_version_keys.clear();
2784
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2781
3
        DORIS_CLOUD_DEFER {
2782
3
            partition_keys.clear();
2783
3
            partition_version_keys.clear();
2784
3
        };
2785
4
        std::unique_ptr<Transaction> txn;
2786
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2787
4
        if (err != TxnErrorCode::TXN_OK) {
2788
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2789
0
            return -1;
2790
0
        }
2791
8
        for (auto& k : partition_keys) {
2792
8
            txn->remove(k);
2793
8
        }
2794
8
        for (auto& k : partition_version_keys) {
2795
8
            txn->remove(k);
2796
8
        }
2797
4
        err = txn->commit();
2798
4
        if (err != TxnErrorCode::TXN_OK) {
2799
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2800
0
                         << " err=" << err;
2801
0
            return -1;
2802
0
        }
2803
4
        return 0;
2804
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2779
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2780
2
        if (partition_keys.empty()) return 0;
2781
1
        DORIS_CLOUD_DEFER {
2782
1
            partition_keys.clear();
2783
1
            partition_version_keys.clear();
2784
1
        };
2785
1
        std::unique_ptr<Transaction> txn;
2786
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2787
1
        if (err != TxnErrorCode::TXN_OK) {
2788
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2789
0
            return -1;
2790
0
        }
2791
1
        for (auto& k : partition_keys) {
2792
1
            txn->remove(k);
2793
1
        }
2794
1
        for (auto& k : partition_version_keys) {
2795
1
            txn->remove(k);
2796
1
        }
2797
1
        err = txn->commit();
2798
1
        if (err != TxnErrorCode::TXN_OK) {
2799
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2800
0
                         << " err=" << err;
2801
0
            return -1;
2802
0
        }
2803
1
        return 0;
2804
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2779
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2780
3
        if (partition_keys.empty()) return 0;
2781
3
        DORIS_CLOUD_DEFER {
2782
3
            partition_keys.clear();
2783
3
            partition_version_keys.clear();
2784
3
        };
2785
3
        std::unique_ptr<Transaction> txn;
2786
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2787
3
        if (err != TxnErrorCode::TXN_OK) {
2788
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2789
0
            return -1;
2790
0
        }
2791
7
        for (auto& k : partition_keys) {
2792
7
            txn->remove(k);
2793
7
        }
2794
7
        for (auto& k : partition_version_keys) {
2795
7
            txn->remove(k);
2796
7
        }
2797
3
        err = txn->commit();
2798
3
        if (err != TxnErrorCode::TXN_OK) {
2799
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2800
0
                         << " err=" << err;
2801
0
            return -1;
2802
0
        }
2803
3
        return 0;
2804
3
    };
2805
2806
15
    if (config::enable_recycler_stats_metrics) {
2807
0
        scan_and_statistics_partitions();
2808
0
    }
2809
    // recycle_func and loop_done for scan and recycle
2810
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2811
15
}
2812
2813
14
int InstanceRecycler::recycle_versions() {
2814
14
    if (should_recycle_versioned_keys()) {
2815
2
        return recycle_orphan_partitions();
2816
2
    }
2817
2818
12
    int64_t num_scanned = 0;
2819
12
    int64_t num_recycled = 0;
2820
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2821
2822
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2823
2824
12
    auto start_time = steady_clock::now();
2825
2826
12
    DORIS_CLOUD_DEFER {
2827
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2828
12
        metrics_context.finish_report();
2829
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2830
12
                .tag("instance_id", instance_id_)
2831
12
                .tag("num_scanned", num_scanned)
2832
12
                .tag("num_recycled", num_recycled);
2833
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2826
12
    DORIS_CLOUD_DEFER {
2827
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2828
12
        metrics_context.finish_report();
2829
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2830
12
                .tag("instance_id", instance_id_)
2831
12
                .tag("num_scanned", num_scanned)
2832
12
                .tag("num_recycled", num_recycled);
2833
12
    };
2834
2835
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2836
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2837
12
    int64_t last_scanned_table_id = 0;
2838
12
    bool is_recycled = false; // Is last scanned kv recycled
2839
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2840
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2841
2
        ++num_scanned;
2842
2
        auto k1 = k;
2843
2
        k1.remove_prefix(1);
2844
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2845
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2846
2
        decode_key(&k1, &out);
2847
2
        DCHECK_EQ(out.size(), 6) << k;
2848
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2849
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2850
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2851
0
            return 0;
2852
0
        }
2853
2
        last_scanned_table_id = table_id;
2854
2
        is_recycled = false;
2855
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2856
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2857
2
        std::unique_ptr<Transaction> txn;
2858
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2859
2
        if (err != TxnErrorCode::TXN_OK) {
2860
0
            return -1;
2861
0
        }
2862
2
        std::unique_ptr<RangeGetIterator> iter;
2863
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2864
2
        if (err != TxnErrorCode::TXN_OK) {
2865
0
            return -1;
2866
0
        }
2867
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2868
1
            return 0;
2869
1
        }
2870
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2871
        // 1. Remove all partition version kvs of this table
2872
1
        auto partition_version_key_begin =
2873
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2874
1
        auto partition_version_key_end =
2875
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2876
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2877
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2878
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2879
1
                     << " table_id=" << table_id;
2880
        // 2. Remove the table version kv of this table
2881
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2882
1
        txn->remove(tbl_version_key);
2883
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2884
        // 3. Remove mow delete bitmap update lock and tablet job lock
2885
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2886
1
        txn->remove(lock_key);
2887
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2888
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2889
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2890
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2891
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2892
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2893
1
                     << " table_id=" << table_id;
2894
1
        err = txn->commit();
2895
1
        if (err != TxnErrorCode::TXN_OK) {
2896
0
            return -1;
2897
0
        }
2898
1
        metrics_context.total_recycled_num = ++num_recycled;
2899
1
        metrics_context.report();
2900
1
        is_recycled = true;
2901
1
        return 0;
2902
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2840
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2841
2
        ++num_scanned;
2842
2
        auto k1 = k;
2843
2
        k1.remove_prefix(1);
2844
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2845
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2846
2
        decode_key(&k1, &out);
2847
2
        DCHECK_EQ(out.size(), 6) << k;
2848
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2849
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2850
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2851
0
            return 0;
2852
0
        }
2853
2
        last_scanned_table_id = table_id;
2854
2
        is_recycled = false;
2855
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2856
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2857
2
        std::unique_ptr<Transaction> txn;
2858
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2859
2
        if (err != TxnErrorCode::TXN_OK) {
2860
0
            return -1;
2861
0
        }
2862
2
        std::unique_ptr<RangeGetIterator> iter;
2863
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2864
2
        if (err != TxnErrorCode::TXN_OK) {
2865
0
            return -1;
2866
0
        }
2867
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2868
1
            return 0;
2869
1
        }
2870
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2871
        // 1. Remove all partition version kvs of this table
2872
1
        auto partition_version_key_begin =
2873
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2874
1
        auto partition_version_key_end =
2875
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2876
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2877
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2878
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2879
1
                     << " table_id=" << table_id;
2880
        // 2. Remove the table version kv of this table
2881
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2882
1
        txn->remove(tbl_version_key);
2883
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2884
        // 3. Remove mow delete bitmap update lock and tablet job lock
2885
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2886
1
        txn->remove(lock_key);
2887
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2888
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2889
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2890
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2891
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2892
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2893
1
                     << " table_id=" << table_id;
2894
1
        err = txn->commit();
2895
1
        if (err != TxnErrorCode::TXN_OK) {
2896
0
            return -1;
2897
0
        }
2898
1
        metrics_context.total_recycled_num = ++num_recycled;
2899
1
        metrics_context.report();
2900
1
        is_recycled = true;
2901
1
        return 0;
2902
1
    };
2903
2904
12
    if (config::enable_recycler_stats_metrics) {
2905
0
        scan_and_statistics_versions();
2906
0
    }
2907
    // recycle_func and loop_done for scan and recycle
2908
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2909
14
}
2910
2911
3
int InstanceRecycler::recycle_orphan_partitions() {
2912
3
    int64_t num_scanned = 0;
2913
3
    int64_t num_recycled = 0;
2914
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2915
2916
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2917
3
            .tag("instance_id", instance_id_);
2918
2919
3
    auto start_time = steady_clock::now();
2920
2921
3
    DORIS_CLOUD_DEFER {
2922
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2923
3
        metrics_context.finish_report();
2924
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2925
3
                .tag("instance_id", instance_id_)
2926
3
                .tag("num_scanned", num_scanned)
2927
3
                .tag("num_recycled", num_recycled);
2928
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2921
3
    DORIS_CLOUD_DEFER {
2922
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2923
3
        metrics_context.finish_report();
2924
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2925
3
                .tag("instance_id", instance_id_)
2926
3
                .tag("num_scanned", num_scanned)
2927
3
                .tag("num_recycled", num_recycled);
2928
3
    };
2929
2930
3
    bool is_empty_table = false;        // whether the table has no indexes
2931
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2932
3
    int64_t current_table_id = 0;       // current scanning table id
2933
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2934
3
                         &current_table_id, &is_table_kvs_recycled,
2935
3
                         this](std::string_view k, std::string_view) {
2936
2
        ++num_scanned;
2937
2938
2
        std::string_view k1(k);
2939
2
        int64_t db_id, table_id, partition_id;
2940
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2941
2
                                                            &partition_id)) {
2942
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2943
0
            return -1;
2944
2
        } else if (table_id != current_table_id) {
2945
2
            current_table_id = table_id;
2946
2
            is_table_kvs_recycled = false;
2947
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2948
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2949
2
            if (err != TxnErrorCode::TXN_OK) {
2950
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2951
0
                             << " table_id=" << table_id << " err=" << err;
2952
0
                return -1;
2953
0
            }
2954
2
        }
2955
2956
2
        if (!is_empty_table) {
2957
            // table is not empty, skip recycle
2958
1
            return 0;
2959
1
        }
2960
2961
1
        std::unique_ptr<Transaction> txn;
2962
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2963
1
        if (err != TxnErrorCode::TXN_OK) {
2964
0
            return -1;
2965
0
        }
2966
2967
        // 1. Remove all partition related kvs
2968
1
        std::string partition_meta_key =
2969
1
                versioned::meta_partition_key({instance_id_, partition_id});
2970
1
        std::string partition_index_key =
2971
1
                versioned::partition_index_key({instance_id_, partition_id});
2972
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2973
1
                {instance_id_, db_id, table_id, partition_id});
2974
1
        std::string partition_version_key =
2975
1
                versioned::partition_version_key({instance_id_, partition_id});
2976
1
        txn->remove(partition_index_key);
2977
1
        txn->remove(partition_inverted_key);
2978
1
        versioned_remove_all(txn.get(), partition_meta_key);
2979
1
        versioned_remove_all(txn.get(), partition_version_key);
2980
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2981
1
                     << " table_id=" << table_id << " db_id=" << db_id
2982
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2983
1
                     << " partition_version_key=" << hex(partition_version_key);
2984
2985
1
        if (!is_table_kvs_recycled) {
2986
1
            is_table_kvs_recycled = true;
2987
2988
            // 2. Remove the table version kv of this table
2989
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2990
1
            versioned_remove_all(txn.get(), table_version_key);
2991
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2992
            // 3. Remove mow delete bitmap update lock and tablet job lock
2993
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2994
1
            txn->remove(lock_key);
2995
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2996
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2997
1
            std::string tablet_job_key_end =
2998
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2999
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3000
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3001
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3002
1
                         << " table_id=" << table_id;
3003
1
        }
3004
3005
1
        err = txn->commit();
3006
1
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            return -1;
3008
0
        }
3009
1
        metrics_context.total_recycled_num = ++num_recycled;
3010
1
        metrics_context.report();
3011
1
        return 0;
3012
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
2935
2
                         this](std::string_view k, std::string_view) {
2936
2
        ++num_scanned;
2937
2938
2
        std::string_view k1(k);
2939
2
        int64_t db_id, table_id, partition_id;
2940
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2941
2
                                                            &partition_id)) {
2942
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2943
0
            return -1;
2944
2
        } else if (table_id != current_table_id) {
2945
2
            current_table_id = table_id;
2946
2
            is_table_kvs_recycled = false;
2947
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2948
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2949
2
            if (err != TxnErrorCode::TXN_OK) {
2950
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2951
0
                             << " table_id=" << table_id << " err=" << err;
2952
0
                return -1;
2953
0
            }
2954
2
        }
2955
2956
2
        if (!is_empty_table) {
2957
            // table is not empty, skip recycle
2958
1
            return 0;
2959
1
        }
2960
2961
1
        std::unique_ptr<Transaction> txn;
2962
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2963
1
        if (err != TxnErrorCode::TXN_OK) {
2964
0
            return -1;
2965
0
        }
2966
2967
        // 1. Remove all partition related kvs
2968
1
        std::string partition_meta_key =
2969
1
                versioned::meta_partition_key({instance_id_, partition_id});
2970
1
        std::string partition_index_key =
2971
1
                versioned::partition_index_key({instance_id_, partition_id});
2972
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2973
1
                {instance_id_, db_id, table_id, partition_id});
2974
1
        std::string partition_version_key =
2975
1
                versioned::partition_version_key({instance_id_, partition_id});
2976
1
        txn->remove(partition_index_key);
2977
1
        txn->remove(partition_inverted_key);
2978
1
        versioned_remove_all(txn.get(), partition_meta_key);
2979
1
        versioned_remove_all(txn.get(), partition_version_key);
2980
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2981
1
                     << " table_id=" << table_id << " db_id=" << db_id
2982
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2983
1
                     << " partition_version_key=" << hex(partition_version_key);
2984
2985
1
        if (!is_table_kvs_recycled) {
2986
1
            is_table_kvs_recycled = true;
2987
2988
            // 2. Remove the table version kv of this table
2989
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2990
1
            versioned_remove_all(txn.get(), table_version_key);
2991
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2992
            // 3. Remove mow delete bitmap update lock and tablet job lock
2993
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2994
1
            txn->remove(lock_key);
2995
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2996
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2997
1
            std::string tablet_job_key_end =
2998
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2999
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3000
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3001
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3002
1
                         << " table_id=" << table_id;
3003
1
        }
3004
3005
1
        err = txn->commit();
3006
1
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            return -1;
3008
0
        }
3009
1
        metrics_context.total_recycled_num = ++num_recycled;
3010
1
        metrics_context.report();
3011
1
        return 0;
3012
1
    };
3013
3014
    // recycle_func and loop_done for scan and recycle
3015
3
    return scan_and_recycle(
3016
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3017
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3018
3
            std::move(recycle_func));
3019
3
}
3020
3021
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3022
                                      RecyclerMetricsContext& metrics_context,
3023
52
                                      int64_t partition_id) {
3024
52
    bool is_multi_version =
3025
52
            instance_info_.has_multi_version_status() &&
3026
52
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3027
52
    int64_t num_scanned = 0;
3028
52
    std::atomic_long num_recycled = 0;
3029
3030
52
    std::string tablet_key_begin, tablet_key_end;
3031
52
    std::string stats_key_begin, stats_key_end;
3032
52
    std::string job_key_begin, job_key_end;
3033
3034
52
    std::string tablet_belongs;
3035
52
    if (partition_id > 0) {
3036
        // recycle tablets in a partition belonging to the index
3037
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3038
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3039
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3040
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3041
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3042
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3043
33
        tablet_belongs = "partition";
3044
33
    } else {
3045
        // recycle tablets in the index
3046
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3047
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3048
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3049
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3050
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3051
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3052
19
        tablet_belongs = "index";
3053
19
    }
3054
3055
52
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3056
52
            .tag("table_id", table_id)
3057
52
            .tag("index_id", index_id)
3058
52
            .tag("partition_id", partition_id);
3059
3060
52
    auto start_time = steady_clock::now();
3061
3062
52
    DORIS_CLOUD_DEFER {
3063
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3064
52
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3065
52
                .tag("instance_id", instance_id_)
3066
52
                .tag("table_id", table_id)
3067
52
                .tag("index_id", index_id)
3068
52
                .tag("partition_id", partition_id)
3069
52
                .tag("num_scanned", num_scanned)
3070
52
                .tag("num_recycled", num_recycled);
3071
52
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3062
4
    DORIS_CLOUD_DEFER {
3063
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3064
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3065
4
                .tag("instance_id", instance_id_)
3066
4
                .tag("table_id", table_id)
3067
4
                .tag("index_id", index_id)
3068
4
                .tag("partition_id", partition_id)
3069
4
                .tag("num_scanned", num_scanned)
3070
4
                .tag("num_recycled", num_recycled);
3071
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3062
48
    DORIS_CLOUD_DEFER {
3063
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3064
48
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3065
48
                .tag("instance_id", instance_id_)
3066
48
                .tag("table_id", table_id)
3067
48
                .tag("index_id", index_id)
3068
48
                .tag("partition_id", partition_id)
3069
48
                .tag("num_scanned", num_scanned)
3070
48
                .tag("num_recycled", num_recycled);
3071
48
    };
3072
3073
    // The tablet key and id which have been recycled.
3074
52
    struct TabletInfo {
3075
52
        std::string_view tablet_meta_key;
3076
52
        int64_t tablet_id;
3077
52
    };
3078
52
    SyncExecutor<TabletInfo> sync_executor(
3079
52
            _thread_pool_group.recycle_tablet_pool,
3080
52
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3081
52
                        index_id, partition_id),
3082
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3082
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3082
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3083
3084
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3085
52
    std::vector<std::string> init_rs_keys;
3086
52
    bool has_failure = false;
3087
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3088
8.25k
        ++num_scanned;
3089
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3090
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3091
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3092
0
            has_failure = true;
3093
0
            return -1;
3094
0
        }
3095
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3096
3097
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3098
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3099
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3100
4.00k
            has_failure = true;
3101
4.00k
            return -1;
3102
4.00k
        }
3103
3104
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3105
4.25k
        sync_executor.add(
3106
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3107
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3108
2
                        LOG_WARNING("failed to recycle tablet")
3109
2
                                .tag("instance_id", instance_id_)
3110
2
                                .tag("tablet_id", tid);
3111
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3112
2
                    }
3113
4.25k
                    ++num_recycled;
3114
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3115
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3116
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3106
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3107
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3108
0
                        LOG_WARNING("failed to recycle tablet")
3109
0
                                .tag("instance_id", instance_id_)
3110
0
                                .tag("tablet_id", tid);
3111
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3112
0
                    }
3113
4.00k
                    ++num_recycled;
3114
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3115
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3116
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3106
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3107
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3108
2
                        LOG_WARNING("failed to recycle tablet")
3109
2
                                .tag("instance_id", instance_id_)
3110
2
                                .tag("tablet_id", tid);
3111
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3112
2
                    }
3113
248
                    ++num_recycled;
3114
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3115
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3116
250
                });
3117
4.25k
        return 0;
3118
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3087
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3088
8.00k
        ++num_scanned;
3089
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3090
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3091
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3092
0
            has_failure = true;
3093
0
            return -1;
3094
0
        }
3095
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3096
3097
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3098
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3099
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3100
4.00k
            has_failure = true;
3101
4.00k
            return -1;
3102
4.00k
        }
3103
3104
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3105
4.00k
        sync_executor.add(
3106
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3107
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3108
4.00k
                        LOG_WARNING("failed to recycle tablet")
3109
4.00k
                                .tag("instance_id", instance_id_)
3110
4.00k
                                .tag("tablet_id", tid);
3111
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3112
4.00k
                    }
3113
4.00k
                    ++num_recycled;
3114
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3115
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3116
4.00k
                });
3117
4.00k
        return 0;
3118
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3087
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3088
251
        ++num_scanned;
3089
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3090
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3091
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3092
0
            has_failure = true;
3093
0
            return -1;
3094
0
        }
3095
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3096
3097
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3098
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3099
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3100
1
            has_failure = true;
3101
1
            return -1;
3102
1
        }
3103
3104
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3105
250
        sync_executor.add(
3106
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3107
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3108
250
                        LOG_WARNING("failed to recycle tablet")
3109
250
                                .tag("instance_id", instance_id_)
3110
250
                                .tag("tablet_id", tid);
3111
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3112
250
                    }
3113
250
                    ++num_recycled;
3114
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3115
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3116
250
                });
3117
250
        return 0;
3118
250
    };
3119
3120
52
    auto loop_done = [&, this]() -> int {
3121
52
        int ret = 0;
3122
52
        bool finished = true;
3123
52
        bool has_empty_key = false;
3124
52
        DORIS_CLOUD_DEFER {
3125
52
            init_rs_keys.clear();
3126
52
            has_failure = false;
3127
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3124
4
        DORIS_CLOUD_DEFER {
3125
4
            init_rs_keys.clear();
3126
4
            has_failure = false;
3127
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3124
48
        DORIS_CLOUD_DEFER {
3125
48
            init_rs_keys.clear();
3126
48
            has_failure = false;
3127
48
        };
3128
52
        auto tablets_info = sync_executor.when_all(&finished);
3129
52
        if (!finished) {
3130
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3131
1
            return -1;
3132
1
        }
3133
3134
51
        size_t size_before_erase = tablets_info.size();
3135
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
3135
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
3135
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3136
51
        if (tablets_info.empty()) {
3137
2
            return size_before_erase == 0 ? 0 : -1;
3138
49
        } else if (size_before_erase != tablets_info.size()) {
3139
1
            has_empty_key = true;
3140
1
        }
3141
3142
49
        ret = has_empty_key ? -1 : 0;
3143
        // sort the vector using key's order
3144
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3145
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3146
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3144
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3145
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3146
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3144
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3145
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3146
958
        });
3147
49
        std::unique_ptr<Transaction> txn;
3148
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3149
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3150
0
            return -1;
3151
0
        }
3152
49
        std::string tablet_key_end;
3153
49
        if (!tablets_info.empty()) {
3154
49
            if (!has_empty_key && !has_failure) {
3155
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3156
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3157
47
            } else {
3158
8
                for (auto& tablet_info : tablets_info) {
3159
8
                    txn->remove(tablet_info.tablet_meta_key);
3160
8
                }
3161
2
            }
3162
49
        }
3163
49
        if (is_multi_version) {
3164
6
            for (auto& tablet_info : tablets_info) {
3165
                // Remove all versions of tablet compact stats for recycled tablet
3166
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3167
6
                LOG_INFO("remove versioned tablet compact stats key")
3168
6
                        .tag("compact_stats_key", hex(k));
3169
6
                versioned_remove_all(txn.get(), k);
3170
6
            }
3171
6
            for (auto& tablet_info : tablets_info) {
3172
                // Remove all versions of tablet load stats for recycled tablet
3173
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3174
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3175
6
                versioned_remove_all(txn.get(), k);
3176
6
            }
3177
6
            for (auto& tablet_info : tablets_info) {
3178
                // Remove all versions of meta tablet for recycled tablet
3179
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3180
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3181
6
                versioned_remove_all(txn.get(), k);
3182
6
            }
3183
5
        }
3184
4.25k
        for (auto& tablet_info : tablets_info) {
3185
4.25k
            std::string k;
3186
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3187
4.25k
            txn->remove(k);
3188
4.25k
        }
3189
4.25k
        for (auto& tablet_info : tablets_info) {
3190
4.25k
            std::string k;
3191
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3192
4.25k
            txn->remove(k);
3193
4.25k
        }
3194
49
        for (auto& k : init_rs_keys) {
3195
0
            txn->remove(k);
3196
0
        }
3197
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3198
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3199
0
                         << ", err=" << err;
3200
0
            return -1;
3201
0
        }
3202
49
        return ret;
3203
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3120
4
    auto loop_done = [&, this]() -> int {
3121
4
        int ret = 0;
3122
4
        bool finished = true;
3123
4
        bool has_empty_key = false;
3124
4
        DORIS_CLOUD_DEFER {
3125
4
            init_rs_keys.clear();
3126
4
            has_failure = false;
3127
4
        };
3128
4
        auto tablets_info = sync_executor.when_all(&finished);
3129
4
        if (!finished) {
3130
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3131
0
            return -1;
3132
0
        }
3133
3134
4
        size_t size_before_erase = tablets_info.size();
3135
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3136
4
        if (tablets_info.empty()) {
3137
2
            return size_before_erase == 0 ? 0 : -1;
3138
2
        } else if (size_before_erase != tablets_info.size()) {
3139
0
            has_empty_key = true;
3140
0
        }
3141
3142
2
        ret = has_empty_key ? -1 : 0;
3143
        // sort the vector using key's order
3144
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3145
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3146
2
        });
3147
2
        std::unique_ptr<Transaction> txn;
3148
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3149
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3150
0
            return -1;
3151
0
        }
3152
2
        std::string tablet_key_end;
3153
2
        if (!tablets_info.empty()) {
3154
2
            if (!has_empty_key && !has_failure) {
3155
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3156
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3157
2
            } else {
3158
0
                for (auto& tablet_info : tablets_info) {
3159
0
                    txn->remove(tablet_info.tablet_meta_key);
3160
0
                }
3161
0
            }
3162
2
        }
3163
2
        if (is_multi_version) {
3164
0
            for (auto& tablet_info : tablets_info) {
3165
                // Remove all versions of tablet compact stats for recycled tablet
3166
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3167
0
                LOG_INFO("remove versioned tablet compact stats key")
3168
0
                        .tag("compact_stats_key", hex(k));
3169
0
                versioned_remove_all(txn.get(), k);
3170
0
            }
3171
0
            for (auto& tablet_info : tablets_info) {
3172
                // Remove all versions of tablet load stats for recycled tablet
3173
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3174
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3175
0
                versioned_remove_all(txn.get(), k);
3176
0
            }
3177
0
            for (auto& tablet_info : tablets_info) {
3178
                // Remove all versions of meta tablet for recycled tablet
3179
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3180
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3181
0
                versioned_remove_all(txn.get(), k);
3182
0
            }
3183
0
        }
3184
4.00k
        for (auto& tablet_info : tablets_info) {
3185
4.00k
            std::string k;
3186
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3187
4.00k
            txn->remove(k);
3188
4.00k
        }
3189
4.00k
        for (auto& tablet_info : tablets_info) {
3190
4.00k
            std::string k;
3191
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3192
4.00k
            txn->remove(k);
3193
4.00k
        }
3194
2
        for (auto& k : init_rs_keys) {
3195
0
            txn->remove(k);
3196
0
        }
3197
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3198
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3199
0
                         << ", err=" << err;
3200
0
            return -1;
3201
0
        }
3202
2
        return ret;
3203
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3120
48
    auto loop_done = [&, this]() -> int {
3121
48
        int ret = 0;
3122
48
        bool finished = true;
3123
48
        bool has_empty_key = false;
3124
48
        DORIS_CLOUD_DEFER {
3125
48
            init_rs_keys.clear();
3126
48
            has_failure = false;
3127
48
        };
3128
48
        auto tablets_info = sync_executor.when_all(&finished);
3129
48
        if (!finished) {
3130
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3131
1
            return -1;
3132
1
        }
3133
3134
47
        size_t size_before_erase = tablets_info.size();
3135
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3136
47
        if (tablets_info.empty()) {
3137
0
            return size_before_erase == 0 ? 0 : -1;
3138
47
        } else if (size_before_erase != tablets_info.size()) {
3139
1
            has_empty_key = true;
3140
1
        }
3141
3142
47
        ret = has_empty_key ? -1 : 0;
3143
        // sort the vector using key's order
3144
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3145
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3146
47
        });
3147
47
        std::unique_ptr<Transaction> txn;
3148
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3149
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3150
0
            return -1;
3151
0
        }
3152
47
        std::string tablet_key_end;
3153
47
        if (!tablets_info.empty()) {
3154
47
            if (!has_empty_key && !has_failure) {
3155
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3156
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3157
45
            } else {
3158
8
                for (auto& tablet_info : tablets_info) {
3159
8
                    txn->remove(tablet_info.tablet_meta_key);
3160
8
                }
3161
2
            }
3162
47
        }
3163
47
        if (is_multi_version) {
3164
6
            for (auto& tablet_info : tablets_info) {
3165
                // Remove all versions of tablet compact stats for recycled tablet
3166
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3167
6
                LOG_INFO("remove versioned tablet compact stats key")
3168
6
                        .tag("compact_stats_key", hex(k));
3169
6
                versioned_remove_all(txn.get(), k);
3170
6
            }
3171
6
            for (auto& tablet_info : tablets_info) {
3172
                // Remove all versions of tablet load stats for recycled tablet
3173
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3174
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3175
6
                versioned_remove_all(txn.get(), k);
3176
6
            }
3177
6
            for (auto& tablet_info : tablets_info) {
3178
                // Remove all versions of meta tablet for recycled tablet
3179
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3180
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3181
6
                versioned_remove_all(txn.get(), k);
3182
6
            }
3183
5
        }
3184
248
        for (auto& tablet_info : tablets_info) {
3185
248
            std::string k;
3186
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3187
248
            txn->remove(k);
3188
248
        }
3189
248
        for (auto& tablet_info : tablets_info) {
3190
248
            std::string k;
3191
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3192
248
            txn->remove(k);
3193
248
        }
3194
47
        for (auto& k : init_rs_keys) {
3195
0
            txn->remove(k);
3196
0
        }
3197
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3198
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3199
0
                         << ", err=" << err;
3200
0
            return -1;
3201
0
        }
3202
47
        return ret;
3203
47
    };
3204
3205
52
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3206
52
                               std::move(loop_done));
3207
52
    if (ret != 0) {
3208
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3209
5
        return ret;
3210
5
    }
3211
3212
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3213
47
    std::unique_ptr<Transaction> txn;
3214
47
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3215
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3216
0
        return -1;
3217
0
    }
3218
47
    txn->remove(stats_key_begin, stats_key_end);
3219
47
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3220
47
                 << " end=" << hex(stats_key_end);
3221
47
    txn->remove(job_key_begin, job_key_end);
3222
47
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3223
47
    std::string schema_key_begin, schema_key_end;
3224
47
    std::string schema_dict_key;
3225
47
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3226
47
    if (partition_id <= 0) {
3227
        // Delete schema kv of this index
3228
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3229
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3230
15
        txn->remove(schema_key_begin, schema_key_end);
3231
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3232
15
                     << " end=" << hex(schema_key_end);
3233
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3234
15
        txn->remove(schema_dict_key);
3235
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3236
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3237
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3238
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3239
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3240
15
                     << " end=" << hex(versioned_schema_key_end);
3241
15
    }
3242
3243
47
    TxnErrorCode err = txn->commit();
3244
47
    if (err != TxnErrorCode::TXN_OK) {
3245
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3246
0
                     << " err=" << err;
3247
0
        return -1;
3248
0
    }
3249
3250
47
    return ret;
3251
47
}
3252
3253
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3254
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3255
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3256
5.61k
    if (num_segments <= 0) return 0;
3257
3258
5.61k
    std::vector<std::string> file_paths;
3259
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3260
0
        return -1;
3261
0
    }
3262
3263
    // Process inverted indexes
3264
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3265
    // default format as v1.
3266
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3267
5.61k
    bool delete_rowset_data_by_prefix = false;
3268
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3269
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3270
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3271
0
        delete_rowset_data_by_prefix = true;
3272
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3273
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3274
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3275
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3276
10.0k
            }
3277
10.0k
        }
3278
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3279
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3280
2.00k
        }
3281
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3282
        // schema version and index id are not found, delete rowset data by prefix directly.
3283
0
        delete_rowset_data_by_prefix = true;
3284
809
    } else {
3285
        // otherwise, try to get schema kv
3286
809
        InvertedIndexInfo index_info;
3287
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3288
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3289
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3290
809
                                 &inverted_index_get_ret);
3291
809
        if (inverted_index_get_ret == 0) {
3292
809
            index_format = index_info.first;
3293
809
            index_ids = index_info.second;
3294
809
        } else if (inverted_index_get_ret == 1) {
3295
            // 1. Schema kv not found means tablet has been recycled
3296
            // Maybe some tablet recycle failed by some bugs
3297
            // We need to delete again to double check
3298
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3299
            // because we are uncertain about the inverted index information.
3300
            // If there are inverted indexes, some data might not be deleted,
3301
            // but this is acceptable as we have made our best effort to delete the data.
3302
0
            LOG_INFO(
3303
0
                    "delete rowset data schema kv not found, need to delete again to double "
3304
0
                    "check")
3305
0
                    .tag("instance_id", instance_id_)
3306
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3307
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3308
            // Currently index_ids is guaranteed to be empty,
3309
            // but we clear it again here as a safeguard against future code changes
3310
            // that might cause index_ids to no longer be empty
3311
0
            index_format = InvertedIndexStorageFormatPB::V2;
3312
0
            index_ids.clear();
3313
0
        } else {
3314
            // failed to get schema kv, delete rowset data by prefix directly.
3315
0
            delete_rowset_data_by_prefix = true;
3316
0
        }
3317
809
    }
3318
3319
5.61k
    if (delete_rowset_data_by_prefix) {
3320
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3321
0
                                  rs_meta_pb.rowset_id_v2());
3322
0
    }
3323
3324
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3325
5.61k
    if (it == accessor_map_.end()) {
3326
1.60k
        LOG_WARNING("instance has no such resource id")
3327
1.60k
                .tag("instance_id", instance_id_)
3328
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3329
1.60k
        return -1;
3330
1.60k
    }
3331
4.01k
    auto& accessor = it->second;
3332
3333
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3334
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3335
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3336
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3337
20.0k
                                         &file_paths);
3338
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3339
40.0k
            for (const auto& index_id : index_ids) {
3340
40.0k
                add_file_to_delete_if_not_packed(
3341
40.0k
                        rs_meta_pb,
3342
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3343
40.0k
                                               index_id.second),
3344
40.0k
                        &file_paths);
3345
40.0k
            }
3346
20.0k
        } else if (!index_ids.empty()) {
3347
0
            add_file_to_delete_if_not_packed(
3348
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3349
0
        }
3350
20.0k
    }
3351
3352
    // Process delete bitmap - check where it's stored.
3353
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3354
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3355
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3356
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3357
0
                .tag("instance_id", instance_id_)
3358
0
                .tag("tablet_id", tablet_id)
3359
0
                .tag("rowset_id", rowset_id);
3360
0
        return -1;
3361
0
    }
3362
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3363
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3364
2.00k
    }
3365
    // TODO(AlexYue): seems could do do batch
3366
4.01k
    return accessor->delete_files(file_paths);
3367
4.01k
}
3368
3369
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3370
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3371
62.3k
            .tag("instance_id", instance_id_)
3372
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3373
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3374
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3375
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3376
62.3k
    if (index_map.empty()) {
3377
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3378
62.3k
                .tag("instance_id", instance_id_)
3379
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3380
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3381
62.3k
        return 0;
3382
62.3k
    }
3383
3384
16
    struct PackedSmallFileInfo {
3385
16
        std::string small_file_path;
3386
16
    };
3387
16
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3388
16
    packed_file_updates.reserve(index_map.size());
3389
27
    for (const auto& [small_path, index_pb] : index_map) {
3390
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3391
0
            continue;
3392
0
        }
3393
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3394
27
                PackedSmallFileInfo {small_path});
3395
27
    }
3396
16
    if (packed_file_updates.empty()) {
3397
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3398
0
                .tag("instance_id", instance_id_)
3399
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3400
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3401
0
                .tag("index_map_size", index_map.size());
3402
0
        return 0;
3403
0
    }
3404
3405
16
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3406
16
    int ret = 0;
3407
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3408
24
        if (small_files.empty()) {
3409
0
            continue;
3410
0
        }
3411
3412
24
        bool success = false;
3413
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3414
24
            std::unique_ptr<Transaction> txn;
3415
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3416
24
            if (err != TxnErrorCode::TXN_OK) {
3417
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3418
0
                        .tag("instance_id", instance_id_)
3419
0
                        .tag("packed_file_path", packed_file_path)
3420
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3421
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3422
0
                        .tag("err", err);
3423
0
                ret = -1;
3424
0
                break;
3425
0
            }
3426
3427
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3428
24
            std::string packed_val;
3429
24
            err = txn->get(packed_key, &packed_val);
3430
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3431
0
                LOG_WARNING("packed file info not found when recycling rowset")
3432
0
                        .tag("instance_id", instance_id_)
3433
0
                        .tag("packed_file_path", packed_file_path)
3434
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3435
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3436
0
                        .tag("key", hex(packed_key))
3437
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3438
                // Skip this packed file entry and continue with others
3439
0
                success = true;
3440
0
                break;
3441
0
            }
3442
24
            if (err != TxnErrorCode::TXN_OK) {
3443
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3444
0
                        .tag("instance_id", instance_id_)
3445
0
                        .tag("packed_file_path", packed_file_path)
3446
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3447
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3448
0
                        .tag("err", err);
3449
0
                ret = -1;
3450
0
                break;
3451
0
            }
3452
3453
24
            cloud::PackedFileInfoPB packed_info;
3454
24
            if (!packed_info.ParseFromString(packed_val)) {
3455
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3456
0
                        .tag("instance_id", instance_id_)
3457
0
                        .tag("packed_file_path", packed_file_path)
3458
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3459
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3460
0
                ret = -1;
3461
0
                break;
3462
0
            }
3463
3464
24
            LOG_INFO("packed file update check")
3465
24
                    .tag("instance_id", instance_id_)
3466
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3467
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3468
24
                    .tag("merged_file_path", packed_file_path)
3469
24
                    .tag("requested_small_files", small_files.size())
3470
24
                    .tag("merge_entries", packed_info.slices_size());
3471
3472
24
            auto* small_file_entries = packed_info.mutable_slices();
3473
24
            int64_t changed_files = 0;
3474
24
            int64_t missing_entries = 0;
3475
24
            int64_t already_deleted = 0;
3476
27
            for (const auto& small_file_info : small_files) {
3477
27
                bool found = false;
3478
87
                for (auto& small_file_entry : *small_file_entries) {
3479
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3480
27
                        if (!small_file_entry.deleted()) {
3481
27
                            small_file_entry.set_deleted(true);
3482
27
                            if (!small_file_entry.corrected()) {
3483
27
                                small_file_entry.set_corrected(true);
3484
27
                            }
3485
27
                            ++changed_files;
3486
27
                        } else {
3487
0
                            ++already_deleted;
3488
0
                        }
3489
27
                        found = true;
3490
27
                        break;
3491
27
                    }
3492
87
                }
3493
27
                if (!found) {
3494
0
                    ++missing_entries;
3495
0
                    LOG_WARNING("packed file info missing small file entry")
3496
0
                            .tag("instance_id", instance_id_)
3497
0
                            .tag("packed_file_path", packed_file_path)
3498
0
                            .tag("small_file_path", small_file_info.small_file_path)
3499
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3500
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3501
0
                }
3502
27
            }
3503
3504
24
            if (changed_files == 0) {
3505
0
                LOG_INFO("skip merge file update: no merge entries changed")
3506
0
                        .tag("instance_id", instance_id_)
3507
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3508
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3509
0
                        .tag("merged_file_path", packed_file_path)
3510
0
                        .tag("missing_entries", missing_entries)
3511
0
                        .tag("already_deleted", already_deleted)
3512
0
                        .tag("requested_small_files", small_files.size())
3513
0
                        .tag("merge_entries", packed_info.slices_size());
3514
0
                success = true;
3515
0
                break;
3516
0
            }
3517
3518
            // Calculate remaining files
3519
24
            int64_t left_file_count = 0;
3520
24
            int64_t left_file_bytes = 0;
3521
141
            for (const auto& small_file_entry : packed_info.slices()) {
3522
141
                if (!small_file_entry.deleted()) {
3523
57
                    ++left_file_count;
3524
57
                    left_file_bytes += small_file_entry.size();
3525
57
                }
3526
141
            }
3527
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3528
24
            packed_info.set_ref_cnt(left_file_count);
3529
24
            LOG_INFO("updated packed file reference info")
3530
24
                    .tag("instance_id", instance_id_)
3531
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3532
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3533
24
                    .tag("packed_file_path", packed_file_path)
3534
24
                    .tag("ref_cnt", left_file_count)
3535
24
                    .tag("left_file_bytes", left_file_bytes);
3536
3537
24
            if (left_file_count == 0) {
3538
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3539
7
            }
3540
3541
24
            std::string updated_val;
3542
24
            if (!packed_info.SerializeToString(&updated_val)) {
3543
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3544
0
                        .tag("instance_id", instance_id_)
3545
0
                        .tag("packed_file_path", packed_file_path)
3546
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3547
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3548
0
                ret = -1;
3549
0
                break;
3550
0
            }
3551
3552
24
            txn->put(packed_key, updated_val);
3553
24
            err = txn->commit();
3554
24
            if (err == TxnErrorCode::TXN_OK) {
3555
24
                success = true;
3556
24
                if (left_file_count == 0) {
3557
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3558
7
                            .tag("instance_id", instance_id_)
3559
7
                            .tag("packed_file_path", packed_file_path);
3560
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3561
0
                        ret = -1;
3562
0
                    }
3563
7
                }
3564
24
                break;
3565
24
            }
3566
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3567
0
                if (attempt >= max_retry_times) {
3568
0
                    LOG_WARNING("packed file info update conflict after max retry")
3569
0
                            .tag("instance_id", instance_id_)
3570
0
                            .tag("packed_file_path", packed_file_path)
3571
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3572
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3573
0
                            .tag("changed_files", changed_files)
3574
0
                            .tag("attempt", attempt);
3575
0
                    ret = -1;
3576
0
                    break;
3577
0
                }
3578
0
                LOG_WARNING("packed file info update conflict, retrying")
3579
0
                        .tag("instance_id", instance_id_)
3580
0
                        .tag("packed_file_path", packed_file_path)
3581
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3582
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3583
0
                        .tag("changed_files", changed_files)
3584
0
                        .tag("attempt", attempt);
3585
0
                sleep_for_packed_file_retry();
3586
0
                continue;
3587
0
            }
3588
3589
0
            LOG_WARNING("failed to commit packed file info update")
3590
0
                    .tag("instance_id", instance_id_)
3591
0
                    .tag("packed_file_path", packed_file_path)
3592
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3593
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3594
0
                    .tag("err", err)
3595
0
                    .tag("changed_files", changed_files);
3596
0
            ret = -1;
3597
0
            break;
3598
0
        }
3599
3600
24
        if (!success) {
3601
0
            ret = -1;
3602
0
        }
3603
24
    }
3604
3605
16
    return ret;
3606
16
}
3607
3608
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3609
        int64_t tablet_id, const std::string& rowset_id,
3610
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3611
58.2k
    if (out_storage_type) {
3612
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3613
58.2k
    }
3614
3615
    // Get delete bitmap storage info from FDB
3616
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3617
58.2k
    std::unique_ptr<Transaction> txn;
3618
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3619
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3620
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3621
0
                .tag("instance_id", instance_id_)
3622
0
                .tag("tablet_id", tablet_id)
3623
0
                .tag("rowset_id", rowset_id)
3624
0
                .tag("err", err);
3625
0
        return -1;
3626
0
    }
3627
3628
58.2k
    std::string dbm_val;
3629
58.2k
    err = txn->get(dbm_key, &dbm_val);
3630
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3631
        // No delete bitmap for this rowset, nothing to do
3632
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3633
4.63k
                .tag("instance_id", instance_id_)
3634
4.63k
                .tag("tablet_id", tablet_id)
3635
4.63k
                .tag("rowset_id", rowset_id);
3636
4.63k
        return 0;
3637
4.63k
    }
3638
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3639
0
        LOG_WARNING("failed to get delete bitmap storage")
3640
0
                .tag("instance_id", instance_id_)
3641
0
                .tag("tablet_id", tablet_id)
3642
0
                .tag("rowset_id", rowset_id)
3643
0
                .tag("err", err);
3644
0
        return -1;
3645
0
    }
3646
3647
53.5k
    DeleteBitmapStoragePB storage;
3648
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3649
0
        LOG_WARNING("failed to parse delete bitmap storage")
3650
0
                .tag("instance_id", instance_id_)
3651
0
                .tag("tablet_id", tablet_id)
3652
0
                .tag("rowset_id", rowset_id);
3653
0
        return -1;
3654
0
    }
3655
3656
53.5k
    if (storage.store_in_fdb()) {
3657
0
        if (out_storage_type) {
3658
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3659
0
        }
3660
0
        return 0;
3661
0
    }
3662
3663
    // Check if delete bitmap is stored in standalone file.
3664
53.5k
    if (!storage.has_packed_slice_location() ||
3665
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3666
53.5k
        if (out_storage_type) {
3667
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3668
53.5k
        }
3669
53.5k
        return 0;
3670
53.5k
    }
3671
3672
18.4E
    if (out_storage_type) {
3673
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3674
0
    }
3675
3676
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3677
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3678
3679
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3680
18.4E
            .tag("instance_id", instance_id_)
3681
18.4E
            .tag("tablet_id", tablet_id)
3682
18.4E
            .tag("rowset_id", rowset_id)
3683
18.4E
            .tag("packed_file_path", packed_file_path);
3684
3685
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3686
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3687
0
        std::unique_ptr<Transaction> update_txn;
3688
0
        err = txn_kv_->create_txn(&update_txn);
3689
0
        if (err != TxnErrorCode::TXN_OK) {
3690
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3691
0
                    .tag("instance_id", instance_id_)
3692
0
                    .tag("tablet_id", tablet_id)
3693
0
                    .tag("rowset_id", rowset_id)
3694
0
                    .tag("err", err);
3695
0
            return -1;
3696
0
        }
3697
3698
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3699
0
        std::string packed_val;
3700
0
        err = update_txn->get(packed_key, &packed_val);
3701
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3702
0
            LOG_WARNING("packed file info not found for delete bitmap")
3703
0
                    .tag("instance_id", instance_id_)
3704
0
                    .tag("tablet_id", tablet_id)
3705
0
                    .tag("rowset_id", rowset_id)
3706
0
                    .tag("packed_file_path", packed_file_path);
3707
0
            return 0;
3708
0
        }
3709
0
        if (err != TxnErrorCode::TXN_OK) {
3710
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3711
0
                    .tag("instance_id", instance_id_)
3712
0
                    .tag("tablet_id", tablet_id)
3713
0
                    .tag("rowset_id", rowset_id)
3714
0
                    .tag("packed_file_path", packed_file_path)
3715
0
                    .tag("err", err);
3716
0
            return -1;
3717
0
        }
3718
3719
0
        cloud::PackedFileInfoPB packed_info;
3720
0
        if (!packed_info.ParseFromString(packed_val)) {
3721
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3722
0
                    .tag("instance_id", instance_id_)
3723
0
                    .tag("tablet_id", tablet_id)
3724
0
                    .tag("rowset_id", rowset_id)
3725
0
                    .tag("packed_file_path", packed_file_path);
3726
0
            return -1;
3727
0
        }
3728
3729
        // Find and mark the small file entry as deleted
3730
        // Use tablet_id and rowset_id to match entry instead of path,
3731
        // because path format may vary with path_version (with or without shard prefix)
3732
0
        auto* entries = packed_info.mutable_slices();
3733
0
        bool found = false;
3734
0
        bool already_deleted = false;
3735
0
        for (auto& entry : *entries) {
3736
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3737
0
                if (!entry.deleted()) {
3738
0
                    entry.set_deleted(true);
3739
0
                    if (!entry.corrected()) {
3740
0
                        entry.set_corrected(true);
3741
0
                    }
3742
0
                } else {
3743
0
                    already_deleted = true;
3744
0
                }
3745
0
                found = true;
3746
0
                break;
3747
0
            }
3748
0
        }
3749
3750
0
        if (!found) {
3751
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3752
0
                    .tag("instance_id", instance_id_)
3753
0
                    .tag("tablet_id", tablet_id)
3754
0
                    .tag("rowset_id", rowset_id)
3755
0
                    .tag("packed_file_path", packed_file_path);
3756
0
            return 0;
3757
0
        }
3758
3759
0
        if (already_deleted) {
3760
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3761
0
                    .tag("instance_id", instance_id_)
3762
0
                    .tag("tablet_id", tablet_id)
3763
0
                    .tag("rowset_id", rowset_id)
3764
0
                    .tag("packed_file_path", packed_file_path);
3765
0
            return 0;
3766
0
        }
3767
3768
        // Calculate remaining files
3769
0
        int64_t left_file_count = 0;
3770
0
        int64_t left_file_bytes = 0;
3771
0
        for (const auto& entry : packed_info.slices()) {
3772
0
            if (!entry.deleted()) {
3773
0
                ++left_file_count;
3774
0
                left_file_bytes += entry.size();
3775
0
            }
3776
0
        }
3777
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3778
0
        packed_info.set_ref_cnt(left_file_count);
3779
3780
0
        if (left_file_count == 0) {
3781
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3782
0
        }
3783
3784
0
        std::string updated_val;
3785
0
        if (!packed_info.SerializeToString(&updated_val)) {
3786
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3787
0
                    .tag("instance_id", instance_id_)
3788
0
                    .tag("tablet_id", tablet_id)
3789
0
                    .tag("rowset_id", rowset_id)
3790
0
                    .tag("packed_file_path", packed_file_path);
3791
0
            return -1;
3792
0
        }
3793
3794
0
        update_txn->put(packed_key, updated_val);
3795
0
        err = update_txn->commit();
3796
0
        if (err == TxnErrorCode::TXN_OK) {
3797
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3798
0
                    .tag("instance_id", instance_id_)
3799
0
                    .tag("tablet_id", tablet_id)
3800
0
                    .tag("rowset_id", rowset_id)
3801
0
                    .tag("packed_file_path", packed_file_path)
3802
0
                    .tag("left_file_count", left_file_count);
3803
0
            if (left_file_count == 0) {
3804
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3805
0
                    return -1;
3806
0
                }
3807
0
            }
3808
0
            return 0;
3809
0
        }
3810
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3811
0
            if (attempt >= max_retry_times) {
3812
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3813
0
                        .tag("instance_id", instance_id_)
3814
0
                        .tag("tablet_id", tablet_id)
3815
0
                        .tag("rowset_id", rowset_id)
3816
0
                        .tag("packed_file_path", packed_file_path)
3817
0
                        .tag("attempt", attempt);
3818
0
                return -1;
3819
0
            }
3820
0
            sleep_for_packed_file_retry();
3821
0
            continue;
3822
0
        }
3823
3824
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3825
0
                .tag("instance_id", instance_id_)
3826
0
                .tag("tablet_id", tablet_id)
3827
0
                .tag("rowset_id", rowset_id)
3828
0
                .tag("packed_file_path", packed_file_path)
3829
0
                .tag("err", err);
3830
0
        return -1;
3831
0
    }
3832
3833
18.4E
    return -1;
3834
18.4E
}
3835
3836
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3837
                                                const std::string& packed_key,
3838
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3839
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3840
0
        LOG_WARNING("packed file missing resource id when recycling")
3841
0
                .tag("instance_id", instance_id_)
3842
0
                .tag("packed_file_path", packed_file_path);
3843
0
        return -1;
3844
0
    }
3845
3846
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3847
7
    if (!accessor) {
3848
0
        LOG_WARNING("no accessor available to delete packed file")
3849
0
                .tag("instance_id", instance_id_)
3850
0
                .tag("packed_file_path", packed_file_path)
3851
0
                .tag("resource_id", packed_info.resource_id());
3852
0
        return -1;
3853
0
    }
3854
3855
7
    int del_ret = accessor->delete_file(packed_file_path);
3856
7
    if (del_ret != 0 && del_ret != 1) {
3857
0
        LOG_WARNING("failed to delete packed file")
3858
0
                .tag("instance_id", instance_id_)
3859
0
                .tag("packed_file_path", packed_file_path)
3860
0
                .tag("resource_id", resource_id)
3861
0
                .tag("ret", del_ret);
3862
0
        return -1;
3863
0
    }
3864
7
    if (del_ret == 1) {
3865
0
        LOG_INFO("packed file already removed")
3866
0
                .tag("instance_id", instance_id_)
3867
0
                .tag("packed_file_path", packed_file_path)
3868
0
                .tag("resource_id", resource_id);
3869
7
    } else {
3870
7
        LOG_INFO("deleted packed file")
3871
7
                .tag("instance_id", instance_id_)
3872
7
                .tag("packed_file_path", packed_file_path)
3873
7
                .tag("resource_id", resource_id);
3874
7
    }
3875
3876
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3877
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3878
7
        std::unique_ptr<Transaction> del_txn;
3879
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3880
7
        if (err != TxnErrorCode::TXN_OK) {
3881
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3882
0
                    .tag("instance_id", instance_id_)
3883
0
                    .tag("packed_file_path", packed_file_path)
3884
0
                    .tag("attempt", attempt)
3885
0
                    .tag("err", err);
3886
0
            return -1;
3887
0
        }
3888
3889
7
        std::string latest_val;
3890
7
        err = del_txn->get(packed_key, &latest_val);
3891
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3892
0
            return 0;
3893
0
        }
3894
7
        if (err != TxnErrorCode::TXN_OK) {
3895
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3896
0
                    .tag("instance_id", instance_id_)
3897
0
                    .tag("packed_file_path", packed_file_path)
3898
0
                    .tag("attempt", attempt)
3899
0
                    .tag("err", err);
3900
0
            return -1;
3901
0
        }
3902
3903
7
        cloud::PackedFileInfoPB latest_info;
3904
7
        if (!latest_info.ParseFromString(latest_val)) {
3905
0
            LOG_WARNING("failed to parse packed file info before removal")
3906
0
                    .tag("instance_id", instance_id_)
3907
0
                    .tag("packed_file_path", packed_file_path)
3908
0
                    .tag("attempt", attempt);
3909
0
            return -1;
3910
0
        }
3911
3912
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3913
7
              latest_info.ref_cnt() == 0)) {
3914
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3915
0
                    .tag("instance_id", instance_id_)
3916
0
                    .tag("packed_file_path", packed_file_path)
3917
0
                    .tag("attempt", attempt);
3918
0
            return 0;
3919
0
        }
3920
3921
7
        del_txn->remove(packed_key);
3922
7
        err = del_txn->commit();
3923
7
        if (err == TxnErrorCode::TXN_OK) {
3924
7
            LOG_INFO("removed packed file metadata")
3925
7
                    .tag("instance_id", instance_id_)
3926
7
                    .tag("packed_file_path", packed_file_path);
3927
7
            return 0;
3928
7
        }
3929
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3930
0
            if (attempt >= max_retry_times) {
3931
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3932
0
                        .tag("instance_id", instance_id_)
3933
0
                        .tag("packed_file_path", packed_file_path)
3934
0
                        .tag("attempt", attempt);
3935
0
                return -1;
3936
0
            }
3937
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3938
0
                    .tag("instance_id", instance_id_)
3939
0
                    .tag("packed_file_path", packed_file_path)
3940
0
                    .tag("attempt", attempt);
3941
0
            sleep_for_packed_file_retry();
3942
0
            continue;
3943
0
        }
3944
0
        LOG_WARNING("failed to remove packed file kv")
3945
0
                .tag("instance_id", instance_id_)
3946
0
                .tag("packed_file_path", packed_file_path)
3947
0
                .tag("attempt", attempt)
3948
0
                .tag("err", err);
3949
0
        return -1;
3950
0
    }
3951
0
    return -1;
3952
7
}
3953
3954
int InstanceRecycler::delete_rowset_data(
3955
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3956
67
        RecyclerMetricsContext& metrics_context) {
3957
67
    int ret = 0;
3958
    // resource_id -> file_paths
3959
67
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3960
    // (resource_id, tablet_id, rowset_id)
3961
67
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3962
67
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3963
3964
56.1k
    for (const auto& [_, rs] : rowsets) {
3965
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3966
        // due to aborted schema change.
3967
56.1k
        if (is_formal_rowset) {
3968
3.15k
            std::lock_guard lock(recycled_tablets_mtx_);
3969
3.15k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3970
                // Tablet has been recycled and this rowset has no packed slices, so file data
3971
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3972
                // slice info must still run to decrement packed file ref counts.
3973
0
                continue;
3974
0
            }
3975
3.15k
        }
3976
3977
56.1k
        int64_t num_segments = rs.num_segments();
3978
        // Check num_segments before accessor lookup, because empty rowsets
3979
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3980
        // set. Skipping them early avoids a spurious "no such resource id" error
3981
        // that marks the entire batch as failed and prevents txn_remove from
3982
        // cleaning up recycle KV keys.
3983
56.1k
        if (num_segments <= 0) {
3984
0
            metrics_context.total_recycled_num++;
3985
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3986
0
            continue;
3987
0
        }
3988
3989
56.1k
        auto it = accessor_map_.find(rs.resource_id());
3990
        // possible if the accessor is not initilized correctly
3991
56.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3992
2.00k
            LOG_WARNING("instance has no such resource id")
3993
2.00k
                    .tag("instance_id", instance_id_)
3994
2.00k
                    .tag("resource_id", rs.resource_id());
3995
2.00k
            ret = -1;
3996
2.00k
            continue;
3997
2.00k
        }
3998
3999
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4000
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
4001
54.1k
        int64_t tablet_id = rs.tablet_id();
4002
54.1k
        LOG_INFO("recycle rowset merge index size")
4003
54.1k
                .tag("instance_id", instance_id_)
4004
54.1k
                .tag("tablet_id", tablet_id)
4005
54.1k
                .tag("rowset_id", rowset_id)
4006
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4007
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4008
0
            ret = -1;
4009
0
            continue;
4010
0
        }
4011
4012
        // Process delete bitmap - check where it's stored.
4013
54.1k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4014
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4015
54.1k
                                                           &delete_bitmap_storage_type) != 0) {
4016
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4017
0
                    .tag("instance_id", instance_id_)
4018
0
                    .tag("tablet_id", tablet_id)
4019
0
                    .tag("rowset_id", rowset_id);
4020
0
            ret = -1;
4021
0
            continue;
4022
0
        }
4023
54.1k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4024
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4025
51.5k
        }
4026
4027
        // Process inverted indexes
4028
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4029
        // default format as v1.
4030
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4031
54.1k
        int inverted_index_get_ret = 0;
4032
54.1k
        if (rs.has_tablet_schema()) {
4033
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4034
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4035
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4036
53.5k
                }
4037
53.5k
            }
4038
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4039
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4040
26.5k
            }
4041
27.5k
        } else {
4042
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4043
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4044
0
                                "instance_id="
4045
0
                             << instance_id_ << " tablet_id=" << tablet_id
4046
0
                             << " rowset_id=" << rowset_id;
4047
0
                ret = -1;
4048
0
                continue;
4049
0
            }
4050
27.5k
            InvertedIndexInfo index_info;
4051
27.5k
            inverted_index_get_ret =
4052
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4053
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4054
27.5k
                                     &inverted_index_get_ret);
4055
27.5k
            if (inverted_index_get_ret == 0) {
4056
27.0k
                index_format = index_info.first;
4057
27.0k
                index_ids = index_info.second;
4058
27.0k
            } else if (inverted_index_get_ret == 1) {
4059
                // 1. Schema kv not found means tablet has been recycled
4060
                // Maybe some tablet recycle failed by some bugs
4061
                // We need to delete again to double check
4062
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4063
                // because we are uncertain about the inverted index information.
4064
                // If there are inverted indexes, some data might not be deleted,
4065
                // but this is acceptable as we have made our best effort to delete the data.
4066
503
                LOG_INFO(
4067
503
                        "delete rowset data schema kv not found, need to delete again to "
4068
503
                        "double "
4069
503
                        "check")
4070
503
                        .tag("instance_id", instance_id_)
4071
503
                        .tag("tablet_id", tablet_id)
4072
503
                        .tag("rowset", rs.ShortDebugString());
4073
                // Currently index_ids is guaranteed to be empty,
4074
                // but we clear it again here as a safeguard against future code changes
4075
                // that might cause index_ids to no longer be empty
4076
503
                index_format = InvertedIndexStorageFormatPB::V2;
4077
503
                index_ids.clear();
4078
18.4E
            } else {
4079
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4080
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4081
18.4E
                ret = -1;
4082
18.4E
                continue;
4083
18.4E
            }
4084
27.5k
        }
4085
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4086
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4087
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4088
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4089
5
            continue;
4090
5
        }
4091
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4092
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4093
269k
                                             &file_paths);
4094
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4095
535k
                for (const auto& index_id : index_ids) {
4096
535k
                    add_file_to_delete_if_not_packed(
4097
535k
                            rs,
4098
535k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4099
535k
                                                   index_id.second),
4100
535k
                            &file_paths);
4101
535k
                }
4102
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4103
                // try to recycle inverted index v2 when get_ret == 1
4104
                // we treat schema not found as if it has a v2 format inverted index
4105
                // to reduce chance of data leakage
4106
2.50k
                if (inverted_index_get_ret == 1) {
4107
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4108
2.50k
                            .tag("instance_id", instance_id_)
4109
2.50k
                            .tag("inverted index v2 path",
4110
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4111
2.50k
                }
4112
2.50k
                add_file_to_delete_if_not_packed(
4113
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4114
2.50k
            }
4115
269k
        }
4116
54.1k
    }
4117
4118
67
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4119
67
                                                 "delete_rowset_data",
4120
67
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
4120
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
4120
51
                                                 [](const int& ret) { return ret != 0; });
4121
67
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4122
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4123
51
            DCHECK(accessor_map_.count(*rid))
4124
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4125
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4126
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4127
51
                                     &accessor_map_);
4128
51
            if (!accessor_map_.contains(*rid)) {
4129
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4130
0
                        .tag("resource_id", resource_id)
4131
0
                        .tag("instance_id", instance_id_);
4132
0
                return -1;
4133
0
            }
4134
51
            auto& accessor = accessor_map_[*rid];
4135
51
            int ret = accessor->delete_files(*paths);
4136
51
            if (!ret) {
4137
                // deduplication of different files with the same rowset id
4138
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4139
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4140
51
                std::set<std::string> deleted_rowset_id;
4141
4142
51
                std::for_each(paths->begin(), paths->end(),
4143
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4144
857k
                               this](const std::string& path) {
4145
857k
                                  std::vector<std::string> str;
4146
857k
                                  butil::SplitString(path, '/', &str);
4147
857k
                                  std::string rowset_id;
4148
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4149
851k
                                      rowset_id = str.back().substr(0, pos);
4150
851k
                                  } else {
4151
5.94k
                                      if (path.find("packed_file/") != std::string::npos) {
4152
0
                                          return; // packed files do not have rowset_id encoded
4153
0
                                      }
4154
5.94k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4155
5.94k
                                      return;
4156
5.94k
                                  }
4157
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4158
851k
                                  if (rs_meta != rowsets.end() &&
4159
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
4160
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4161
54.1k
                                      metrics_context.total_recycled_data_size +=
4162
54.1k
                                              rs_meta->second.total_disk_size();
4163
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4164
54.1k
                                              rs_meta->second.num_segments();
4165
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4166
54.1k
                                              rs_meta->second.total_disk_size();
4167
54.1k
                                      metrics_context.total_recycled_num++;
4168
54.1k
                                  }
4169
851k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4144
7
                               this](const std::string& path) {
4145
7
                                  std::vector<std::string> str;
4146
7
                                  butil::SplitString(path, '/', &str);
4147
7
                                  std::string rowset_id;
4148
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4149
7
                                      rowset_id = str.back().substr(0, pos);
4150
7
                                  } else {
4151
0
                                      if (path.find("packed_file/") != std::string::npos) {
4152
0
                                          return; // packed files do not have rowset_id encoded
4153
0
                                      }
4154
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4155
0
                                      return;
4156
0
                                  }
4157
7
                                  auto rs_meta = rowsets.find(rowset_id);
4158
7
                                  if (rs_meta != rowsets.end() &&
4159
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4160
7
                                      deleted_rowset_id.emplace(rowset_id);
4161
7
                                      metrics_context.total_recycled_data_size +=
4162
7
                                              rs_meta->second.total_disk_size();
4163
7
                                      segment_metrics_context_.total_recycled_num +=
4164
7
                                              rs_meta->second.num_segments();
4165
7
                                      segment_metrics_context_.total_recycled_data_size +=
4166
7
                                              rs_meta->second.total_disk_size();
4167
7
                                      metrics_context.total_recycled_num++;
4168
7
                                  }
4169
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4144
857k
                               this](const std::string& path) {
4145
857k
                                  std::vector<std::string> str;
4146
857k
                                  butil::SplitString(path, '/', &str);
4147
857k
                                  std::string rowset_id;
4148
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4149
851k
                                      rowset_id = str.back().substr(0, pos);
4150
851k
                                  } else {
4151
5.94k
                                      if (path.find("packed_file/") != std::string::npos) {
4152
0
                                          return; // packed files do not have rowset_id encoded
4153
0
                                      }
4154
5.94k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4155
5.94k
                                      return;
4156
5.94k
                                  }
4157
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4158
851k
                                  if (rs_meta != rowsets.end() &&
4159
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
4160
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4161
54.1k
                                      metrics_context.total_recycled_data_size +=
4162
54.1k
                                              rs_meta->second.total_disk_size();
4163
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4164
54.1k
                                              rs_meta->second.num_segments();
4165
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4166
54.1k
                                              rs_meta->second.total_disk_size();
4167
54.1k
                                      metrics_context.total_recycled_num++;
4168
54.1k
                                  }
4169
851k
                              });
4170
51
            }
4171
51
            return ret;
4172
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4122
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4123
5
            DCHECK(accessor_map_.count(*rid))
4124
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4125
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4126
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4127
5
                                     &accessor_map_);
4128
5
            if (!accessor_map_.contains(*rid)) {
4129
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4130
0
                        .tag("resource_id", resource_id)
4131
0
                        .tag("instance_id", instance_id_);
4132
0
                return -1;
4133
0
            }
4134
5
            auto& accessor = accessor_map_[*rid];
4135
5
            int ret = accessor->delete_files(*paths);
4136
5
            if (!ret) {
4137
                // deduplication of different files with the same rowset id
4138
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4139
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4140
5
                std::set<std::string> deleted_rowset_id;
4141
4142
5
                std::for_each(paths->begin(), paths->end(),
4143
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4144
5
                               this](const std::string& path) {
4145
5
                                  std::vector<std::string> str;
4146
5
                                  butil::SplitString(path, '/', &str);
4147
5
                                  std::string rowset_id;
4148
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4149
5
                                      rowset_id = str.back().substr(0, pos);
4150
5
                                  } else {
4151
5
                                      if (path.find("packed_file/") != std::string::npos) {
4152
5
                                          return; // packed files do not have rowset_id encoded
4153
5
                                      }
4154
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4155
5
                                      return;
4156
5
                                  }
4157
5
                                  auto rs_meta = rowsets.find(rowset_id);
4158
5
                                  if (rs_meta != rowsets.end() &&
4159
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4160
5
                                      deleted_rowset_id.emplace(rowset_id);
4161
5
                                      metrics_context.total_recycled_data_size +=
4162
5
                                              rs_meta->second.total_disk_size();
4163
5
                                      segment_metrics_context_.total_recycled_num +=
4164
5
                                              rs_meta->second.num_segments();
4165
5
                                      segment_metrics_context_.total_recycled_data_size +=
4166
5
                                              rs_meta->second.total_disk_size();
4167
5
                                      metrics_context.total_recycled_num++;
4168
5
                                  }
4169
5
                              });
4170
5
            }
4171
5
            return ret;
4172
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4122
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4123
46
            DCHECK(accessor_map_.count(*rid))
4124
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4125
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4126
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4127
46
                                     &accessor_map_);
4128
46
            if (!accessor_map_.contains(*rid)) {
4129
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4130
0
                        .tag("resource_id", resource_id)
4131
0
                        .tag("instance_id", instance_id_);
4132
0
                return -1;
4133
0
            }
4134
46
            auto& accessor = accessor_map_[*rid];
4135
46
            int ret = accessor->delete_files(*paths);
4136
46
            if (!ret) {
4137
                // deduplication of different files with the same rowset id
4138
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4139
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4140
46
                std::set<std::string> deleted_rowset_id;
4141
4142
46
                std::for_each(paths->begin(), paths->end(),
4143
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4144
46
                               this](const std::string& path) {
4145
46
                                  std::vector<std::string> str;
4146
46
                                  butil::SplitString(path, '/', &str);
4147
46
                                  std::string rowset_id;
4148
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4149
46
                                      rowset_id = str.back().substr(0, pos);
4150
46
                                  } else {
4151
46
                                      if (path.find("packed_file/") != std::string::npos) {
4152
46
                                          return; // packed files do not have rowset_id encoded
4153
46
                                      }
4154
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4155
46
                                      return;
4156
46
                                  }
4157
46
                                  auto rs_meta = rowsets.find(rowset_id);
4158
46
                                  if (rs_meta != rowsets.end() &&
4159
46
                                      !deleted_rowset_id.contains(rowset_id)) {
4160
46
                                      deleted_rowset_id.emplace(rowset_id);
4161
46
                                      metrics_context.total_recycled_data_size +=
4162
46
                                              rs_meta->second.total_disk_size();
4163
46
                                      segment_metrics_context_.total_recycled_num +=
4164
46
                                              rs_meta->second.num_segments();
4165
46
                                      segment_metrics_context_.total_recycled_data_size +=
4166
46
                                              rs_meta->second.total_disk_size();
4167
46
                                      metrics_context.total_recycled_num++;
4168
46
                                  }
4169
46
                              });
4170
46
            }
4171
46
            return ret;
4172
46
        });
4173
51
    }
4174
67
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4175
5
        LOG_INFO(
4176
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4177
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4178
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4179
5
        concurrent_delete_executor.add([&]() -> int {
4180
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4181
5
            if (!ret) {
4182
5
                auto rs = rowsets.at(rowset_id);
4183
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4184
5
                metrics_context.total_recycled_num++;
4185
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4186
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4187
5
            }
4188
5
            return ret;
4189
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
4179
5
        concurrent_delete_executor.add([&]() -> int {
4180
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4181
5
            if (!ret) {
4182
5
                auto rs = rowsets.at(rowset_id);
4183
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4184
5
                metrics_context.total_recycled_num++;
4185
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4186
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4187
5
            }
4188
5
            return ret;
4189
5
        });
4190
5
    }
4191
4192
67
    bool finished = true;
4193
67
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4194
67
    for (int r : rets) {
4195
56
        if (r != 0) {
4196
0
            ret = -1;
4197
0
            break;
4198
0
        }
4199
56
    }
4200
67
    ret = finished ? ret : -1;
4201
67
    return ret;
4202
67
}
4203
4204
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4205
3.30k
                                         const std::string& rowset_id) {
4206
3.30k
    auto it = accessor_map_.find(resource_id);
4207
3.30k
    if (it == accessor_map_.end()) {
4208
400
        LOG_WARNING("instance has no such resource id")
4209
400
                .tag("instance_id", instance_id_)
4210
400
                .tag("resource_id", resource_id)
4211
400
                .tag("tablet_id", tablet_id)
4212
400
                .tag("rowset_id", rowset_id);
4213
400
        return -1;
4214
400
    }
4215
2.90k
    auto& accessor = it->second;
4216
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4217
3.30k
}
4218
4219
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4220
4
    if (key.empty()) {
4221
0
        return false;
4222
0
    }
4223
4
    std::string_view key_view = key;
4224
4
    key_view.remove_prefix(1); // remove keyspace prefix
4225
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4226
4
    if (decode_key(&key_view, &decoded) != 0) {
4227
0
        return false;
4228
0
    }
4229
4
    if (decoded.size() < 4) {
4230
0
        return false;
4231
0
    }
4232
4
    try {
4233
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4234
4
    } catch (const std::bad_variant_access&) {
4235
0
        return false;
4236
0
    }
4237
4
    return true;
4238
4
}
4239
4240
14
int InstanceRecycler::recycle_packed_files() {
4241
14
    const std::string task_name = "recycle_packed_files";
4242
14
    auto start_tp = steady_clock::now();
4243
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4244
14
    int ret = 0;
4245
14
    PackedFileRecycleStats stats;
4246
4247
14
    register_recycle_task(task_name, start_time);
4248
14
    DORIS_CLOUD_DEFER {
4249
14
        unregister_recycle_task(task_name);
4250
14
        int64_t cost =
4251
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4252
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4253
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4254
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4255
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4256
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4257
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4258
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4259
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4260
14
                                                             stats.bytes_object_deleted);
4261
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4262
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4263
14
                .tag("instance_id", instance_id_)
4264
14
                .tag("num_scanned", stats.num_scanned)
4265
14
                .tag("num_corrected", stats.num_corrected)
4266
14
                .tag("num_deleted", stats.num_deleted)
4267
14
                .tag("num_failed", stats.num_failed)
4268
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4269
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4270
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4271
14
                .tag("bytes_deleted", stats.bytes_deleted)
4272
14
                .tag("ret", ret);
4273
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4248
14
    DORIS_CLOUD_DEFER {
4249
14
        unregister_recycle_task(task_name);
4250
14
        int64_t cost =
4251
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4252
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4253
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4254
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4255
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4256
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4257
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4258
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4259
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4260
14
                                                             stats.bytes_object_deleted);
4261
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4262
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4263
14
                .tag("instance_id", instance_id_)
4264
14
                .tag("num_scanned", stats.num_scanned)
4265
14
                .tag("num_corrected", stats.num_corrected)
4266
14
                .tag("num_deleted", stats.num_deleted)
4267
14
                .tag("num_failed", stats.num_failed)
4268
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4269
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4270
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4271
14
                .tag("bytes_deleted", stats.bytes_deleted)
4272
14
                .tag("ret", ret);
4273
14
    };
4274
4275
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4276
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4277
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4278
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
4275
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4276
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4277
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4278
4
    };
4279
4280
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4281
4282
14
    std::string begin = packed_file_key({instance_id_, ""});
4283
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4284
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4285
0
        ret = -1;
4286
0
    }
4287
4288
14
    return ret;
4289
14
}
4290
4291
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4292
                                                  RecyclerMetricsContext& metrics_context,
4293
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4294
0
    std::string tablet_key_begin, tablet_key_end;
4295
4296
0
    if (partition_id > 0) {
4297
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4298
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4299
0
    } else {
4300
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4301
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4302
0
    }
4303
    // for calculate the total num or bytes of recyled objects
4304
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4305
0
                                                          std::string_view v) -> int {
4306
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4307
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4308
0
            return 0;
4309
0
        }
4310
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4311
4312
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4313
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4314
0
            return 0;
4315
0
        }
4316
4317
0
        if (!is_empty_tablet) {
4318
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4319
0
                return 0;
4320
0
            }
4321
0
            tablet_metrics_context_.total_need_recycle_num++;
4322
0
        }
4323
0
        return 0;
4324
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_
4325
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4326
0
    metrics_context.report(true);
4327
0
    tablet_metrics_context_.report(true);
4328
0
    segment_metrics_context_.report(true);
4329
0
    return ret;
4330
0
}
4331
4332
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4333
0
                                                 RecyclerMetricsContext& metrics_context) {
4334
0
    int ret = 0;
4335
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4336
0
    std::unique_ptr<Transaction> txn;
4337
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4338
0
        LOG_WARNING("failed to recycle tablet ")
4339
0
                .tag("tablet id", tablet_id)
4340
0
                .tag("instance_id", instance_id_)
4341
0
                .tag("reason", "failed to create txn");
4342
0
        ret = -1;
4343
0
    }
4344
0
    GetRowsetResponse resp;
4345
0
    std::string msg;
4346
0
    MetaServiceCode code = MetaServiceCode::OK;
4347
    // get rowsets in tablet
4348
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4349
0
                        tablet_id, code, msg, &resp);
4350
0
    if (code != MetaServiceCode::OK) {
4351
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4352
0
                .tag("tablet id", tablet_id)
4353
0
                .tag("msg", msg)
4354
0
                .tag("code", code)
4355
0
                .tag("instance id", instance_id_);
4356
0
        ret = -1;
4357
0
    }
4358
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4359
        /*
4360
        * For compatibility, we skip the loop for [0-1] here.
4361
        * The purpose of this loop is to delete object files,
4362
        * and since [0-1] only has meta and doesn't have object files,
4363
        * skipping it doesn't affect system correctness.
4364
        *
4365
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4366
        * would return error -1 directly, causing the recycle operation to fail.
4367
        *
4368
        * [0-1] doesn't have resource id is a bug.
4369
        * In the future, we will fix this problem, after that,
4370
        * we can remove this if statement.
4371
        *
4372
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4373
        */
4374
4375
0
        if (rs_meta.end_version() == 1) {
4376
            // Assert that [0-1] has no resource_id to make sure
4377
            // this if statement will not be forgetted to remove
4378
            // when the resource id bug is fixed
4379
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4380
0
            continue;
4381
0
        }
4382
0
        if (!rs_meta.has_resource_id()) {
4383
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4384
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4385
0
                    .tag("instance_id", instance_id_)
4386
0
                    .tag("tablet_id", tablet_id);
4387
0
            continue;
4388
0
        }
4389
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4390
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4391
        // possible if the accessor is not initilized correctly
4392
0
        if (it == accessor_map_.end()) [[unlikely]] {
4393
0
            LOG_WARNING(
4394
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4395
0
                    "recycle process")
4396
0
                    .tag("tablet id", tablet_id)
4397
0
                    .tag("instance_id", instance_id_)
4398
0
                    .tag("resource_id", rs_meta.resource_id())
4399
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4400
0
            continue;
4401
0
        }
4402
4403
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4404
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4405
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4406
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4407
0
    }
4408
0
    return ret;
4409
0
}
4410
4411
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4412
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4413
4.26k
            .tag("instance_id", instance_id_)
4414
4.26k
            .tag("tablet_id", tablet_id);
4415
4416
4.26k
    if (should_recycle_versioned_keys()) {
4417
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4418
14
        if (ret != 0) {
4419
0
            return ret;
4420
0
        }
4421
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4422
        // during the recycle_versioned_tablet process.
4423
        //
4424
        // .. And remove restore job rowsets of this tablet too
4425
14
    }
4426
4427
4.26k
    int ret = 0;
4428
4.26k
    auto start_time = steady_clock::now();
4429
4430
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4431
4432
    // collect resource ids
4433
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4434
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4435
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4436
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4437
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4438
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4439
4440
260
    std::set<std::string> resource_ids;
4441
260
    int64_t recycle_rowsets_number = 0;
4442
260
    int64_t recycle_segments_number = 0;
4443
260
    int64_t recycle_rowsets_data_size = 0;
4444
260
    int64_t recycle_rowsets_index_size = 0;
4445
260
    int64_t recycle_restore_job_rowsets_number = 0;
4446
260
    int64_t recycle_restore_job_segments_number = 0;
4447
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4448
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4449
260
    int64_t max_rowset_version = 0;
4450
260
    int64_t min_rowset_creation_time = INT64_MAX;
4451
260
    int64_t max_rowset_creation_time = 0;
4452
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4453
260
    int64_t max_rowset_expiration_time = 0;
4454
4455
260
    DORIS_CLOUD_DEFER {
4456
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4457
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4458
260
                .tag("instance_id", instance_id_)
4459
260
                .tag("tablet_id", tablet_id)
4460
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4461
260
                .tag("recycle segments number", recycle_segments_number)
4462
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4463
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4464
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4465
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4466
260
                .tag("all restore job rowsets recycle data size",
4467
260
                     recycle_restore_job_rowsets_data_size)
4468
260
                .tag("all restore job rowsets recycle index size",
4469
260
                     recycle_restore_job_rowsets_index_size)
4470
260
                .tag("max rowset version", max_rowset_version)
4471
260
                .tag("min rowset creation time", min_rowset_creation_time)
4472
260
                .tag("max rowset creation time", max_rowset_creation_time)
4473
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4474
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4475
260
                .tag("task type", metrics_context.operation_type)
4476
260
                .tag("ret", ret);
4477
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4455
260
    DORIS_CLOUD_DEFER {
4456
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4457
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4458
260
                .tag("instance_id", instance_id_)
4459
260
                .tag("tablet_id", tablet_id)
4460
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4461
260
                .tag("recycle segments number", recycle_segments_number)
4462
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4463
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4464
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4465
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4466
260
                .tag("all restore job rowsets recycle data size",
4467
260
                     recycle_restore_job_rowsets_data_size)
4468
260
                .tag("all restore job rowsets recycle index size",
4469
260
                     recycle_restore_job_rowsets_index_size)
4470
260
                .tag("max rowset version", max_rowset_version)
4471
260
                .tag("min rowset creation time", min_rowset_creation_time)
4472
260
                .tag("max rowset creation time", max_rowset_creation_time)
4473
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4474
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4475
260
                .tag("task type", metrics_context.operation_type)
4476
260
                .tag("ret", ret);
4477
260
    };
4478
4479
260
    std::unique_ptr<Transaction> txn;
4480
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4481
0
        LOG_WARNING("failed to recycle tablet ")
4482
0
                .tag("tablet id", tablet_id)
4483
0
                .tag("instance_id", instance_id_)
4484
0
                .tag("reason", "failed to create txn");
4485
0
        ret = -1;
4486
0
    }
4487
260
    GetRowsetResponse resp;
4488
260
    std::string msg;
4489
260
    MetaServiceCode code = MetaServiceCode::OK;
4490
    // get rowsets in tablet
4491
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4492
260
                        tablet_id, code, msg, &resp);
4493
260
    if (code != MetaServiceCode::OK) {
4494
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4495
0
                .tag("tablet id", tablet_id)
4496
0
                .tag("msg", msg)
4497
0
                .tag("code", code)
4498
0
                .tag("instance id", instance_id_);
4499
0
        ret = -1;
4500
0
    }
4501
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4502
4503
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4504
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4505
3
            if (rs_meta.num_segments() <= 0) {
4506
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4507
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4508
2
                        .tag("instance_id", instance_id_)
4509
2
                        .tag("tablet_id", tablet_id);
4510
2
                recycle_rowsets_number += 1;
4511
2
                continue;
4512
2
            }
4513
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4514
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4515
1
                    .tag("instance_id", instance_id_)
4516
1
                    .tag("tablet_id", tablet_id);
4517
1
            return -1;
4518
3
        }
4519
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4520
3
                << "rs_meta" << rs_meta.ShortDebugString();
4521
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4522
        // possible if the accessor is not initilized correctly
4523
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4524
1
            LOG_WARNING(
4525
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4526
1
                    "recycle process")
4527
1
                    .tag("tablet id", tablet_id)
4528
1
                    .tag("instance_id", instance_id_)
4529
1
                    .tag("resource_id", rs_meta.resource_id())
4530
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4531
1
            return -1;
4532
1
        }
4533
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4534
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4535
0
                    .tag("instance_id", instance_id_)
4536
0
                    .tag("tablet_id", tablet_id)
4537
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4538
0
            return -1;
4539
0
        }
4540
2.54k
        recycle_rowsets_number += 1;
4541
2.54k
        recycle_segments_number += rs_meta.num_segments();
4542
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4543
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4544
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4545
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4546
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4547
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4548
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4549
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4550
2.54k
    }
4551
4552
    // get restore job rowset in tablet
4553
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4554
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4555
258
    if (code != MetaServiceCode::OK) {
4556
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4557
0
                .tag("tablet id", tablet_id)
4558
0
                .tag("msg", msg)
4559
0
                .tag("code", code)
4560
0
                .tag("instance id", instance_id_);
4561
0
        return -1;
4562
0
    }
4563
4564
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4565
0
        if (!rs_meta.has_resource_id()) {
4566
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4567
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4568
0
                    .tag("instance_id", instance_id_)
4569
0
                    .tag("tablet_id", tablet_id);
4570
0
            return -1;
4571
0
        }
4572
4573
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4574
        // possible if the accessor is not initilized correctly
4575
0
        if (it == accessor_map_.end()) [[unlikely]] {
4576
0
            LOG_WARNING(
4577
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4578
0
                    "recycle process")
4579
0
                    .tag("tablet id", tablet_id)
4580
0
                    .tag("instance_id", instance_id_)
4581
0
                    .tag("resource_id", rs_meta.resource_id())
4582
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4583
0
            return -1;
4584
0
        }
4585
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4586
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4587
0
                    .tag("instance_id", instance_id_)
4588
0
                    .tag("tablet_id", tablet_id)
4589
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4590
0
            return -1;
4591
0
        }
4592
0
        recycle_restore_job_rowsets_number += 1;
4593
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4594
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4595
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4596
0
        resource_ids.emplace(rs_meta.resource_id());
4597
0
    }
4598
4599
258
    LOG_INFO("recycle tablet start to delete object")
4600
258
            .tag("instance id", instance_id_)
4601
258
            .tag("tablet id", tablet_id)
4602
258
            .tag("recycle tablet resource ids are",
4603
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4604
258
                                 [](std::string rs_id, const auto& it) {
4605
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4606
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
4604
217
                                 [](std::string rs_id, const auto& it) {
4605
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4606
217
                                 }));
4607
4608
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4609
258
            _thread_pool_group.s3_producer_pool,
4610
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4611
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
4611
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4612
4613
    // delete all rowset data in this tablet
4614
    // ATTN: there may be data leak if not all accessor initilized successfully
4615
    //       partial data deleted if the tablet is stored cross-storage vault
4616
    //       vault id is not attached to TabletMeta...
4617
258
    for (const auto& resource_id : resource_ids) {
4618
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4619
217
        concurrent_delete_executor.add(
4620
217
                [&, rs_id = resource_id,
4621
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4622
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4623
217
                    if (res != 0) {
4624
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4625
3
                                     << " path=" << accessor_ptr->uri()
4626
3
                                     << " task type=" << metrics_context.operation_type;
4627
3
                        return std::make_pair(-1, rs_id);
4628
3
                    }
4629
214
                    return std::make_pair(0, rs_id);
4630
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4621
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4622
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4623
217
                    if (res != 0) {
4624
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4625
3
                                     << " path=" << accessor_ptr->uri()
4626
3
                                     << " task type=" << metrics_context.operation_type;
4627
3
                        return std::make_pair(-1, rs_id);
4628
3
                    }
4629
214
                    return std::make_pair(0, rs_id);
4630
217
                });
4631
217
    }
4632
4633
258
    bool finished = true;
4634
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4635
258
    for (auto& r : rets) {
4636
217
        if (r.first != 0) {
4637
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4638
3
            ret = -1;
4639
3
        }
4640
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4641
217
    }
4642
258
    ret = finished ? ret : -1;
4643
4644
258
    if (ret != 0) { // failed recycle tablet data
4645
3
        LOG_WARNING("ret!=0")
4646
3
                .tag("finished", finished)
4647
3
                .tag("ret", ret)
4648
3
                .tag("instance_id", instance_id_)
4649
3
                .tag("tablet_id", tablet_id);
4650
3
        return ret;
4651
3
    }
4652
4653
255
    tablet_metrics_context_.total_recycled_data_size +=
4654
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4655
255
    tablet_metrics_context_.total_recycled_num += 1;
4656
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4657
255
    segment_metrics_context_.total_recycled_data_size +=
4658
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4659
255
    metrics_context.total_recycled_data_size +=
4660
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4661
255
    tablet_metrics_context_.report();
4662
255
    segment_metrics_context_.report();
4663
255
    metrics_context.report();
4664
4665
255
    txn.reset();
4666
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4667
0
        LOG_WARNING("failed to recycle tablet ")
4668
0
                .tag("tablet id", tablet_id)
4669
0
                .tag("instance_id", instance_id_)
4670
0
                .tag("reason", "failed to create txn");
4671
0
        ret = -1;
4672
0
    }
4673
    // delete all rowset kv in this tablet
4674
255
    txn->remove(rs_key0, rs_key1);
4675
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4676
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4677
4678
    // remove delete bitmap for MoW table
4679
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4680
255
    txn->remove(pending_key);
4681
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4682
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4683
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4684
4685
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4686
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4687
255
    txn->remove(dbm_start_key, dbm_end_key);
4688
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4689
255
              << " end=" << hex(dbm_end_key);
4690
4691
255
    TxnErrorCode err = txn->commit();
4692
255
    if (err != TxnErrorCode::TXN_OK) {
4693
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4694
0
        ret = -1;
4695
0
    }
4696
4697
255
    if (ret == 0) {
4698
        // All object files under tablet have been deleted
4699
255
        std::lock_guard lock(recycled_tablets_mtx_);
4700
255
        recycled_tablets_.insert(tablet_id);
4701
255
    }
4702
4703
255
    return ret;
4704
258
}
4705
4706
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4707
14
                                               RecyclerMetricsContext& metrics_context) {
4708
14
    int ret = 0;
4709
14
    auto start_time = steady_clock::now();
4710
4711
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4712
4713
    // collect resource ids
4714
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4715
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4716
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4717
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4718
4719
11
    int64_t recycle_rowsets_number = 0;
4720
11
    int64_t recycle_segments_number = 0;
4721
11
    int64_t recycle_rowsets_data_size = 0;
4722
11
    int64_t recycle_rowsets_index_size = 0;
4723
11
    int64_t max_rowset_version = 0;
4724
11
    int64_t min_rowset_creation_time = INT64_MAX;
4725
11
    int64_t max_rowset_creation_time = 0;
4726
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4727
11
    int64_t max_rowset_expiration_time = 0;
4728
4729
11
    DORIS_CLOUD_DEFER {
4730
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4731
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4732
11
                .tag("instance_id", instance_id_)
4733
11
                .tag("tablet_id", tablet_id)
4734
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4735
11
                .tag("recycle segments number", recycle_segments_number)
4736
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4737
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4738
11
                .tag("max rowset version", max_rowset_version)
4739
11
                .tag("min rowset creation time", min_rowset_creation_time)
4740
11
                .tag("max rowset creation time", max_rowset_creation_time)
4741
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4742
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4743
11
                .tag("ret", ret);
4744
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4729
11
    DORIS_CLOUD_DEFER {
4730
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4731
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4732
11
                .tag("instance_id", instance_id_)
4733
11
                .tag("tablet_id", tablet_id)
4734
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4735
11
                .tag("recycle segments number", recycle_segments_number)
4736
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4737
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4738
11
                .tag("max rowset version", max_rowset_version)
4739
11
                .tag("min rowset creation time", min_rowset_creation_time)
4740
11
                .tag("max rowset creation time", max_rowset_creation_time)
4741
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4742
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4743
11
                .tag("ret", ret);
4744
11
    };
4745
4746
11
    std::unique_ptr<Transaction> txn;
4747
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4748
0
        LOG_WARNING("failed to recycle tablet ")
4749
0
                .tag("tablet id", tablet_id)
4750
0
                .tag("instance_id", instance_id_)
4751
0
                .tag("reason", "failed to create txn");
4752
0
        ret = -1;
4753
0
    }
4754
4755
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4756
    // by the related operation logs.
4757
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4758
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4759
11
    MetaReader meta_reader(instance_id_);
4760
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4761
11
    if (err == TxnErrorCode::TXN_OK) {
4762
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4763
11
    }
4764
11
    if (err != TxnErrorCode::TXN_OK) {
4765
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4766
0
                .tag("tablet id", tablet_id)
4767
0
                .tag("err", err)
4768
0
                .tag("instance id", instance_id_);
4769
0
        ret = -1;
4770
0
    }
4771
4772
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4773
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4774
11
            .tag("instance_id", instance_id_)
4775
11
            .tag("tablet_id", tablet_id);
4776
4777
11
    SyncExecutor<int> concurrent_delete_executor(
4778
11
            _thread_pool_group.s3_producer_pool,
4779
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4780
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
4781
4782
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4783
60
        recycle_rowsets_number += 1;
4784
60
        recycle_segments_number += rs_meta.num_segments();
4785
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4786
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4787
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4788
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4789
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4790
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4791
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4792
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4782
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4783
60
        recycle_rowsets_number += 1;
4784
60
        recycle_segments_number += rs_meta.num_segments();
4785
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4786
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4787
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4788
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4789
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4790
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4791
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4792
60
    };
4793
4794
11
    std::vector<RowsetDeleteTask> all_tasks;
4795
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4796
60
        update_rowset_stats(rs_meta);
4797
        // Version 0-1 rowset has no resource_id and no actual data files,
4798
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4799
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4800
60
        RowsetDeleteTask task;
4801
60
        task.rowset_meta = rs_meta;
4802
60
        task.versioned_rowset_key =
4803
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4804
60
        task.non_versioned_rowset_key =
4805
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4806
60
        task.versionstamp = versionstamp;
4807
60
        all_tasks.push_back(std::move(task));
4808
60
    }
4809
4810
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4811
0
        update_rowset_stats(rs_meta);
4812
        // Version 0-1 rowset has no resource_id and no actual data files,
4813
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4814
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4815
0
        RowsetDeleteTask task;
4816
0
        task.rowset_meta = rs_meta;
4817
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
4818
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4819
0
        task.non_versioned_rowset_key =
4820
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4821
0
        task.versionstamp = versionstamp;
4822
0
        all_tasks.push_back(std::move(task));
4823
0
    }
4824
4825
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4826
0
        RecycleRowsetPB recycle_rowset;
4827
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4828
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4829
0
            return -1;
4830
0
        }
4831
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4832
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4833
                // in old version, keep this key-value pair and it needs to be checked manually
4834
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4835
0
                return -1;
4836
0
            }
4837
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4838
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4839
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4840
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4841
0
                return -1;
4842
0
            }
4843
            // decode rowset_id
4844
0
            auto k1 = k;
4845
0
            k1.remove_prefix(1);
4846
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4847
0
            decode_key(&k1, &out);
4848
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4849
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4850
0
            LOG_INFO("delete old-version rowset data")
4851
0
                    .tag("instance_id", instance_id_)
4852
0
                    .tag("tablet_id", tablet_id)
4853
0
                    .tag("rowset_id", rowset_id);
4854
4855
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4856
            // so we must use prefix deletion directly instead of batch delete.
4857
0
            concurrent_delete_executor.add(
4858
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4859
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4860
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4861
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
4862
0
        } else {
4863
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4864
            // Version 0-1 rowset has no resource_id and no actual data files,
4865
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4866
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4867
0
            RowsetDeleteTask task;
4868
0
            task.rowset_meta = rowset_meta;
4869
0
            task.recycle_rowset_key = k;
4870
0
            all_tasks.push_back(std::move(task));
4871
0
        }
4872
0
        return 0;
4873
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_
4874
4875
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4876
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4877
0
                .tag("tablet id", tablet_id)
4878
0
                .tag("instance_id", instance_id_)
4879
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4880
0
        ret = -1;
4881
0
    }
4882
4883
    // Phase 1: Classify tasks by ref_count
4884
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4885
60
    for (auto& task : all_tasks) {
4886
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4887
60
        if (classify_ret < 0) {
4888
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4889
0
                    .tag("instance_id", instance_id_)
4890
0
                    .tag("tablet_id", tablet_id)
4891
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4892
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4893
0
                return recycle_rowset_meta_and_data(t);
4894
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_4clEv
4895
0
        }
4896
60
    }
4897
4898
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4899
4900
11
    LOG_INFO("batch delete plan created")
4901
11
            .tag("instance_id", instance_id_)
4902
11
            .tag("tablet_id", tablet_id)
4903
11
            .tag("plan_count", batch_delete_tasks.size());
4904
4905
    // Phase 2: Execute batch delete using existing delete_rowset_data
4906
11
    if (!batch_delete_tasks.empty()) {
4907
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4908
49
        for (const auto& task : batch_delete_tasks) {
4909
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4910
49
            if (task.rowset_meta.resource_id().empty()) {
4911
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4912
10
                        .tag("instance_id", instance_id_)
4913
10
                        .tag("tablet_id", tablet_id)
4914
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4915
10
                continue;
4916
10
            }
4917
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4918
39
        }
4919
4920
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4921
10
        bool delete_success = true;
4922
10
        if (!rowsets_to_delete.empty()) {
4923
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4924
9
                                                         "batch_delete_versioned_tablet");
4925
9
            int delete_ret = delete_rowset_data(
4926
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4927
9
            if (delete_ret != 0) {
4928
0
                LOG_WARNING("batch delete execution failed")
4929
0
                        .tag("instance_id", instance_id_)
4930
0
                        .tag("tablet_id", tablet_id);
4931
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4932
0
                ret = -1;
4933
0
                delete_success = false;
4934
0
            }
4935
9
        }
4936
4937
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4938
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4939
10
        if (delete_success) {
4940
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4941
10
            if (cleanup_ret != 0) {
4942
0
                LOG_WARNING("batch delete cleanup failed")
4943
0
                        .tag("instance_id", instance_id_)
4944
0
                        .tag("tablet_id", tablet_id);
4945
0
                ret = -1;
4946
0
            }
4947
10
        }
4948
10
    }
4949
4950
    // Always wait for fallback tasks to complete before returning
4951
11
    bool finished = true;
4952
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4953
11
    for (int r : rets) {
4954
0
        if (r != 0) {
4955
0
            ret = -1;
4956
0
        }
4957
0
    }
4958
4959
11
    ret = finished ? ret : -1;
4960
4961
11
    if (ret != 0) { // failed recycle tablet data
4962
0
        LOG_WARNING("recycle versioned tablet failed")
4963
0
                .tag("finished", finished)
4964
0
                .tag("ret", ret)
4965
0
                .tag("instance_id", instance_id_)
4966
0
                .tag("tablet_id", tablet_id);
4967
0
        return ret;
4968
0
    }
4969
4970
11
    tablet_metrics_context_.total_recycled_data_size +=
4971
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4972
11
    tablet_metrics_context_.total_recycled_num += 1;
4973
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4974
11
    segment_metrics_context_.total_recycled_data_size +=
4975
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4976
11
    metrics_context.total_recycled_data_size +=
4977
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4978
11
    tablet_metrics_context_.report();
4979
11
    segment_metrics_context_.report();
4980
11
    metrics_context.report();
4981
4982
11
    txn.reset();
4983
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4984
0
        LOG_WARNING("failed to recycle tablet ")
4985
0
                .tag("tablet id", tablet_id)
4986
0
                .tag("instance_id", instance_id_)
4987
0
                .tag("reason", "failed to create txn");
4988
0
        ret = -1;
4989
0
    }
4990
    // delete all rowset kv in this tablet
4991
11
    txn->remove(rs_key0, rs_key1);
4992
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4993
4994
    // remove delete bitmap for MoW table
4995
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4996
11
    txn->remove(pending_key);
4997
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4998
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4999
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5000
5001
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5002
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5003
11
    txn->remove(dbm_start_key, dbm_end_key);
5004
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5005
11
              << " end=" << hex(dbm_end_key);
5006
5007
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5008
11
    std::string tablet_index_val;
5009
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5010
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5011
0
        LOG_WARNING("failed to get tablet index kv")
5012
0
                .tag("instance_id", instance_id_)
5013
0
                .tag("tablet_id", tablet_id)
5014
0
                .tag("err", err);
5015
0
        ret = -1;
5016
11
    } else if (err == TxnErrorCode::TXN_OK) {
5017
        // If the tablet index kv exists, we need to delete it
5018
10
        TabletIndexPB tablet_index_pb;
5019
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5020
0
            LOG_WARNING("failed to parse tablet index pb")
5021
0
                    .tag("instance_id", instance_id_)
5022
0
                    .tag("tablet_id", tablet_id);
5023
0
            ret = -1;
5024
10
        } else {
5025
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5026
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5027
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5028
10
            txn->remove(versioned_inverted_idx_key);
5029
10
            txn->remove(versioned_idx_key);
5030
10
        }
5031
10
    }
5032
5033
11
    err = txn->commit();
5034
11
    if (err != TxnErrorCode::TXN_OK) {
5035
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5036
0
        ret = -1;
5037
0
    }
5038
5039
11
    if (ret == 0) {
5040
        // All object files under tablet have been deleted
5041
11
        std::lock_guard lock(recycled_tablets_mtx_);
5042
11
        recycled_tablets_.insert(tablet_id);
5043
11
    }
5044
5045
11
    return ret;
5046
11
}
5047
5048
27
int InstanceRecycler::recycle_rowsets() {
5049
27
    if (should_recycle_versioned_keys()) {
5050
5
        return recycle_versioned_rowsets();
5051
5
    }
5052
5053
22
    const std::string task_name = "recycle_rowsets";
5054
22
    int64_t num_scanned = 0;
5055
22
    int64_t num_expired = 0;
5056
22
    int64_t num_prepare = 0;
5057
22
    int64_t num_compacted = 0;
5058
22
    int64_t num_empty_rowset = 0;
5059
22
    size_t total_rowset_key_size = 0;
5060
22
    size_t total_rowset_value_size = 0;
5061
22
    size_t expired_rowset_size = 0;
5062
22
    std::atomic_long num_recycled = 0;
5063
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5064
5065
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5066
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5067
22
    std::string recyc_rs_key0;
5068
22
    std::string recyc_rs_key1;
5069
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5070
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5071
5072
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5073
5074
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5075
22
    register_recycle_task(task_name, start_time);
5076
5077
22
    DORIS_CLOUD_DEFER {
5078
22
        unregister_recycle_task(task_name);
5079
22
        int64_t cost =
5080
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5081
22
        metrics_context.finish_report();
5082
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5083
22
                .tag("instance_id", instance_id_)
5084
22
                .tag("num_scanned", num_scanned)
5085
22
                .tag("num_expired", num_expired)
5086
22
                .tag("num_recycled", num_recycled)
5087
22
                .tag("num_recycled.prepare", num_prepare)
5088
22
                .tag("num_recycled.compacted", num_compacted)
5089
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5090
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5091
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5092
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
5093
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5077
7
    DORIS_CLOUD_DEFER {
5078
7
        unregister_recycle_task(task_name);
5079
7
        int64_t cost =
5080
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5081
7
        metrics_context.finish_report();
5082
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5083
7
                .tag("instance_id", instance_id_)
5084
7
                .tag("num_scanned", num_scanned)
5085
7
                .tag("num_expired", num_expired)
5086
7
                .tag("num_recycled", num_recycled)
5087
7
                .tag("num_recycled.prepare", num_prepare)
5088
7
                .tag("num_recycled.compacted", num_compacted)
5089
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5090
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5091
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5092
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5093
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5077
15
    DORIS_CLOUD_DEFER {
5078
15
        unregister_recycle_task(task_name);
5079
15
        int64_t cost =
5080
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5081
15
        metrics_context.finish_report();
5082
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5083
15
                .tag("instance_id", instance_id_)
5084
15
                .tag("num_scanned", num_scanned)
5085
15
                .tag("num_expired", num_expired)
5086
15
                .tag("num_recycled", num_recycled)
5087
15
                .tag("num_recycled.prepare", num_prepare)
5088
15
                .tag("num_recycled.compacted", num_compacted)
5089
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5090
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5091
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5092
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
5093
15
    };
5094
5095
22
    std::vector<std::string> rowset_keys;
5096
22
    std::vector<std::string> rowset_keys_to_mark_recycled;
5097
22
    std::vector<std::string> rowset_keys_to_abort;
5098
22
    std::vector<std::string> prepare_rowset_keys_to_delete;
5099
    // rowset_id -> rowset_meta
5100
    // store rowset id and meta for statistics rs size when delete
5101
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5102
5103
    // Store keys of rowset recycled by background workers
5104
22
    std::mutex async_recycled_rowset_keys_mutex;
5105
22
    std::vector<std::string> async_recycled_rowset_keys;
5106
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5107
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5108
22
    worker_pool->start();
5109
    // TODO bacth delete
5110
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5111
4.00k
        std::string dbm_start_key =
5112
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5113
4.00k
        std::string dbm_end_key = dbm_start_key;
5114
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
5115
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5116
4.00k
        if (ret != 0) {
5117
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5118
0
                         << instance_id_;
5119
0
        }
5120
4.00k
        return ret;
5121
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5110
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5111
3
        std::string dbm_start_key =
5112
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5113
3
        std::string dbm_end_key = dbm_start_key;
5114
3
        encode_int64(INT64_MAX, &dbm_end_key);
5115
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5116
3
        if (ret != 0) {
5117
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5118
0
                         << instance_id_;
5119
0
        }
5120
3
        return ret;
5121
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5110
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5111
4.00k
        std::string dbm_start_key =
5112
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5113
4.00k
        std::string dbm_end_key = dbm_start_key;
5114
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
5115
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5116
4.00k
        if (ret != 0) {
5117
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5118
0
                         << instance_id_;
5119
0
        }
5120
4.00k
        return ret;
5121
4.00k
    };
5122
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5123
250
                                            int64_t tablet_id, const std::string& rowset_id) {
5124
        // Try to delete rowset data in background thread
5125
250
        int ret = worker_pool->submit_with_timeout(
5126
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5127
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5128
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5129
0
                        return;
5130
0
                    }
5131
246
                    std::vector<std::string> keys;
5132
246
                    {
5133
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5134
246
                        async_recycled_rowset_keys.push_back(std::move(key));
5135
246
                        if (async_recycled_rowset_keys.size() > 100) {
5136
2
                            keys.swap(async_recycled_rowset_keys);
5137
2
                        }
5138
246
                    }
5139
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5140
246
                    if (keys.empty()) return;
5141
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5142
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5143
0
                                     << instance_id_;
5144
2
                    } else {
5145
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5146
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5147
2
                                           num_recycled, start_time);
5148
2
                    }
5149
2
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
5126
246
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5127
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5128
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5129
0
                        return;
5130
0
                    }
5131
246
                    std::vector<std::string> keys;
5132
246
                    {
5133
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5134
246
                        async_recycled_rowset_keys.push_back(std::move(key));
5135
246
                        if (async_recycled_rowset_keys.size() > 100) {
5136
2
                            keys.swap(async_recycled_rowset_keys);
5137
2
                        }
5138
246
                    }
5139
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5140
246
                    if (keys.empty()) return;
5141
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5142
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5143
0
                                     << instance_id_;
5144
2
                    } else {
5145
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5146
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5147
2
                                           num_recycled, start_time);
5148
2
                    }
5149
2
                },
5150
250
                0);
5151
250
        if (ret == 0) return 0;
5152
        // Submit task failed, delete rowset data in current thread
5153
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5154
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5155
0
            return -1;
5156
0
        }
5157
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5158
0
            return -1;
5159
0
        }
5160
4
        rowset_keys.push_back(std::move(key));
5161
4
        return 0;
5162
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
5123
250
                                            int64_t tablet_id, const std::string& rowset_id) {
5124
        // Try to delete rowset data in background thread
5125
250
        int ret = worker_pool->submit_with_timeout(
5126
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5127
250
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5128
250
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5129
250
                        return;
5130
250
                    }
5131
250
                    std::vector<std::string> keys;
5132
250
                    {
5133
250
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5134
250
                        async_recycled_rowset_keys.push_back(std::move(key));
5135
250
                        if (async_recycled_rowset_keys.size() > 100) {
5136
250
                            keys.swap(async_recycled_rowset_keys);
5137
250
                        }
5138
250
                    }
5139
250
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5140
250
                    if (keys.empty()) return;
5141
250
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5142
250
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5143
250
                                     << instance_id_;
5144
250
                    } else {
5145
250
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5146
250
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5147
250
                                           num_recycled, start_time);
5148
250
                    }
5149
250
                },
5150
250
                0);
5151
250
        if (ret == 0) return 0;
5152
        // Submit task failed, delete rowset data in current thread
5153
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5154
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5155
0
            return -1;
5156
0
        }
5157
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5158
0
            return -1;
5159
0
        }
5160
4
        rowset_keys.push_back(std::move(key));
5161
4
        return 0;
5162
4
    };
5163
5164
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5165
5166
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5167
4.00k
        ++num_scanned;
5168
4.00k
        total_rowset_key_size += k.size();
5169
4.00k
        total_rowset_value_size += v.size();
5170
4.00k
        RecycleRowsetPB rowset;
5171
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5172
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5173
0
            return -1;
5174
0
        }
5175
5176
4.00k
        int64_t current_time = ::time(nullptr);
5177
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5178
5179
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5180
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5181
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5182
4.00k
        if (current_time < expiration) { // not expired
5183
0
            return 0;
5184
0
        }
5185
4.00k
        ++num_expired;
5186
4.00k
        expired_rowset_size += v.size();
5187
5188
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5189
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5190
                // in old version, keep this key-value pair and it needs to be checked manually
5191
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5192
0
                return -1;
5193
0
            }
5194
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5195
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5196
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5197
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5198
0
                rowset_keys.emplace_back(k);
5199
0
                return -1;
5200
0
            }
5201
            // decode rowset_id
5202
250
            auto k1 = k;
5203
250
            k1.remove_prefix(1);
5204
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5205
250
            decode_key(&k1, &out);
5206
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5207
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5208
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5209
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5210
250
                      << " task_type=" << metrics_context.operation_type;
5211
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5212
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5213
0
                return -1;
5214
0
            }
5215
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5216
250
            metrics_context.total_recycled_num++;
5217
250
            segment_metrics_context_.total_recycled_data_size +=
5218
250
                    rowset.rowset_meta().total_disk_size();
5219
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5220
250
            return 0;
5221
250
        }
5222
5223
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5224
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5225
6
            if (need_mark_rowset_as_recycled(rowset)) {
5226
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5227
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5228
4
                             "at next turn, instance_id="
5229
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5230
4
                          << " version=[" << rowset_meta->start_version() << '-'
5231
4
                          << rowset_meta->end_version() << "]";
5232
4
                return 0;
5233
4
            }
5234
6
        }
5235
5236
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5237
3.75k
            rowset_meta->end_version() != 1) {
5238
2
            if (make_deferred_abort_task(rowset).has_value()) {
5239
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5240
2
                             "instance_id="
5241
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5242
2
                          << " version=[" << rowset_meta->start_version() << '-'
5243
2
                          << rowset_meta->end_version() << "]";
5244
2
                rowset_keys_to_abort.emplace_back(k);
5245
2
            }
5246
2
        }
5247
5248
        // TODO(plat1ko): check rowset not referenced
5249
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5250
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5251
0
                LOG_INFO("recycle rowset that has empty resource id");
5252
0
            } else {
5253
                // other situations, keep this key-value pair and it needs to be checked manually
5254
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5255
0
                return -1;
5256
0
            }
5257
0
        }
5258
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5259
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5260
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5261
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5262
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5263
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5264
3.75k
                  << " rowset_meta_size=" << v.size()
5265
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5266
3.75k
                  << " task_type=" << metrics_context.operation_type;
5267
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5268
            // unable to calculate file path, can only be deleted by rowset id prefix
5269
653
            num_prepare += 1;
5270
653
            prepare_rowset_keys_to_delete.emplace_back(k);
5271
3.10k
        } else {
5272
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5273
3.10k
            rowset_keys.emplace_back(k);
5274
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5275
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5276
3.10k
                ++num_empty_rowset;
5277
3.10k
            }
5278
3.10k
        }
5279
3.75k
        return 0;
5280
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5166
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5167
7
        ++num_scanned;
5168
7
        total_rowset_key_size += k.size();
5169
7
        total_rowset_value_size += v.size();
5170
7
        RecycleRowsetPB rowset;
5171
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5172
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5173
0
            return -1;
5174
0
        }
5175
5176
7
        int64_t current_time = ::time(nullptr);
5177
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5178
5179
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5180
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5181
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5182
7
        if (current_time < expiration) { // not expired
5183
0
            return 0;
5184
0
        }
5185
7
        ++num_expired;
5186
7
        expired_rowset_size += v.size();
5187
5188
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5189
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5190
                // in old version, keep this key-value pair and it needs to be checked manually
5191
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5192
0
                return -1;
5193
0
            }
5194
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5195
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5196
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5197
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5198
0
                rowset_keys.emplace_back(k);
5199
0
                return -1;
5200
0
            }
5201
            // decode rowset_id
5202
0
            auto k1 = k;
5203
0
            k1.remove_prefix(1);
5204
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5205
0
            decode_key(&k1, &out);
5206
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5207
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5208
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5209
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5210
0
                      << " task_type=" << metrics_context.operation_type;
5211
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5212
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5213
0
                return -1;
5214
0
            }
5215
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5216
0
            metrics_context.total_recycled_num++;
5217
0
            segment_metrics_context_.total_recycled_data_size +=
5218
0
                    rowset.rowset_meta().total_disk_size();
5219
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5220
0
            return 0;
5221
0
        }
5222
5223
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5224
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5225
6
            if (need_mark_rowset_as_recycled(rowset)) {
5226
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5227
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5228
4
                             "at next turn, instance_id="
5229
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5230
4
                          << " version=[" << rowset_meta->start_version() << '-'
5231
4
                          << rowset_meta->end_version() << "]";
5232
4
                return 0;
5233
4
            }
5234
6
        }
5235
5236
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5237
3
            rowset_meta->end_version() != 1) {
5238
2
            if (make_deferred_abort_task(rowset).has_value()) {
5239
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5240
2
                             "instance_id="
5241
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5242
2
                          << " version=[" << rowset_meta->start_version() << '-'
5243
2
                          << rowset_meta->end_version() << "]";
5244
2
                rowset_keys_to_abort.emplace_back(k);
5245
2
            }
5246
2
        }
5247
5248
        // TODO(plat1ko): check rowset not referenced
5249
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5250
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5251
0
                LOG_INFO("recycle rowset that has empty resource id");
5252
0
            } else {
5253
                // other situations, keep this key-value pair and it needs to be checked manually
5254
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5255
0
                return -1;
5256
0
            }
5257
0
        }
5258
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5259
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5260
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5261
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5262
3
                  << "] txn_id=" << rowset_meta->txn_id()
5263
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5264
3
                  << " rowset_meta_size=" << v.size()
5265
3
                  << " creation_time=" << rowset_meta->creation_time()
5266
3
                  << " task_type=" << metrics_context.operation_type;
5267
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5268
            // unable to calculate file path, can only be deleted by rowset id prefix
5269
3
            num_prepare += 1;
5270
3
            prepare_rowset_keys_to_delete.emplace_back(k);
5271
3
        } else {
5272
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5273
0
            rowset_keys.emplace_back(k);
5274
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5275
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5276
0
                ++num_empty_rowset;
5277
0
            }
5278
0
        }
5279
3
        return 0;
5280
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5166
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5167
4.00k
        ++num_scanned;
5168
4.00k
        total_rowset_key_size += k.size();
5169
4.00k
        total_rowset_value_size += v.size();
5170
4.00k
        RecycleRowsetPB rowset;
5171
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5172
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5173
0
            return -1;
5174
0
        }
5175
5176
4.00k
        int64_t current_time = ::time(nullptr);
5177
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5178
5179
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5180
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5181
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5182
4.00k
        if (current_time < expiration) { // not expired
5183
0
            return 0;
5184
0
        }
5185
4.00k
        ++num_expired;
5186
4.00k
        expired_rowset_size += v.size();
5187
5188
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5189
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5190
                // in old version, keep this key-value pair and it needs to be checked manually
5191
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5192
0
                return -1;
5193
0
            }
5194
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5195
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5196
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5197
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5198
0
                rowset_keys.emplace_back(k);
5199
0
                return -1;
5200
0
            }
5201
            // decode rowset_id
5202
250
            auto k1 = k;
5203
250
            k1.remove_prefix(1);
5204
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5205
250
            decode_key(&k1, &out);
5206
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5207
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5208
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5209
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5210
250
                      << " task_type=" << metrics_context.operation_type;
5211
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5212
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5213
0
                return -1;
5214
0
            }
5215
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5216
250
            metrics_context.total_recycled_num++;
5217
250
            segment_metrics_context_.total_recycled_data_size +=
5218
250
                    rowset.rowset_meta().total_disk_size();
5219
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5220
250
            return 0;
5221
250
        }
5222
5223
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5224
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5225
0
            if (need_mark_rowset_as_recycled(rowset)) {
5226
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5227
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5228
0
                             "at next turn, instance_id="
5229
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5230
0
                          << " version=[" << rowset_meta->start_version() << '-'
5231
0
                          << rowset_meta->end_version() << "]";
5232
0
                return 0;
5233
0
            }
5234
0
        }
5235
5236
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5237
3.75k
            rowset_meta->end_version() != 1) {
5238
0
            if (make_deferred_abort_task(rowset).has_value()) {
5239
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5240
0
                             "instance_id="
5241
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5242
0
                          << " version=[" << rowset_meta->start_version() << '-'
5243
0
                          << rowset_meta->end_version() << "]";
5244
0
                rowset_keys_to_abort.emplace_back(k);
5245
0
            }
5246
0
        }
5247
5248
        // TODO(plat1ko): check rowset not referenced
5249
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5250
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5251
0
                LOG_INFO("recycle rowset that has empty resource id");
5252
0
            } else {
5253
                // other situations, keep this key-value pair and it needs to be checked manually
5254
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5255
0
                return -1;
5256
0
            }
5257
0
        }
5258
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5259
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5260
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5261
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5262
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5263
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5264
3.75k
                  << " rowset_meta_size=" << v.size()
5265
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5266
3.75k
                  << " task_type=" << metrics_context.operation_type;
5267
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5268
            // unable to calculate file path, can only be deleted by rowset id prefix
5269
650
            num_prepare += 1;
5270
650
            prepare_rowset_keys_to_delete.emplace_back(k);
5271
3.10k
        } else {
5272
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5273
3.10k
            rowset_keys.emplace_back(k);
5274
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5275
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5276
3.10k
                ++num_empty_rowset;
5277
3.10k
            }
5278
3.10k
        }
5279
3.75k
        return 0;
5280
3.75k
    };
5281
5282
28
    auto loop_done = [&]() -> int {
5283
28
        std::vector<std::string> rowset_keys_to_delete;
5284
28
        std::vector<std::string> mark_keys_to_process;
5285
28
        std::vector<std::string> abort_keys_to_process;
5286
28
        std::vector<std::string> prepare_keys_to_process;
5287
        // rowset_id -> rowset_meta
5288
        // store rowset id and meta for statistics rs size when delete
5289
28
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5290
28
        rowset_keys_to_delete.swap(rowset_keys);
5291
28
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5292
28
        abort_keys_to_process.swap(rowset_keys_to_abort);
5293
28
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5294
28
        rowsets_to_delete.swap(rowsets);
5295
28
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5296
28
                             rowsets_to_delete = std::move(rowsets_to_delete),
5297
28
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5298
28
                             mark_keys_to_process = std::move(mark_keys_to_process),
5299
28
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5300
28
            if (!mark_keys_to_process.empty() &&
5301
28
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5302
4
                                                                mark_keys_to_process) != 0) {
5303
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5304
0
                             << instance_id_;
5305
0
                return;
5306
0
            }
5307
28
            if (!abort_keys_to_process.empty() &&
5308
28
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5309
2
                        0) {
5310
0
                return;
5311
0
            }
5312
28
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5313
28
            if (!prepare_keys_to_process.empty() &&
5314
28
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5315
24
                                             &prepare_delete_tasks) != 0) {
5316
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5317
0
                             << instance_id_;
5318
0
                return;
5319
0
            }
5320
28
            if (!prepare_delete_tasks.empty()) {
5321
24
                std::vector<std::string> prepare_rowset_keys_to_delete;
5322
24
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5323
653
                for (const auto& task : prepare_delete_tasks) {
5324
653
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5325
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5326
0
                        return;
5327
0
                    }
5328
653
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5329
0
                        return;
5330
0
                    }
5331
653
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5332
653
                }
5333
24
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5334
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5335
0
                                 << instance_id_;
5336
0
                    return;
5337
0
                }
5338
24
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5339
24
                                       std::memory_order_relaxed);
5340
24
            }
5341
28
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5342
28
                                   metrics_context) != 0) {
5343
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5344
0
                return;
5345
0
            }
5346
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5347
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5348
0
                    return;
5349
0
                }
5350
3.10k
            }
5351
28
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5352
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5353
0
                return;
5354
0
            }
5355
28
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5356
28
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5299
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5300
7
            if (!mark_keys_to_process.empty() &&
5301
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5302
4
                                                                mark_keys_to_process) != 0) {
5303
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5304
0
                             << instance_id_;
5305
0
                return;
5306
0
            }
5307
7
            if (!abort_keys_to_process.empty() &&
5308
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5309
2
                        0) {
5310
0
                return;
5311
0
            }
5312
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5313
7
            if (!prepare_keys_to_process.empty() &&
5314
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5315
3
                                             &prepare_delete_tasks) != 0) {
5316
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5317
0
                             << instance_id_;
5318
0
                return;
5319
0
            }
5320
7
            if (!prepare_delete_tasks.empty()) {
5321
3
                std::vector<std::string> prepare_rowset_keys_to_delete;
5322
3
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5323
3
                for (const auto& task : prepare_delete_tasks) {
5324
3
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5325
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5326
0
                        return;
5327
0
                    }
5328
3
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5329
0
                        return;
5330
0
                    }
5331
3
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5332
3
                }
5333
3
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5334
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5335
0
                                 << instance_id_;
5336
0
                    return;
5337
0
                }
5338
3
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5339
3
                                       std::memory_order_relaxed);
5340
3
            }
5341
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5342
7
                                   metrics_context) != 0) {
5343
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5344
0
                return;
5345
0
            }
5346
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5347
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5348
0
                    return;
5349
0
                }
5350
0
            }
5351
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5352
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5353
0
                return;
5354
0
            }
5355
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5356
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5299
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5300
21
            if (!mark_keys_to_process.empty() &&
5301
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5302
0
                                                                mark_keys_to_process) != 0) {
5303
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5304
0
                             << instance_id_;
5305
0
                return;
5306
0
            }
5307
21
            if (!abort_keys_to_process.empty() &&
5308
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5309
0
                        0) {
5310
0
                return;
5311
0
            }
5312
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5313
21
            if (!prepare_keys_to_process.empty() &&
5314
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5315
21
                                             &prepare_delete_tasks) != 0) {
5316
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5317
0
                             << instance_id_;
5318
0
                return;
5319
0
            }
5320
21
            if (!prepare_delete_tasks.empty()) {
5321
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5322
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5323
650
                for (const auto& task : prepare_delete_tasks) {
5324
650
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5325
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5326
0
                        return;
5327
0
                    }
5328
650
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5329
0
                        return;
5330
0
                    }
5331
650
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5332
650
                }
5333
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5334
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5335
0
                                 << instance_id_;
5336
0
                    return;
5337
0
                }
5338
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5339
21
                                       std::memory_order_relaxed);
5340
21
            }
5341
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5342
21
                                   metrics_context) != 0) {
5343
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5344
0
                return;
5345
0
            }
5346
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5347
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5348
0
                    return;
5349
0
                }
5350
3.10k
            }
5351
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5352
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5353
0
                return;
5354
0
            }
5355
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5356
21
        });
5357
28
        return 0;
5358
28
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5282
7
    auto loop_done = [&]() -> int {
5283
7
        std::vector<std::string> rowset_keys_to_delete;
5284
7
        std::vector<std::string> mark_keys_to_process;
5285
7
        std::vector<std::string> abort_keys_to_process;
5286
7
        std::vector<std::string> prepare_keys_to_process;
5287
        // rowset_id -> rowset_meta
5288
        // store rowset id and meta for statistics rs size when delete
5289
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5290
7
        rowset_keys_to_delete.swap(rowset_keys);
5291
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5292
7
        abort_keys_to_process.swap(rowset_keys_to_abort);
5293
7
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5294
7
        rowsets_to_delete.swap(rowsets);
5295
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5296
7
                             rowsets_to_delete = std::move(rowsets_to_delete),
5297
7
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5298
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5299
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5300
7
            if (!mark_keys_to_process.empty() &&
5301
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5302
7
                                                                mark_keys_to_process) != 0) {
5303
7
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5304
7
                             << instance_id_;
5305
7
                return;
5306
7
            }
5307
7
            if (!abort_keys_to_process.empty() &&
5308
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5309
7
                        0) {
5310
7
                return;
5311
7
            }
5312
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5313
7
            if (!prepare_keys_to_process.empty() &&
5314
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5315
7
                                             &prepare_delete_tasks) != 0) {
5316
7
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5317
7
                             << instance_id_;
5318
7
                return;
5319
7
            }
5320
7
            if (!prepare_delete_tasks.empty()) {
5321
7
                std::vector<std::string> prepare_rowset_keys_to_delete;
5322
7
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5323
7
                for (const auto& task : prepare_delete_tasks) {
5324
7
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5325
7
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5326
7
                        return;
5327
7
                    }
5328
7
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5329
7
                        return;
5330
7
                    }
5331
7
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5332
7
                }
5333
7
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5334
7
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5335
7
                                 << instance_id_;
5336
7
                    return;
5337
7
                }
5338
7
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5339
7
                                       std::memory_order_relaxed);
5340
7
            }
5341
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5342
7
                                   metrics_context) != 0) {
5343
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5344
7
                return;
5345
7
            }
5346
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5347
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5348
7
                    return;
5349
7
                }
5350
7
            }
5351
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5352
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5353
7
                return;
5354
7
            }
5355
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5356
7
        });
5357
7
        return 0;
5358
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5282
21
    auto loop_done = [&]() -> int {
5283
21
        std::vector<std::string> rowset_keys_to_delete;
5284
21
        std::vector<std::string> mark_keys_to_process;
5285
21
        std::vector<std::string> abort_keys_to_process;
5286
21
        std::vector<std::string> prepare_keys_to_process;
5287
        // rowset_id -> rowset_meta
5288
        // store rowset id and meta for statistics rs size when delete
5289
21
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5290
21
        rowset_keys_to_delete.swap(rowset_keys);
5291
21
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5292
21
        abort_keys_to_process.swap(rowset_keys_to_abort);
5293
21
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5294
21
        rowsets_to_delete.swap(rowsets);
5295
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5296
21
                             rowsets_to_delete = std::move(rowsets_to_delete),
5297
21
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5298
21
                             mark_keys_to_process = std::move(mark_keys_to_process),
5299
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5300
21
            if (!mark_keys_to_process.empty() &&
5301
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5302
21
                                                                mark_keys_to_process) != 0) {
5303
21
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5304
21
                             << instance_id_;
5305
21
                return;
5306
21
            }
5307
21
            if (!abort_keys_to_process.empty() &&
5308
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5309
21
                        0) {
5310
21
                return;
5311
21
            }
5312
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5313
21
            if (!prepare_keys_to_process.empty() &&
5314
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5315
21
                                             &prepare_delete_tasks) != 0) {
5316
21
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5317
21
                             << instance_id_;
5318
21
                return;
5319
21
            }
5320
21
            if (!prepare_delete_tasks.empty()) {
5321
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5322
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5323
21
                for (const auto& task : prepare_delete_tasks) {
5324
21
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5325
21
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5326
21
                        return;
5327
21
                    }
5328
21
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5329
21
                        return;
5330
21
                    }
5331
21
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5332
21
                }
5333
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5334
21
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5335
21
                                 << instance_id_;
5336
21
                    return;
5337
21
                }
5338
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5339
21
                                       std::memory_order_relaxed);
5340
21
            }
5341
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5342
21
                                   metrics_context) != 0) {
5343
21
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5344
21
                return;
5345
21
            }
5346
21
            for (const auto& [_, rs] : rowsets_to_delete) {
5347
21
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5348
21
                    return;
5349
21
                }
5350
21
            }
5351
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5352
21
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5353
21
                return;
5354
21
            }
5355
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5356
21
        });
5357
21
        return 0;
5358
21
    };
5359
5360
22
    if (config::enable_recycler_stats_metrics) {
5361
0
        scan_and_statistics_rowsets();
5362
0
    }
5363
    // recycle_func and loop_done for scan and recycle
5364
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5365
22
                               std::move(loop_done));
5366
5367
22
    worker_pool->stop();
5368
5369
22
    if (!async_recycled_rowset_keys.empty()) {
5370
1
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5371
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5372
0
            return -1;
5373
1
        } else {
5374
1
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5375
1
        }
5376
1
    }
5377
5378
    // Report final metrics after all concurrent tasks completed
5379
22
    segment_metrics_context_.report();
5380
22
    metrics_context.report();
5381
5382
22
    return ret;
5383
22
}
5384
5385
13
int InstanceRecycler::recycle_restore_jobs() {
5386
13
    const std::string task_name = "recycle_restore_jobs";
5387
13
    int64_t num_scanned = 0;
5388
13
    int64_t num_expired = 0;
5389
13
    int64_t num_recycled = 0;
5390
13
    int64_t num_aborted = 0;
5391
5392
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5393
5394
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5395
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5396
13
    std::string restore_job_key0;
5397
13
    std::string restore_job_key1;
5398
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5399
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5400
5401
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5402
5403
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5404
13
    register_recycle_task(task_name, start_time);
5405
5406
13
    DORIS_CLOUD_DEFER {
5407
13
        unregister_recycle_task(task_name);
5408
13
        int64_t cost =
5409
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5410
13
        metrics_context.finish_report();
5411
5412
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5413
13
                .tag("instance_id", instance_id_)
5414
13
                .tag("num_scanned", num_scanned)
5415
13
                .tag("num_expired", num_expired)
5416
13
                .tag("num_recycled", num_recycled)
5417
13
                .tag("num_aborted", num_aborted);
5418
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5406
13
    DORIS_CLOUD_DEFER {
5407
13
        unregister_recycle_task(task_name);
5408
13
        int64_t cost =
5409
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5410
13
        metrics_context.finish_report();
5411
5412
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5413
13
                .tag("instance_id", instance_id_)
5414
13
                .tag("num_scanned", num_scanned)
5415
13
                .tag("num_expired", num_expired)
5416
13
                .tag("num_recycled", num_recycled)
5417
13
                .tag("num_aborted", num_aborted);
5418
13
    };
5419
5420
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5421
5422
13
    std::vector<std::string_view> restore_job_keys;
5423
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5424
41
        ++num_scanned;
5425
41
        RestoreJobCloudPB restore_job_pb;
5426
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5427
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5428
0
            return -1;
5429
0
        }
5430
41
        int64_t expiration =
5431
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5432
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5433
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5434
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5435
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5436
0
                   << " state=" << restore_job_pb.state();
5437
41
        int64_t current_time = ::time(nullptr);
5438
41
        if (current_time < expiration) { // not expired
5439
0
            return 0;
5440
0
        }
5441
41
        ++num_expired;
5442
5443
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5444
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5445
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5446
5447
41
        std::unique_ptr<Transaction> txn;
5448
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5449
41
        if (err != TxnErrorCode::TXN_OK) {
5450
0
            LOG_WARNING("failed to recycle restore job")
5451
0
                    .tag("err", err)
5452
0
                    .tag("tablet id", tablet_id)
5453
0
                    .tag("instance_id", instance_id_)
5454
0
                    .tag("reason", "failed to create txn");
5455
0
            return -1;
5456
0
        }
5457
5458
41
        std::string val;
5459
41
        err = txn->get(k, &val);
5460
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5461
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5462
0
            return 0;
5463
0
        }
5464
41
        if (err != TxnErrorCode::TXN_OK) {
5465
0
            LOG_WARNING("failed to get kv");
5466
0
            return -1;
5467
0
        }
5468
41
        restore_job_pb.Clear();
5469
41
        if (!restore_job_pb.ParseFromString(val)) {
5470
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5471
0
            return -1;
5472
0
        }
5473
5474
        // PREPARED or COMMITTED, change state to DROPPED and return
5475
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5476
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5477
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5478
0
            restore_job_pb.set_need_recycle_data(true);
5479
0
            txn->put(k, restore_job_pb.SerializeAsString());
5480
0
            err = txn->commit();
5481
0
            if (err != TxnErrorCode::TXN_OK) {
5482
0
                LOG_WARNING("failed to commit txn: {}", err);
5483
0
                return -1;
5484
0
            }
5485
0
            num_aborted++;
5486
0
            return 0;
5487
0
        }
5488
5489
        // Change state to RECYCLING
5490
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5491
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5492
21
            txn->put(k, restore_job_pb.SerializeAsString());
5493
21
            err = txn->commit();
5494
21
            if (err != TxnErrorCode::TXN_OK) {
5495
0
                LOG_WARNING("failed to commit txn: {}", err);
5496
0
                return -1;
5497
0
            }
5498
21
            return 0;
5499
21
        }
5500
5501
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5502
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5503
5504
        // Recycle all data associated with the restore job.
5505
        // This includes rowsets, segments, and related resources.
5506
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5507
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5508
0
            LOG_WARNING("failed to recycle tablet")
5509
0
                    .tag("tablet_id", tablet_id)
5510
0
                    .tag("instance_id", instance_id_);
5511
0
            return -1;
5512
0
        }
5513
5514
        // delete all restore job rowset kv
5515
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5516
5517
20
        err = txn->commit();
5518
20
        if (err != TxnErrorCode::TXN_OK) {
5519
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5520
0
                    .tag("err", err)
5521
0
                    .tag("tablet id", tablet_id)
5522
0
                    .tag("instance_id", instance_id_)
5523
0
                    .tag("reason", "failed to commit txn");
5524
0
            return -1;
5525
0
        }
5526
5527
20
        metrics_context.total_recycled_num = ++num_recycled;
5528
20
        metrics_context.report();
5529
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5530
20
        restore_job_keys.push_back(k);
5531
5532
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5533
20
                  << " tablet_id=" << tablet_id;
5534
20
        return 0;
5535
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
5423
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5424
41
        ++num_scanned;
5425
41
        RestoreJobCloudPB restore_job_pb;
5426
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5427
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5428
0
            return -1;
5429
0
        }
5430
41
        int64_t expiration =
5431
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5432
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5433
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5434
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5435
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5436
0
                   << " state=" << restore_job_pb.state();
5437
41
        int64_t current_time = ::time(nullptr);
5438
41
        if (current_time < expiration) { // not expired
5439
0
            return 0;
5440
0
        }
5441
41
        ++num_expired;
5442
5443
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5444
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5445
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5446
5447
41
        std::unique_ptr<Transaction> txn;
5448
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5449
41
        if (err != TxnErrorCode::TXN_OK) {
5450
0
            LOG_WARNING("failed to recycle restore job")
5451
0
                    .tag("err", err)
5452
0
                    .tag("tablet id", tablet_id)
5453
0
                    .tag("instance_id", instance_id_)
5454
0
                    .tag("reason", "failed to create txn");
5455
0
            return -1;
5456
0
        }
5457
5458
41
        std::string val;
5459
41
        err = txn->get(k, &val);
5460
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5461
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5462
0
            return 0;
5463
0
        }
5464
41
        if (err != TxnErrorCode::TXN_OK) {
5465
0
            LOG_WARNING("failed to get kv");
5466
0
            return -1;
5467
0
        }
5468
41
        restore_job_pb.Clear();
5469
41
        if (!restore_job_pb.ParseFromString(val)) {
5470
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5471
0
            return -1;
5472
0
        }
5473
5474
        // PREPARED or COMMITTED, change state to DROPPED and return
5475
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5476
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5477
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5478
0
            restore_job_pb.set_need_recycle_data(true);
5479
0
            txn->put(k, restore_job_pb.SerializeAsString());
5480
0
            err = txn->commit();
5481
0
            if (err != TxnErrorCode::TXN_OK) {
5482
0
                LOG_WARNING("failed to commit txn: {}", err);
5483
0
                return -1;
5484
0
            }
5485
0
            num_aborted++;
5486
0
            return 0;
5487
0
        }
5488
5489
        // Change state to RECYCLING
5490
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5491
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5492
21
            txn->put(k, restore_job_pb.SerializeAsString());
5493
21
            err = txn->commit();
5494
21
            if (err != TxnErrorCode::TXN_OK) {
5495
0
                LOG_WARNING("failed to commit txn: {}", err);
5496
0
                return -1;
5497
0
            }
5498
21
            return 0;
5499
21
        }
5500
5501
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5502
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5503
5504
        // Recycle all data associated with the restore job.
5505
        // This includes rowsets, segments, and related resources.
5506
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5507
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5508
0
            LOG_WARNING("failed to recycle tablet")
5509
0
                    .tag("tablet_id", tablet_id)
5510
0
                    .tag("instance_id", instance_id_);
5511
0
            return -1;
5512
0
        }
5513
5514
        // delete all restore job rowset kv
5515
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5516
5517
20
        err = txn->commit();
5518
20
        if (err != TxnErrorCode::TXN_OK) {
5519
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5520
0
                    .tag("err", err)
5521
0
                    .tag("tablet id", tablet_id)
5522
0
                    .tag("instance_id", instance_id_)
5523
0
                    .tag("reason", "failed to commit txn");
5524
0
            return -1;
5525
0
        }
5526
5527
20
        metrics_context.total_recycled_num = ++num_recycled;
5528
20
        metrics_context.report();
5529
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5530
20
        restore_job_keys.push_back(k);
5531
5532
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5533
20
                  << " tablet_id=" << tablet_id;
5534
20
        return 0;
5535
20
    };
5536
5537
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5538
3
        if (restore_job_keys.empty()) return 0;
5539
1
        DORIS_CLOUD_DEFER {
5540
1
            restore_job_keys.clear();
5541
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5539
1
        DORIS_CLOUD_DEFER {
5540
1
            restore_job_keys.clear();
5541
1
        };
5542
5543
1
        std::unique_ptr<Transaction> txn;
5544
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5545
1
        if (err != TxnErrorCode::TXN_OK) {
5546
0
            LOG_WARNING("failed to recycle restore job")
5547
0
                    .tag("err", err)
5548
0
                    .tag("instance_id", instance_id_)
5549
0
                    .tag("reason", "failed to create txn");
5550
0
            return -1;
5551
0
        }
5552
20
        for (auto& k : restore_job_keys) {
5553
20
            txn->remove(k);
5554
20
        }
5555
1
        err = txn->commit();
5556
1
        if (err != TxnErrorCode::TXN_OK) {
5557
0
            LOG_WARNING("failed to recycle restore job")
5558
0
                    .tag("err", err)
5559
0
                    .tag("instance_id", instance_id_)
5560
0
                    .tag("reason", "failed to commit txn");
5561
0
            return -1;
5562
0
        }
5563
1
        return 0;
5564
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5537
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5538
3
        if (restore_job_keys.empty()) return 0;
5539
1
        DORIS_CLOUD_DEFER {
5540
1
            restore_job_keys.clear();
5541
1
        };
5542
5543
1
        std::unique_ptr<Transaction> txn;
5544
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5545
1
        if (err != TxnErrorCode::TXN_OK) {
5546
0
            LOG_WARNING("failed to recycle restore job")
5547
0
                    .tag("err", err)
5548
0
                    .tag("instance_id", instance_id_)
5549
0
                    .tag("reason", "failed to create txn");
5550
0
            return -1;
5551
0
        }
5552
20
        for (auto& k : restore_job_keys) {
5553
20
            txn->remove(k);
5554
20
        }
5555
1
        err = txn->commit();
5556
1
        if (err != TxnErrorCode::TXN_OK) {
5557
0
            LOG_WARNING("failed to recycle restore job")
5558
0
                    .tag("err", err)
5559
0
                    .tag("instance_id", instance_id_)
5560
0
                    .tag("reason", "failed to commit txn");
5561
0
            return -1;
5562
0
        }
5563
1
        return 0;
5564
1
    };
5565
5566
13
    if (config::enable_recycler_stats_metrics) {
5567
0
        scan_and_statistics_restore_jobs();
5568
0
    }
5569
5570
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5571
13
                            std::move(loop_done));
5572
13
}
5573
5574
11
int InstanceRecycler::recycle_versioned_rowsets() {
5575
11
    const std::string task_name = "recycle_rowsets";
5576
11
    int64_t num_scanned = 0;
5577
11
    int64_t num_expired = 0;
5578
11
    int64_t num_prepare = 0;
5579
11
    int64_t num_compacted = 0;
5580
11
    int64_t num_empty_rowset = 0;
5581
11
    size_t total_rowset_key_size = 0;
5582
11
    size_t total_rowset_value_size = 0;
5583
11
    size_t expired_rowset_size = 0;
5584
11
    std::atomic_long num_recycled = 0;
5585
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5586
5587
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5588
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5589
11
    std::string recyc_rs_key0;
5590
11
    std::string recyc_rs_key1;
5591
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5592
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5593
5594
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5595
5596
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5597
11
    register_recycle_task(task_name, start_time);
5598
5599
11
    DORIS_CLOUD_DEFER {
5600
11
        unregister_recycle_task(task_name);
5601
11
        int64_t cost =
5602
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5603
11
        metrics_context.finish_report();
5604
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5605
11
                .tag("instance_id", instance_id_)
5606
11
                .tag("num_scanned", num_scanned)
5607
11
                .tag("num_expired", num_expired)
5608
11
                .tag("num_recycled", num_recycled)
5609
11
                .tag("num_recycled.prepare", num_prepare)
5610
11
                .tag("num_recycled.compacted", num_compacted)
5611
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5612
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5613
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5614
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5615
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5599
11
    DORIS_CLOUD_DEFER {
5600
11
        unregister_recycle_task(task_name);
5601
11
        int64_t cost =
5602
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5603
11
        metrics_context.finish_report();
5604
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5605
11
                .tag("instance_id", instance_id_)
5606
11
                .tag("num_scanned", num_scanned)
5607
11
                .tag("num_expired", num_expired)
5608
11
                .tag("num_recycled", num_recycled)
5609
11
                .tag("num_recycled.prepare", num_prepare)
5610
11
                .tag("num_recycled.compacted", num_compacted)
5611
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5612
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5613
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5614
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5615
11
    };
5616
5617
11
    std::vector<std::string> orphan_rowset_keys;
5618
5619
    // Store keys of rowset recycled by background workers
5620
11
    std::mutex async_recycled_rowset_keys_mutex;
5621
11
    std::vector<std::string> async_recycled_rowset_keys;
5622
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5623
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5624
11
    worker_pool->start();
5625
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5626
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5627
        // Try to delete rowset data in background thread
5628
400
        int ret = worker_pool->submit_with_timeout(
5629
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5630
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5631
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5632
400
                        return;
5633
400
                    }
5634
                    // The async recycled rowsets are staled format or has not been used,
5635
                    // so we don't need to check the rowset ref count key.
5636
0
                    std::vector<std::string> keys;
5637
0
                    {
5638
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5639
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5640
0
                        if (async_recycled_rowset_keys.size() > 100) {
5641
0
                            keys.swap(async_recycled_rowset_keys);
5642
0
                        }
5643
0
                    }
5644
0
                    if (keys.empty()) return;
5645
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5646
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5647
0
                                     << instance_id_;
5648
0
                    } else {
5649
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5650
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5651
0
                                           num_recycled, start_time);
5652
0
                    }
5653
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
5629
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5630
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5631
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5632
400
                        return;
5633
400
                    }
5634
                    // The async recycled rowsets are staled format or has not been used,
5635
                    // so we don't need to check the rowset ref count key.
5636
0
                    std::vector<std::string> keys;
5637
0
                    {
5638
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5639
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5640
0
                        if (async_recycled_rowset_keys.size() > 100) {
5641
0
                            keys.swap(async_recycled_rowset_keys);
5642
0
                        }
5643
0
                    }
5644
0
                    if (keys.empty()) return;
5645
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5646
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5647
0
                                     << instance_id_;
5648
0
                    } else {
5649
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5650
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5651
0
                                           num_recycled, start_time);
5652
0
                    }
5653
0
                },
5654
400
                0);
5655
400
        if (ret == 0) return 0;
5656
        // Submit task failed, delete rowset data in current thread
5657
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5658
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5659
0
            return -1;
5660
0
        }
5661
0
        orphan_rowset_keys.push_back(std::move(key));
5662
0
        return 0;
5663
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
5626
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5627
        // Try to delete rowset data in background thread
5628
400
        int ret = worker_pool->submit_with_timeout(
5629
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5630
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5631
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5632
400
                        return;
5633
400
                    }
5634
                    // The async recycled rowsets are staled format or has not been used,
5635
                    // so we don't need to check the rowset ref count key.
5636
400
                    std::vector<std::string> keys;
5637
400
                    {
5638
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5639
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5640
400
                        if (async_recycled_rowset_keys.size() > 100) {
5641
400
                            keys.swap(async_recycled_rowset_keys);
5642
400
                        }
5643
400
                    }
5644
400
                    if (keys.empty()) return;
5645
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5646
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5647
400
                                     << instance_id_;
5648
400
                    } else {
5649
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5650
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5651
400
                                           num_recycled, start_time);
5652
400
                    }
5653
400
                },
5654
400
                0);
5655
400
        if (ret == 0) return 0;
5656
        // Submit task failed, delete rowset data in current thread
5657
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5658
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5659
0
            return -1;
5660
0
        }
5661
0
        orphan_rowset_keys.push_back(std::move(key));
5662
0
        return 0;
5663
0
    };
5664
5665
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5666
5667
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5668
2.01k
        ++num_scanned;
5669
2.01k
        total_rowset_key_size += k.size();
5670
2.01k
        total_rowset_value_size += v.size();
5671
2.01k
        RecycleRowsetPB rowset;
5672
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5673
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5674
0
            return -1;
5675
0
        }
5676
5677
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5678
5679
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5680
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5681
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5682
2.01k
        int64_t current_time = ::time(nullptr);
5683
2.01k
        if (current_time < final_expiration) { // not expired
5684
0
            return 0;
5685
0
        }
5686
2.01k
        ++num_expired;
5687
2.01k
        expired_rowset_size += v.size();
5688
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5689
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5690
                // in old version, keep this key-value pair and it needs to be checked manually
5691
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5692
0
                return -1;
5693
0
            }
5694
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5695
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5696
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5697
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5698
0
                orphan_rowset_keys.emplace_back(k);
5699
0
                return -1;
5700
0
            }
5701
            // decode rowset_id
5702
0
            auto k1 = k;
5703
0
            k1.remove_prefix(1);
5704
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5705
0
            decode_key(&k1, &out);
5706
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5707
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5708
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5709
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5710
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5711
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5712
0
                return -1;
5713
0
            }
5714
0
            return 0;
5715
0
        }
5716
        // TODO(plat1ko): check rowset not referenced
5717
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5718
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5719
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5720
0
                LOG_INFO("recycle rowset that has empty resource id");
5721
0
            } else {
5722
                // other situations, keep this key-value pair and it needs to be checked manually
5723
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5724
0
                return -1;
5725
0
            }
5726
0
        }
5727
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5728
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5729
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5730
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5731
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5732
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5733
2.01k
                  << " rowset_meta_size=" << v.size()
5734
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5735
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5736
            // unable to calculate file path, can only be deleted by rowset id prefix
5737
400
            num_prepare += 1;
5738
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5739
400
                                             rowset_meta->tablet_id(),
5740
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5741
0
                return -1;
5742
0
            }
5743
1.61k
        } else {
5744
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5745
1.61k
            worker_pool->submit(
5746
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5747
                        // The load & compact rowset keys are recycled during recycling operation logs.
5748
1.61k
                        RowsetDeleteTask task;
5749
1.61k
                        task.rowset_meta = rowset_meta;
5750
1.61k
                        task.recycle_rowset_key = k;
5751
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5752
1.60k
                            return;
5753
1.60k
                        }
5754
13
                        num_compacted += is_compacted;
5755
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5756
13
                        if (rowset_meta.num_segments() == 0) {
5757
0
                            ++num_empty_rowset;
5758
0
                        }
5759
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
5746
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5747
                        // The load & compact rowset keys are recycled during recycling operation logs.
5748
1.61k
                        RowsetDeleteTask task;
5749
1.61k
                        task.rowset_meta = rowset_meta;
5750
1.61k
                        task.recycle_rowset_key = k;
5751
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5752
1.60k
                            return;
5753
1.60k
                        }
5754
13
                        num_compacted += is_compacted;
5755
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5756
13
                        if (rowset_meta.num_segments() == 0) {
5757
0
                            ++num_empty_rowset;
5758
0
                        }
5759
13
                    });
5760
1.61k
        }
5761
2.01k
        return 0;
5762
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
5667
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5668
2.01k
        ++num_scanned;
5669
2.01k
        total_rowset_key_size += k.size();
5670
2.01k
        total_rowset_value_size += v.size();
5671
2.01k
        RecycleRowsetPB rowset;
5672
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5673
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5674
0
            return -1;
5675
0
        }
5676
5677
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5678
5679
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5680
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5681
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5682
2.01k
        int64_t current_time = ::time(nullptr);
5683
2.01k
        if (current_time < final_expiration) { // not expired
5684
0
            return 0;
5685
0
        }
5686
2.01k
        ++num_expired;
5687
2.01k
        expired_rowset_size += v.size();
5688
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5689
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5690
                // in old version, keep this key-value pair and it needs to be checked manually
5691
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5692
0
                return -1;
5693
0
            }
5694
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5695
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5696
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5697
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5698
0
                orphan_rowset_keys.emplace_back(k);
5699
0
                return -1;
5700
0
            }
5701
            // decode rowset_id
5702
0
            auto k1 = k;
5703
0
            k1.remove_prefix(1);
5704
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5705
0
            decode_key(&k1, &out);
5706
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5707
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5708
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5709
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5710
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5711
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5712
0
                return -1;
5713
0
            }
5714
0
            return 0;
5715
0
        }
5716
        // TODO(plat1ko): check rowset not referenced
5717
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5718
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5719
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5720
0
                LOG_INFO("recycle rowset that has empty resource id");
5721
0
            } else {
5722
                // other situations, keep this key-value pair and it needs to be checked manually
5723
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5724
0
                return -1;
5725
0
            }
5726
0
        }
5727
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5728
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5729
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5730
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5731
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5732
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5733
2.01k
                  << " rowset_meta_size=" << v.size()
5734
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5735
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5736
            // unable to calculate file path, can only be deleted by rowset id prefix
5737
400
            num_prepare += 1;
5738
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5739
400
                                             rowset_meta->tablet_id(),
5740
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5741
0
                return -1;
5742
0
            }
5743
1.61k
        } else {
5744
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5745
1.61k
            worker_pool->submit(
5746
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5747
                        // The load & compact rowset keys are recycled during recycling operation logs.
5748
1.61k
                        RowsetDeleteTask task;
5749
1.61k
                        task.rowset_meta = rowset_meta;
5750
1.61k
                        task.recycle_rowset_key = k;
5751
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
5752
1.61k
                            return;
5753
1.61k
                        }
5754
1.61k
                        num_compacted += is_compacted;
5755
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5756
1.61k
                        if (rowset_meta.num_segments() == 0) {
5757
1.61k
                            ++num_empty_rowset;
5758
1.61k
                        }
5759
1.61k
                    });
5760
1.61k
        }
5761
2.01k
        return 0;
5762
2.01k
    };
5763
5764
11
    if (config::enable_recycler_stats_metrics) {
5765
0
        scan_and_statistics_rowsets();
5766
0
    }
5767
5768
11
    auto loop_done = [&]() -> int {
5769
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5770
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5771
0
        }
5772
6
        orphan_rowset_keys.clear();
5773
6
        return 0;
5774
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5768
6
    auto loop_done = [&]() -> int {
5769
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5770
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5771
0
        }
5772
6
        orphan_rowset_keys.clear();
5773
6
        return 0;
5774
6
    };
5775
5776
    // recycle_func and loop_done for scan and recycle
5777
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5778
11
                               std::move(loop_done));
5779
5780
11
    worker_pool->stop();
5781
5782
11
    if (!async_recycled_rowset_keys.empty()) {
5783
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5784
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5785
0
            return -1;
5786
0
        } else {
5787
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5788
0
        }
5789
0
    }
5790
5791
    // Report final metrics after all concurrent tasks completed
5792
11
    segment_metrics_context_.report();
5793
11
    metrics_context.report();
5794
5795
11
    return ret;
5796
11
}
5797
5798
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
5799
1.61k
    constexpr int MAX_RETRY = 10;
5800
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
5801
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5802
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5803
1.61k
    std::string_view reference_instance_id = instance_id_;
5804
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5805
8
        reference_instance_id = rowset_meta.reference_instance_id();
5806
8
    }
5807
5808
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5809
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5810
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
5811
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5812
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5813
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5814
1.61k
        std::unique_ptr<Transaction> txn;
5815
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5816
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5817
0
            LOG_WARNING("failed to create txn").tag("err", err);
5818
0
            return -1;
5819
0
        }
5820
5821
1.61k
        std::string rowset_ref_count_key =
5822
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5823
1.61k
        int64_t ref_count = 0;
5824
1.61k
        {
5825
1.61k
            std::string value;
5826
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5827
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5828
                // This is the old version rowset, we could recycle it directly.
5829
1.60k
                ref_count = 1;
5830
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5831
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5832
0
                return -1;
5833
9
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5834
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5835
0
                return -1;
5836
0
            }
5837
1.61k
        }
5838
5839
1.61k
        if (ref_count == 1) {
5840
            // It would not be added since it is recycling.
5841
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5842
1.60k
                LOG_WARNING("failed to delete rowset data");
5843
1.60k
                return -1;
5844
1.60k
            }
5845
5846
            // Reset the transaction to avoid timeout.
5847
10
            err = txn_kv_->create_txn(&txn);
5848
10
            if (err != TxnErrorCode::TXN_OK) {
5849
0
                LOG_WARNING("failed to create txn").tag("err", err);
5850
0
                return -1;
5851
0
            }
5852
10
            txn->remove(rowset_ref_count_key);
5853
10
            LOG_INFO("delete rowset data ref count key")
5854
10
                    .tag("txn_id", rowset_meta.txn_id())
5855
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5856
5857
10
            std::string dbm_start_key =
5858
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5859
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5860
10
                    {reference_instance_id, tablet_id, rowset_id,
5861
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5862
10
            txn->remove(dbm_start_key, dbm_end_key);
5863
10
            LOG_INFO("remove delete bitmap kv")
5864
10
                    .tag("begin", hex(dbm_start_key))
5865
10
                    .tag("end", hex(dbm_end_key));
5866
5867
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5868
10
                    {reference_instance_id, tablet_id, rowset_id});
5869
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5870
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5871
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5872
10
            LOG_INFO("remove versioned delete bitmap kv")
5873
10
                    .tag("begin", hex(versioned_dbm_start_key))
5874
10
                    .tag("end", hex(versioned_dbm_end_key));
5875
10
        } else {
5876
            // Decrease the rowset ref count.
5877
            //
5878
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5879
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5880
1
            txn->atomic_add(rowset_ref_count_key, -1);
5881
1
            LOG_INFO("decrease rowset data ref count")
5882
1
                    .tag("txn_id", rowset_meta.txn_id())
5883
1
                    .tag("ref_count", ref_count - 1)
5884
1
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5885
1
        }
5886
5887
11
        if (!task.versioned_rowset_key.empty()) {
5888
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
5889
0
                                                          task.versionstamp);
5890
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
5891
0
        }
5892
5893
11
        if (!task.non_versioned_rowset_key.empty()) {
5894
0
            txn->remove(task.non_versioned_rowset_key);
5895
0
            LOG_INFO("remove non versioned rowset key")
5896
0
                    .tag("key", hex(task.non_versioned_rowset_key));
5897
0
        }
5898
5899
        // empty when recycle ref rowsets for deleted instance
5900
13
        if (!task.recycle_rowset_key.empty()) {
5901
13
            txn->remove(task.recycle_rowset_key);
5902
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
5903
13
        }
5904
5905
11
        err = txn->commit();
5906
11
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5907
            // The rowset ref count key has been changed, we need to retry.
5908
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5909
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5910
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5911
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5912
0
            continue;
5913
11
        } else if (err != TxnErrorCode::TXN_OK) {
5914
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5915
0
            return -1;
5916
0
        }
5917
11
        LOG_INFO("recycle rowset meta and data success");
5918
11
        return 0;
5919
11
    }
5920
2
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5921
2
            .tag("tablet_id", tablet_id)
5922
2
            .tag("rowset_id", rowset_id)
5923
2
            .tag("retry", MAX_RETRY);
5924
2
    return -1;
5925
1.61k
}
5926
5927
35
int InstanceRecycler::recycle_tmp_rowsets() {
5928
35
    const std::string task_name = "recycle_tmp_rowsets";
5929
35
    int64_t num_scanned = 0;
5930
35
    int64_t num_expired = 0;
5931
35
    std::atomic_long num_recycled = 0;
5932
35
    size_t expired_rowset_size = 0;
5933
35
    size_t total_rowset_key_size = 0;
5934
35
    size_t total_rowset_value_size = 0;
5935
35
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5936
5937
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5938
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5939
35
    std::string tmp_rs_key0;
5940
35
    std::string tmp_rs_key1;
5941
35
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5942
35
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5943
5944
35
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5945
5946
35
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5947
35
    register_recycle_task(task_name, start_time);
5948
5949
35
    DORIS_CLOUD_DEFER {
5950
35
        unregister_recycle_task(task_name);
5951
35
        int64_t cost =
5952
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5953
35
        metrics_context.finish_report();
5954
35
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5955
35
                .tag("instance_id", instance_id_)
5956
35
                .tag("num_scanned", num_scanned)
5957
35
                .tag("num_expired", num_expired)
5958
35
                .tag("num_recycled", num_recycled)
5959
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5960
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5961
35
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5962
35
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5949
12
    DORIS_CLOUD_DEFER {
5950
12
        unregister_recycle_task(task_name);
5951
12
        int64_t cost =
5952
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5953
12
        metrics_context.finish_report();
5954
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5955
12
                .tag("instance_id", instance_id_)
5956
12
                .tag("num_scanned", num_scanned)
5957
12
                .tag("num_expired", num_expired)
5958
12
                .tag("num_recycled", num_recycled)
5959
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5960
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5961
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5962
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5949
23
    DORIS_CLOUD_DEFER {
5950
23
        unregister_recycle_task(task_name);
5951
23
        int64_t cost =
5952
23
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5953
23
        metrics_context.finish_report();
5954
23
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5955
23
                .tag("instance_id", instance_id_)
5956
23
                .tag("num_scanned", num_scanned)
5957
23
                .tag("num_expired", num_expired)
5958
23
                .tag("num_recycled", num_recycled)
5959
23
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5960
23
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5961
23
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5962
23
    };
5963
5964
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5965
5966
35
    std::vector<std::string> tmp_rowset_keys;
5967
35
    std::vector<std::string> tmp_rowset_ref_count_keys;
5968
35
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
5969
35
    std::vector<std::string> tmp_rowset_keys_to_abort;
5970
5971
    // rowset_id -> rowset_meta
5972
    // store tmp_rowset id and meta for statistics rs size when delete
5973
35
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5974
35
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5975
35
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5976
35
    worker_pool->start();
5977
5978
35
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5979
5980
35
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5981
35
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5982
35
                             &earlest_ts, &tmp_rowset_ref_count_keys,
5983
35
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
5984
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5985
53.0k
        ++num_scanned;
5986
53.0k
        total_rowset_key_size += k.size();
5987
53.0k
        total_rowset_value_size += v.size();
5988
53.0k
        doris::RowsetMetaCloudPB rowset;
5989
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5990
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5991
0
            return -1;
5992
0
        }
5993
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5994
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5995
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5996
0
                   << " txn_expiration=" << rowset.txn_expiration()
5997
0
                   << " rowset_creation_time=" << rowset.creation_time();
5998
53.0k
        int64_t current_time = ::time(nullptr);
5999
53.0k
        if (current_time < expiration) { // not expired
6000
0
            return 0;
6001
0
        }
6002
6003
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6004
16
            if (need_mark_rowset_as_recycled(rowset)) {
6005
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6006
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6007
9
                             "at next turn, instance_id="
6008
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6009
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6010
9
                return 0;
6011
9
            }
6012
16
        }
6013
6014
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6015
7
            if (make_deferred_abort_task(rowset).has_value()) {
6016
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6017
3
                             "instance_id="
6018
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6019
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6020
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6021
3
            }
6022
7
        }
6023
6024
53.0k
        ++num_expired;
6025
53.0k
        expired_rowset_size += v.size();
6026
53.0k
        if (!rowset.has_resource_id()) {
6027
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6028
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6029
0
                return -1;
6030
0
            }
6031
            // might be a delete pred rowset
6032
0
            tmp_rowset_keys.emplace_back(k);
6033
0
            return 0;
6034
0
        }
6035
        // TODO(plat1ko): check rowset not referenced
6036
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6037
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6038
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6039
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6040
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6041
53.0k
                  << " num_expired=" << num_expired
6042
53.0k
                  << " task_type=" << metrics_context.operation_type;
6043
6044
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6045
        // Remove the rowset ref count key directly since it has not been used.
6046
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6047
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6048
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6049
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6050
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6051
6052
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6053
53.0k
        return 0;
6054
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5984
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5985
16
        ++num_scanned;
5986
16
        total_rowset_key_size += k.size();
5987
16
        total_rowset_value_size += v.size();
5988
16
        doris::RowsetMetaCloudPB rowset;
5989
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5990
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5991
0
            return -1;
5992
0
        }
5993
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5994
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5995
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5996
0
                   << " txn_expiration=" << rowset.txn_expiration()
5997
0
                   << " rowset_creation_time=" << rowset.creation_time();
5998
16
        int64_t current_time = ::time(nullptr);
5999
16
        if (current_time < expiration) { // not expired
6000
0
            return 0;
6001
0
        }
6002
6003
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6004
16
            if (need_mark_rowset_as_recycled(rowset)) {
6005
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6006
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6007
9
                             "at next turn, instance_id="
6008
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6009
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6010
9
                return 0;
6011
9
            }
6012
16
        }
6013
6014
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6015
7
            if (make_deferred_abort_task(rowset).has_value()) {
6016
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6017
3
                             "instance_id="
6018
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6019
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6020
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6021
3
            }
6022
7
        }
6023
6024
7
        ++num_expired;
6025
7
        expired_rowset_size += v.size();
6026
7
        if (!rowset.has_resource_id()) {
6027
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6028
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6029
0
                return -1;
6030
0
            }
6031
            // might be a delete pred rowset
6032
0
            tmp_rowset_keys.emplace_back(k);
6033
0
            return 0;
6034
0
        }
6035
        // TODO(plat1ko): check rowset not referenced
6036
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6037
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6038
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6039
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6040
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6041
7
                  << " num_expired=" << num_expired
6042
7
                  << " task_type=" << metrics_context.operation_type;
6043
6044
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6045
        // Remove the rowset ref count key directly since it has not been used.
6046
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6047
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6048
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6049
7
                  << "key=" << hex(rowset_ref_count_key);
6050
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6051
6052
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6053
7
        return 0;
6054
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5984
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5985
53.0k
        ++num_scanned;
5986
53.0k
        total_rowset_key_size += k.size();
5987
53.0k
        total_rowset_value_size += v.size();
5988
53.0k
        doris::RowsetMetaCloudPB rowset;
5989
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5990
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5991
0
            return -1;
5992
0
        }
5993
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5994
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5995
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5996
0
                   << " txn_expiration=" << rowset.txn_expiration()
5997
0
                   << " rowset_creation_time=" << rowset.creation_time();
5998
53.0k
        int64_t current_time = ::time(nullptr);
5999
53.0k
        if (current_time < expiration) { // not expired
6000
0
            return 0;
6001
0
        }
6002
6003
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6004
0
            if (need_mark_rowset_as_recycled(rowset)) {
6005
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6006
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6007
0
                             "at next turn, instance_id="
6008
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6009
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6010
0
                return 0;
6011
0
            }
6012
0
        }
6013
6014
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6015
0
            if (make_deferred_abort_task(rowset).has_value()) {
6016
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6017
0
                             "instance_id="
6018
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6019
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6020
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6021
0
            }
6022
0
        }
6023
6024
53.0k
        ++num_expired;
6025
53.0k
        expired_rowset_size += v.size();
6026
53.0k
        if (!rowset.has_resource_id()) {
6027
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6028
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6029
0
                return -1;
6030
0
            }
6031
            // might be a delete pred rowset
6032
0
            tmp_rowset_keys.emplace_back(k);
6033
0
            return 0;
6034
0
        }
6035
        // TODO(plat1ko): check rowset not referenced
6036
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6037
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6038
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6039
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6040
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6041
53.0k
                  << " num_expired=" << num_expired
6042
53.0k
                  << " task_type=" << metrics_context.operation_type;
6043
6044
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6045
        // Remove the rowset ref count key directly since it has not been used.
6046
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6047
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6048
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6049
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6050
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6051
6052
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6053
53.0k
        return 0;
6054
53.0k
    };
6055
6056
    // TODO bacth delete
6057
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6058
51.0k
        std::string dbm_start_key =
6059
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6060
51.0k
        std::string dbm_end_key = dbm_start_key;
6061
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6062
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6063
51.0k
        if (ret != 0) {
6064
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6065
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6066
0
                         << ", rowset_id=" << rowset_id;
6067
0
        }
6068
51.0k
        return ret;
6069
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6057
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6058
7
        std::string dbm_start_key =
6059
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6060
7
        std::string dbm_end_key = dbm_start_key;
6061
7
        encode_int64(INT64_MAX, &dbm_end_key);
6062
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6063
7
        if (ret != 0) {
6064
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6065
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6066
0
                         << ", rowset_id=" << rowset_id;
6067
0
        }
6068
7
        return ret;
6069
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6057
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6058
51.0k
        std::string dbm_start_key =
6059
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6060
51.0k
        std::string dbm_end_key = dbm_start_key;
6061
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6062
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6063
51.0k
        if (ret != 0) {
6064
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6065
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6066
0
                         << ", rowset_id=" << rowset_id;
6067
0
        }
6068
51.0k
        return ret;
6069
51.0k
    };
6070
6071
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6072
51.0k
        auto delete_bitmap_start =
6073
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6074
51.0k
        auto delete_bitmap_end =
6075
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6076
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6077
51.0k
        if (ret != 0) {
6078
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6079
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6080
0
        }
6081
51.0k
        return ret;
6082
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6071
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6072
7
        auto delete_bitmap_start =
6073
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6074
7
        auto delete_bitmap_end =
6075
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6076
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6077
7
        if (ret != 0) {
6078
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6079
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6080
0
        }
6081
7
        return ret;
6082
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6071
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6072
51.0k
        auto delete_bitmap_start =
6073
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6074
51.0k
        auto delete_bitmap_end =
6075
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6076
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6077
51.0k
        if (ret != 0) {
6078
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6079
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6080
0
        }
6081
51.0k
        return ret;
6082
51.0k
    };
6083
6084
35
    auto loop_done = [&]() -> int {
6085
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6086
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6087
22
        std::vector<std::string> mark_keys_to_process;
6088
22
        std::vector<std::string> abort_keys_to_process;
6089
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6090
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6091
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6092
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6093
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6094
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6095
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6096
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6097
22
                             tmp_rowset_ref_count_keys_to_delete =
6098
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6099
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6100
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6101
22
            if (!mark_keys_to_process.empty() &&
6102
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6103
7
                                                                  mark_keys_to_process) != 0) {
6104
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6105
0
                             << instance_id_;
6106
0
                return;
6107
0
            }
6108
22
            if (!abort_keys_to_process.empty() &&
6109
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6110
3
                                                                      false) != 0) {
6111
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6112
0
                             << instance_id_;
6113
0
                return;
6114
0
            }
6115
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6116
22
                                   metrics_context) != 0) {
6117
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6118
2
                return;
6119
2
            }
6120
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6121
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6122
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6123
0
                                 << rs.ShortDebugString();
6124
0
                    return;
6125
0
                }
6126
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6127
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6128
0
                                 << rs.ShortDebugString();
6129
0
                    return;
6130
0
                }
6131
51.0k
            }
6132
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6133
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6134
0
                return;
6135
0
            }
6136
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6137
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6138
0
                return;
6139
0
            }
6140
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6141
20
            return;
6142
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6100
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6101
12
            if (!mark_keys_to_process.empty() &&
6102
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6103
7
                                                                  mark_keys_to_process) != 0) {
6104
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6105
0
                             << instance_id_;
6106
0
                return;
6107
0
            }
6108
12
            if (!abort_keys_to_process.empty() &&
6109
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6110
3
                                                                      false) != 0) {
6111
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6112
0
                             << instance_id_;
6113
0
                return;
6114
0
            }
6115
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6116
12
                                   metrics_context) != 0) {
6117
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6118
0
                return;
6119
0
            }
6120
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6121
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6122
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6123
0
                                 << rs.ShortDebugString();
6124
0
                    return;
6125
0
                }
6126
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6127
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6128
0
                                 << rs.ShortDebugString();
6129
0
                    return;
6130
0
                }
6131
7
            }
6132
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6133
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6134
0
                return;
6135
0
            }
6136
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6137
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6138
0
                return;
6139
0
            }
6140
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6141
12
            return;
6142
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6100
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6101
10
            if (!mark_keys_to_process.empty() &&
6102
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6103
0
                                                                  mark_keys_to_process) != 0) {
6104
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6105
0
                             << instance_id_;
6106
0
                return;
6107
0
            }
6108
10
            if (!abort_keys_to_process.empty() &&
6109
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6110
0
                                                                      false) != 0) {
6111
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6112
0
                             << instance_id_;
6113
0
                return;
6114
0
            }
6115
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6116
10
                                   metrics_context) != 0) {
6117
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6118
2
                return;
6119
2
            }
6120
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6121
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6122
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6123
0
                                 << rs.ShortDebugString();
6124
0
                    return;
6125
0
                }
6126
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6127
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6128
0
                                 << rs.ShortDebugString();
6129
0
                    return;
6130
0
                }
6131
51.0k
            }
6132
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6133
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6134
0
                return;
6135
0
            }
6136
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6137
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6138
0
                return;
6139
0
            }
6140
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6141
8
            return;
6142
8
        });
6143
22
        return 0;
6144
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6084
12
    auto loop_done = [&]() -> int {
6085
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6086
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6087
12
        std::vector<std::string> mark_keys_to_process;
6088
12
        std::vector<std::string> abort_keys_to_process;
6089
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6090
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6091
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6092
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6093
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6094
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6095
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6096
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6097
12
                             tmp_rowset_ref_count_keys_to_delete =
6098
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6099
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6100
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6101
12
            if (!mark_keys_to_process.empty() &&
6102
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6103
12
                                                                  mark_keys_to_process) != 0) {
6104
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6105
12
                             << instance_id_;
6106
12
                return;
6107
12
            }
6108
12
            if (!abort_keys_to_process.empty() &&
6109
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6110
12
                                                                      false) != 0) {
6111
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6112
12
                             << instance_id_;
6113
12
                return;
6114
12
            }
6115
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6116
12
                                   metrics_context) != 0) {
6117
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6118
12
                return;
6119
12
            }
6120
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6121
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6122
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6123
12
                                 << rs.ShortDebugString();
6124
12
                    return;
6125
12
                }
6126
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6127
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6128
12
                                 << rs.ShortDebugString();
6129
12
                    return;
6130
12
                }
6131
12
            }
6132
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6133
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6134
12
                return;
6135
12
            }
6136
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6137
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6138
12
                return;
6139
12
            }
6140
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6141
12
            return;
6142
12
        });
6143
12
        return 0;
6144
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6084
10
    auto loop_done = [&]() -> int {
6085
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6086
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6087
10
        std::vector<std::string> mark_keys_to_process;
6088
10
        std::vector<std::string> abort_keys_to_process;
6089
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6090
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6091
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6092
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6093
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6094
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6095
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6096
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6097
10
                             tmp_rowset_ref_count_keys_to_delete =
6098
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6099
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6100
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6101
10
            if (!mark_keys_to_process.empty() &&
6102
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6103
10
                                                                  mark_keys_to_process) != 0) {
6104
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6105
10
                             << instance_id_;
6106
10
                return;
6107
10
            }
6108
10
            if (!abort_keys_to_process.empty() &&
6109
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6110
10
                                                                      false) != 0) {
6111
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6112
10
                             << instance_id_;
6113
10
                return;
6114
10
            }
6115
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6116
10
                                   metrics_context) != 0) {
6117
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6118
10
                return;
6119
10
            }
6120
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6121
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6122
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6123
10
                                 << rs.ShortDebugString();
6124
10
                    return;
6125
10
                }
6126
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6127
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6128
10
                                 << rs.ShortDebugString();
6129
10
                    return;
6130
10
                }
6131
10
            }
6132
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6133
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6134
10
                return;
6135
10
            }
6136
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6137
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6138
10
                return;
6139
10
            }
6140
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6141
10
            return;
6142
10
        });
6143
10
        return 0;
6144
10
    };
6145
6146
35
    if (config::enable_recycler_stats_metrics) {
6147
0
        scan_and_statistics_tmp_rowsets();
6148
0
    }
6149
    // recycle_func and loop_done for scan and recycle
6150
35
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6151
35
                               std::move(loop_done));
6152
6153
35
    worker_pool->stop();
6154
6155
    // Report final metrics after all concurrent tasks completed
6156
35
    segment_metrics_context_.report();
6157
35
    metrics_context.report();
6158
6159
35
    return ret;
6160
35
}
6161
6162
int InstanceRecycler::scan_and_recycle(
6163
        std::string begin, std::string_view end,
6164
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6165
268
        std::function<int()> loop_done) {
6166
268
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6167
268
    int ret = 0;
6168
268
    int64_t cnt = 0;
6169
268
    int get_range_retried = 0;
6170
268
    std::string err;
6171
268
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6172
268
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6173
268
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6174
268
                  << " ret=" << ret << " err=" << err;
6175
268
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6171
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6172
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6173
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6174
31
                  << " ret=" << ret << " err=" << err;
6175
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6171
237
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6172
237
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6173
237
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6174
237
                  << " ret=" << ret << " err=" << err;
6175
237
    };
6176
6177
268
    std::unique_ptr<RangeGetIterator> it;
6178
421
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6179
296
        if (get_range_retried > 1000) {
6180
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6181
0
            ret = -3;
6182
0
            return ret;
6183
0
        }
6184
296
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6185
296
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6186
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6187
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6188
0
                         << " get_range_retried=" << get_range_retried;
6189
0
            ++get_range_retried;
6190
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6191
0
            continue; // try again
6192
0
        }
6193
296
        if (!it->has_next()) {
6194
143
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6195
143
            break; // scan finished
6196
143
        }
6197
97.5k
        while (it->has_next()) {
6198
97.4k
            ++cnt;
6199
            // recycle corresponding resources
6200
97.4k
            auto [k, v] = it->next();
6201
97.4k
            if (!it->has_next()) {
6202
153
                begin = k;
6203
153
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6204
153
            }
6205
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6206
97.4k
            if (recycle_func(k, v) != 0) {
6207
4.00k
                err = "recycle_func error";
6208
4.00k
                ret = -1;
6209
4.00k
            }
6210
97.4k
        }
6211
153
        begin.push_back('\x00'); // Update to next smallest key for iteration
6212
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6213
153
        if (loop_done && loop_done() != 0) {
6214
5
            err = "loop_done error";
6215
5
            ret = -1;
6216
5
        }
6217
153
    }
6218
268
    return ret;
6219
268
}
6220
6221
19
int InstanceRecycler::abort_timeout_txn() {
6222
19
    const std::string task_name = "abort_timeout_txn";
6223
19
    int64_t num_scanned = 0;
6224
19
    int64_t num_timeout = 0;
6225
19
    int64_t num_abort = 0;
6226
19
    int64_t num_advance = 0;
6227
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6228
6229
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6230
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6231
19
    std::string begin_txn_running_key;
6232
19
    std::string end_txn_running_key;
6233
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6234
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6235
6236
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6237
6238
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6239
19
    register_recycle_task(task_name, start_time);
6240
6241
19
    DORIS_CLOUD_DEFER {
6242
19
        unregister_recycle_task(task_name);
6243
19
        int64_t cost =
6244
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6245
19
        metrics_context.finish_report();
6246
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6247
19
                .tag("instance_id", instance_id_)
6248
19
                .tag("num_scanned", num_scanned)
6249
19
                .tag("num_timeout", num_timeout)
6250
19
                .tag("num_abort", num_abort)
6251
19
                .tag("num_advance", num_advance);
6252
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6241
3
    DORIS_CLOUD_DEFER {
6242
3
        unregister_recycle_task(task_name);
6243
3
        int64_t cost =
6244
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6245
3
        metrics_context.finish_report();
6246
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6247
3
                .tag("instance_id", instance_id_)
6248
3
                .tag("num_scanned", num_scanned)
6249
3
                .tag("num_timeout", num_timeout)
6250
3
                .tag("num_abort", num_abort)
6251
3
                .tag("num_advance", num_advance);
6252
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6241
16
    DORIS_CLOUD_DEFER {
6242
16
        unregister_recycle_task(task_name);
6243
16
        int64_t cost =
6244
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6245
16
        metrics_context.finish_report();
6246
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6247
16
                .tag("instance_id", instance_id_)
6248
16
                .tag("num_scanned", num_scanned)
6249
16
                .tag("num_timeout", num_timeout)
6250
16
                .tag("num_abort", num_abort)
6251
16
                .tag("num_advance", num_advance);
6252
16
    };
6253
6254
19
    int64_t current_time =
6255
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6256
6257
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6258
19
                                  &current_time, &metrics_context,
6259
19
                                  this](std::string_view k, std::string_view v) -> int {
6260
9
        ++num_scanned;
6261
6262
9
        std::unique_ptr<Transaction> txn;
6263
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6264
9
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6266
0
            return -1;
6267
0
        }
6268
9
        std::string_view k1 = k;
6269
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6270
9
        k1.remove_prefix(1); // Remove key space
6271
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6272
9
        if (decode_key(&k1, &out) != 0) {
6273
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6274
0
            return -1;
6275
0
        }
6276
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6277
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6278
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6279
        // Update txn_info
6280
9
        std::string txn_inf_key, txn_inf_val;
6281
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6282
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6283
9
        if (err != TxnErrorCode::TXN_OK) {
6284
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6285
0
            return -1;
6286
0
        }
6287
9
        TxnInfoPB txn_info;
6288
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6289
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6290
0
            return -1;
6291
0
        }
6292
6293
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6294
3
            txn.reset();
6295
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6296
3
            std::shared_ptr<TxnLazyCommitTask> task =
6297
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6298
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6299
3
            if (ret.first != MetaServiceCode::OK) {
6300
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6301
0
                             << "msg=" << ret.second;
6302
0
                return -1;
6303
0
            }
6304
3
            ++num_advance;
6305
3
            return 0;
6306
6
        } else {
6307
6
            TxnRunningPB txn_running_pb;
6308
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6309
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6310
0
                return -1;
6311
0
            }
6312
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6313
4
                return 0;
6314
4
            }
6315
2
            ++num_timeout;
6316
6317
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6318
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6319
2
            txn_info.set_finish_time(current_time);
6320
2
            txn_info.set_reason("timeout");
6321
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6322
2
            txn_inf_val.clear();
6323
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6324
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6325
0
                return -1;
6326
0
            }
6327
2
            txn->put(txn_inf_key, txn_inf_val);
6328
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6329
            // Put recycle txn key
6330
2
            std::string recyc_txn_key, recyc_txn_val;
6331
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6332
2
            RecycleTxnPB recycle_txn_pb;
6333
2
            recycle_txn_pb.set_creation_time(current_time);
6334
2
            recycle_txn_pb.set_label(txn_info.label());
6335
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6336
0
                LOG_WARNING("failed to serialize txn recycle info")
6337
0
                        .tag("key", hex(k))
6338
0
                        .tag("db_id", db_id)
6339
0
                        .tag("txn_id", txn_id);
6340
0
                return -1;
6341
0
            }
6342
2
            txn->put(recyc_txn_key, recyc_txn_val);
6343
            // Remove txn running key
6344
2
            txn->remove(k);
6345
2
            err = txn->commit();
6346
2
            if (err != TxnErrorCode::TXN_OK) {
6347
0
                LOG_WARNING("failed to commit txn err={}", err)
6348
0
                        .tag("key", hex(k))
6349
0
                        .tag("db_id", db_id)
6350
0
                        .tag("txn_id", txn_id);
6351
0
                return -1;
6352
0
            }
6353
2
            metrics_context.total_recycled_num = ++num_abort;
6354
2
            metrics_context.report();
6355
2
        }
6356
6357
2
        return 0;
6358
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6259
3
                                  this](std::string_view k, std::string_view v) -> int {
6260
3
        ++num_scanned;
6261
6262
3
        std::unique_ptr<Transaction> txn;
6263
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6264
3
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6266
0
            return -1;
6267
0
        }
6268
3
        std::string_view k1 = k;
6269
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6270
3
        k1.remove_prefix(1); // Remove key space
6271
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6272
3
        if (decode_key(&k1, &out) != 0) {
6273
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6274
0
            return -1;
6275
0
        }
6276
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6277
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6278
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6279
        // Update txn_info
6280
3
        std::string txn_inf_key, txn_inf_val;
6281
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6282
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6283
3
        if (err != TxnErrorCode::TXN_OK) {
6284
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6285
0
            return -1;
6286
0
        }
6287
3
        TxnInfoPB txn_info;
6288
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6289
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6290
0
            return -1;
6291
0
        }
6292
6293
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6294
3
            txn.reset();
6295
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6296
3
            std::shared_ptr<TxnLazyCommitTask> task =
6297
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6298
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6299
3
            if (ret.first != MetaServiceCode::OK) {
6300
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6301
0
                             << "msg=" << ret.second;
6302
0
                return -1;
6303
0
            }
6304
3
            ++num_advance;
6305
3
            return 0;
6306
3
        } else {
6307
0
            TxnRunningPB txn_running_pb;
6308
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6309
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6310
0
                return -1;
6311
0
            }
6312
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6313
0
                return 0;
6314
0
            }
6315
0
            ++num_timeout;
6316
6317
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6318
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6319
0
            txn_info.set_finish_time(current_time);
6320
0
            txn_info.set_reason("timeout");
6321
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6322
0
            txn_inf_val.clear();
6323
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6324
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6325
0
                return -1;
6326
0
            }
6327
0
            txn->put(txn_inf_key, txn_inf_val);
6328
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6329
            // Put recycle txn key
6330
0
            std::string recyc_txn_key, recyc_txn_val;
6331
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6332
0
            RecycleTxnPB recycle_txn_pb;
6333
0
            recycle_txn_pb.set_creation_time(current_time);
6334
0
            recycle_txn_pb.set_label(txn_info.label());
6335
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6336
0
                LOG_WARNING("failed to serialize txn recycle info")
6337
0
                        .tag("key", hex(k))
6338
0
                        .tag("db_id", db_id)
6339
0
                        .tag("txn_id", txn_id);
6340
0
                return -1;
6341
0
            }
6342
0
            txn->put(recyc_txn_key, recyc_txn_val);
6343
            // Remove txn running key
6344
0
            txn->remove(k);
6345
0
            err = txn->commit();
6346
0
            if (err != TxnErrorCode::TXN_OK) {
6347
0
                LOG_WARNING("failed to commit txn err={}", err)
6348
0
                        .tag("key", hex(k))
6349
0
                        .tag("db_id", db_id)
6350
0
                        .tag("txn_id", txn_id);
6351
0
                return -1;
6352
0
            }
6353
0
            metrics_context.total_recycled_num = ++num_abort;
6354
0
            metrics_context.report();
6355
0
        }
6356
6357
0
        return 0;
6358
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6259
6
                                  this](std::string_view k, std::string_view v) -> int {
6260
6
        ++num_scanned;
6261
6262
6
        std::unique_ptr<Transaction> txn;
6263
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6264
6
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6266
0
            return -1;
6267
0
        }
6268
6
        std::string_view k1 = k;
6269
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6270
6
        k1.remove_prefix(1); // Remove key space
6271
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6272
6
        if (decode_key(&k1, &out) != 0) {
6273
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6274
0
            return -1;
6275
0
        }
6276
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6277
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6278
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6279
        // Update txn_info
6280
6
        std::string txn_inf_key, txn_inf_val;
6281
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6282
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6283
6
        if (err != TxnErrorCode::TXN_OK) {
6284
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6285
0
            return -1;
6286
0
        }
6287
6
        TxnInfoPB txn_info;
6288
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6289
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6290
0
            return -1;
6291
0
        }
6292
6293
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6294
0
            txn.reset();
6295
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6296
0
            std::shared_ptr<TxnLazyCommitTask> task =
6297
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6298
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6299
0
            if (ret.first != MetaServiceCode::OK) {
6300
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6301
0
                             << "msg=" << ret.second;
6302
0
                return -1;
6303
0
            }
6304
0
            ++num_advance;
6305
0
            return 0;
6306
6
        } else {
6307
6
            TxnRunningPB txn_running_pb;
6308
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6309
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6310
0
                return -1;
6311
0
            }
6312
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6313
4
                return 0;
6314
4
            }
6315
2
            ++num_timeout;
6316
6317
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6318
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6319
2
            txn_info.set_finish_time(current_time);
6320
2
            txn_info.set_reason("timeout");
6321
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6322
2
            txn_inf_val.clear();
6323
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6324
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6325
0
                return -1;
6326
0
            }
6327
2
            txn->put(txn_inf_key, txn_inf_val);
6328
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6329
            // Put recycle txn key
6330
2
            std::string recyc_txn_key, recyc_txn_val;
6331
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6332
2
            RecycleTxnPB recycle_txn_pb;
6333
2
            recycle_txn_pb.set_creation_time(current_time);
6334
2
            recycle_txn_pb.set_label(txn_info.label());
6335
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6336
0
                LOG_WARNING("failed to serialize txn recycle info")
6337
0
                        .tag("key", hex(k))
6338
0
                        .tag("db_id", db_id)
6339
0
                        .tag("txn_id", txn_id);
6340
0
                return -1;
6341
0
            }
6342
2
            txn->put(recyc_txn_key, recyc_txn_val);
6343
            // Remove txn running key
6344
2
            txn->remove(k);
6345
2
            err = txn->commit();
6346
2
            if (err != TxnErrorCode::TXN_OK) {
6347
0
                LOG_WARNING("failed to commit txn err={}", err)
6348
0
                        .tag("key", hex(k))
6349
0
                        .tag("db_id", db_id)
6350
0
                        .tag("txn_id", txn_id);
6351
0
                return -1;
6352
0
            }
6353
2
            metrics_context.total_recycled_num = ++num_abort;
6354
2
            metrics_context.report();
6355
2
        }
6356
6357
2
        return 0;
6358
6
    };
6359
6360
19
    if (config::enable_recycler_stats_metrics) {
6361
0
        scan_and_statistics_abort_timeout_txn();
6362
0
    }
6363
    // recycle_func and loop_done for scan and recycle
6364
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6365
19
                            std::move(handle_txn_running_kv));
6366
19
}
6367
6368
19
int InstanceRecycler::recycle_expired_txn_label() {
6369
19
    const std::string task_name = "recycle_expired_txn_label";
6370
19
    int64_t num_scanned = 0;
6371
19
    int64_t num_expired = 0;
6372
19
    std::atomic_long num_recycled = 0;
6373
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6374
19
    int ret = 0;
6375
6376
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6377
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6378
19
    std::string begin_recycle_txn_key;
6379
19
    std::string end_recycle_txn_key;
6380
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6381
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6382
19
    std::vector<std::string> recycle_txn_info_keys;
6383
6384
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6385
6386
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6387
19
    register_recycle_task(task_name, start_time);
6388
19
    DORIS_CLOUD_DEFER {
6389
19
        unregister_recycle_task(task_name);
6390
19
        int64_t cost =
6391
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6392
19
        metrics_context.finish_report();
6393
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6394
19
                .tag("instance_id", instance_id_)
6395
19
                .tag("num_scanned", num_scanned)
6396
19
                .tag("num_expired", num_expired)
6397
19
                .tag("num_recycled", num_recycled);
6398
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6388
1
    DORIS_CLOUD_DEFER {
6389
1
        unregister_recycle_task(task_name);
6390
1
        int64_t cost =
6391
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6392
1
        metrics_context.finish_report();
6393
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6394
1
                .tag("instance_id", instance_id_)
6395
1
                .tag("num_scanned", num_scanned)
6396
1
                .tag("num_expired", num_expired)
6397
1
                .tag("num_recycled", num_recycled);
6398
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6388
18
    DORIS_CLOUD_DEFER {
6389
18
        unregister_recycle_task(task_name);
6390
18
        int64_t cost =
6391
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6392
18
        metrics_context.finish_report();
6393
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6394
18
                .tag("instance_id", instance_id_)
6395
18
                .tag("num_scanned", num_scanned)
6396
18
                .tag("num_expired", num_expired)
6397
18
                .tag("num_recycled", num_recycled);
6398
18
    };
6399
6400
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6401
6402
19
    SyncExecutor<int> concurrent_delete_executor(
6403
19
            _thread_pool_group.s3_producer_pool,
6404
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6405
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6405
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6405
23.0k
            [](const int& ret) { return ret != 0; });
6406
6407
19
    int64_t current_time_ms =
6408
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6409
6410
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6411
30.0k
        ++num_scanned;
6412
30.0k
        RecycleTxnPB recycle_txn_pb;
6413
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6414
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6415
0
            return -1;
6416
0
        }
6417
30.0k
        if ((config::force_immediate_recycle) ||
6418
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6419
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6420
30.0k
             current_time_ms)) {
6421
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6422
23.0k
            num_expired++;
6423
23.0k
            recycle_txn_info_keys.emplace_back(k);
6424
23.0k
        }
6425
30.0k
        return 0;
6426
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6410
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6411
1
        ++num_scanned;
6412
1
        RecycleTxnPB recycle_txn_pb;
6413
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6414
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6415
0
            return -1;
6416
0
        }
6417
1
        if ((config::force_immediate_recycle) ||
6418
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6419
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6420
1
             current_time_ms)) {
6421
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6422
1
            num_expired++;
6423
1
            recycle_txn_info_keys.emplace_back(k);
6424
1
        }
6425
1
        return 0;
6426
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6410
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6411
30.0k
        ++num_scanned;
6412
30.0k
        RecycleTxnPB recycle_txn_pb;
6413
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6414
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6415
0
            return -1;
6416
0
        }
6417
30.0k
        if ((config::force_immediate_recycle) ||
6418
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6419
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6420
30.0k
             current_time_ms)) {
6421
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6422
23.0k
            num_expired++;
6423
23.0k
            recycle_txn_info_keys.emplace_back(k);
6424
23.0k
        }
6425
30.0k
        return 0;
6426
30.0k
    };
6427
6428
    // int 0 for success, 1 for conflict, -1 for error
6429
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6430
23.0k
        std::string_view k1 = k;
6431
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6432
23.0k
        k1.remove_prefix(1); // Remove key space
6433
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6434
23.0k
        int ret = decode_key(&k1, &out);
6435
23.0k
        if (ret != 0) {
6436
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6437
0
            return -1;
6438
0
        }
6439
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6440
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6441
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6442
23.0k
        std::unique_ptr<Transaction> txn;
6443
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6444
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6445
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6446
0
            return -1;
6447
0
        }
6448
        // Remove txn index kv
6449
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6450
23.0k
        txn->remove(index_key);
6451
        // Remove txn info kv
6452
23.0k
        std::string info_key, info_val;
6453
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6454
23.0k
        err = txn->get(info_key, &info_val);
6455
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6456
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6457
0
            return -1;
6458
0
        }
6459
23.0k
        TxnInfoPB txn_info;
6460
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6461
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6462
0
            return -1;
6463
0
        }
6464
23.0k
        txn->remove(info_key);
6465
        // Remove sub txn index kvs
6466
23.0k
        std::vector<std::string> sub_txn_index_keys;
6467
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6468
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6469
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6470
22.9k
        }
6471
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6472
22.9k
            txn->remove(sub_txn_index_key);
6473
22.9k
        }
6474
        // Update txn label
6475
23.0k
        std::string label_key, label_val;
6476
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6477
23.0k
        err = txn->get(label_key, &label_val);
6478
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6479
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6480
0
                         << " err=" << err;
6481
0
            return -1;
6482
0
        }
6483
23.0k
        TxnLabelPB txn_label;
6484
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6485
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6486
0
            return -1;
6487
0
        }
6488
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6489
23.0k
        if (it != txn_label.txn_ids().end()) {
6490
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6491
23.0k
        }
6492
23.0k
        if (txn_label.txn_ids().empty()) {
6493
23.0k
            txn->remove(label_key);
6494
23.0k
            TEST_SYNC_POINT_CALLBACK(
6495
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6496
23.0k
        } else {
6497
73
            if (!txn_label.SerializeToString(&label_val)) {
6498
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6499
0
                return -1;
6500
0
            }
6501
73
            TEST_SYNC_POINT_CALLBACK(
6502
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6503
73
            txn->atomic_set_ver_value(label_key, label_val);
6504
73
            TEST_SYNC_POINT_CALLBACK(
6505
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6506
73
        }
6507
        // Remove recycle txn kv
6508
23.0k
        txn->remove(k);
6509
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6510
23.0k
        err = txn->commit();
6511
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6512
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6513
62
                TEST_SYNC_POINT_CALLBACK(
6514
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6515
                // log the txn_id and label
6516
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6517
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6518
62
                             << " txn_label=" << txn_info.label();
6519
62
                return 1;
6520
62
            }
6521
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6522
0
            return -1;
6523
62
        }
6524
23.0k
        ++num_recycled;
6525
6526
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6527
23.0k
        return 0;
6528
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6429
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6430
1
        std::string_view k1 = k;
6431
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6432
1
        k1.remove_prefix(1); // Remove key space
6433
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6434
1
        int ret = decode_key(&k1, &out);
6435
1
        if (ret != 0) {
6436
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6437
0
            return -1;
6438
0
        }
6439
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6440
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6441
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6442
1
        std::unique_ptr<Transaction> txn;
6443
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6444
1
        if (err != TxnErrorCode::TXN_OK) {
6445
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6446
0
            return -1;
6447
0
        }
6448
        // Remove txn index kv
6449
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6450
1
        txn->remove(index_key);
6451
        // Remove txn info kv
6452
1
        std::string info_key, info_val;
6453
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6454
1
        err = txn->get(info_key, &info_val);
6455
1
        if (err != TxnErrorCode::TXN_OK) {
6456
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6457
0
            return -1;
6458
0
        }
6459
1
        TxnInfoPB txn_info;
6460
1
        if (!txn_info.ParseFromString(info_val)) {
6461
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6462
0
            return -1;
6463
0
        }
6464
1
        txn->remove(info_key);
6465
        // Remove sub txn index kvs
6466
1
        std::vector<std::string> sub_txn_index_keys;
6467
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6468
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6469
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6470
0
        }
6471
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6472
0
            txn->remove(sub_txn_index_key);
6473
0
        }
6474
        // Update txn label
6475
1
        std::string label_key, label_val;
6476
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6477
1
        err = txn->get(label_key, &label_val);
6478
1
        if (err != TxnErrorCode::TXN_OK) {
6479
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6480
0
                         << " err=" << err;
6481
0
            return -1;
6482
0
        }
6483
1
        TxnLabelPB txn_label;
6484
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6485
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6486
0
            return -1;
6487
0
        }
6488
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6489
1
        if (it != txn_label.txn_ids().end()) {
6490
1
            txn_label.mutable_txn_ids()->erase(it);
6491
1
        }
6492
1
        if (txn_label.txn_ids().empty()) {
6493
1
            txn->remove(label_key);
6494
1
            TEST_SYNC_POINT_CALLBACK(
6495
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6496
1
        } else {
6497
0
            if (!txn_label.SerializeToString(&label_val)) {
6498
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6499
0
                return -1;
6500
0
            }
6501
0
            TEST_SYNC_POINT_CALLBACK(
6502
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6503
0
            txn->atomic_set_ver_value(label_key, label_val);
6504
0
            TEST_SYNC_POINT_CALLBACK(
6505
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6506
0
        }
6507
        // Remove recycle txn kv
6508
1
        txn->remove(k);
6509
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6510
1
        err = txn->commit();
6511
1
        if (err != TxnErrorCode::TXN_OK) {
6512
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6513
0
                TEST_SYNC_POINT_CALLBACK(
6514
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6515
                // log the txn_id and label
6516
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6517
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6518
0
                             << " txn_label=" << txn_info.label();
6519
0
                return 1;
6520
0
            }
6521
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6522
0
            return -1;
6523
0
        }
6524
1
        ++num_recycled;
6525
6526
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6527
1
        return 0;
6528
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6429
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6430
23.0k
        std::string_view k1 = k;
6431
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6432
23.0k
        k1.remove_prefix(1); // Remove key space
6433
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6434
23.0k
        int ret = decode_key(&k1, &out);
6435
23.0k
        if (ret != 0) {
6436
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6437
0
            return -1;
6438
0
        }
6439
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6440
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6441
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6442
23.0k
        std::unique_ptr<Transaction> txn;
6443
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6444
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6445
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6446
0
            return -1;
6447
0
        }
6448
        // Remove txn index kv
6449
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6450
23.0k
        txn->remove(index_key);
6451
        // Remove txn info kv
6452
23.0k
        std::string info_key, info_val;
6453
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6454
23.0k
        err = txn->get(info_key, &info_val);
6455
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6456
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6457
0
            return -1;
6458
0
        }
6459
23.0k
        TxnInfoPB txn_info;
6460
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6461
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6462
0
            return -1;
6463
0
        }
6464
23.0k
        txn->remove(info_key);
6465
        // Remove sub txn index kvs
6466
23.0k
        std::vector<std::string> sub_txn_index_keys;
6467
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6468
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6469
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6470
22.9k
        }
6471
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6472
22.9k
            txn->remove(sub_txn_index_key);
6473
22.9k
        }
6474
        // Update txn label
6475
23.0k
        std::string label_key, label_val;
6476
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6477
23.0k
        err = txn->get(label_key, &label_val);
6478
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6479
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6480
0
                         << " err=" << err;
6481
0
            return -1;
6482
0
        }
6483
23.0k
        TxnLabelPB txn_label;
6484
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6485
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6486
0
            return -1;
6487
0
        }
6488
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6489
23.0k
        if (it != txn_label.txn_ids().end()) {
6490
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6491
23.0k
        }
6492
23.0k
        if (txn_label.txn_ids().empty()) {
6493
23.0k
            txn->remove(label_key);
6494
23.0k
            TEST_SYNC_POINT_CALLBACK(
6495
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6496
23.0k
        } else {
6497
73
            if (!txn_label.SerializeToString(&label_val)) {
6498
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6499
0
                return -1;
6500
0
            }
6501
73
            TEST_SYNC_POINT_CALLBACK(
6502
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6503
73
            txn->atomic_set_ver_value(label_key, label_val);
6504
73
            TEST_SYNC_POINT_CALLBACK(
6505
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6506
73
        }
6507
        // Remove recycle txn kv
6508
23.0k
        txn->remove(k);
6509
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6510
23.0k
        err = txn->commit();
6511
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6512
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6513
62
                TEST_SYNC_POINT_CALLBACK(
6514
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6515
                // log the txn_id and label
6516
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6517
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6518
62
                             << " txn_label=" << txn_info.label();
6519
62
                return 1;
6520
62
            }
6521
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6522
0
            return -1;
6523
62
        }
6524
23.0k
        ++num_recycled;
6525
6526
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6527
23.0k
        return 0;
6528
23.0k
    };
6529
6530
19
    auto loop_done = [&]() -> int {
6531
10
        DORIS_CLOUD_DEFER {
6532
10
            recycle_txn_info_keys.clear();
6533
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6531
1
        DORIS_CLOUD_DEFER {
6532
1
            recycle_txn_info_keys.clear();
6533
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6531
9
        DORIS_CLOUD_DEFER {
6532
9
            recycle_txn_info_keys.clear();
6533
9
        };
6534
10
        TEST_SYNC_POINT_CALLBACK(
6535
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6536
10
                &recycle_txn_info_keys);
6537
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6538
23.0k
            concurrent_delete_executor.add([&]() {
6539
23.0k
                int ret = delete_recycle_txn_kv(k);
6540
23.0k
                if (ret == 1) {
6541
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6542
54
                    for (int i = 1; i <= max_retry; ++i) {
6543
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6544
54
                        ret = delete_recycle_txn_kv(k);
6545
                        // clang-format off
6546
54
                        TEST_SYNC_POINT_CALLBACK(
6547
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6548
                        // clang-format off
6549
54
                        if (ret != 1) {
6550
18
                            break;
6551
18
                        }
6552
                        // random sleep 0-100 ms to retry
6553
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6554
36
                    }
6555
18
                }
6556
23.0k
                if (ret != 0) {
6557
9
                    LOG_WARNING("failed to delete recycle txn kv")
6558
9
                            .tag("instance id", instance_id_)
6559
9
                            .tag("key", hex(k));
6560
9
                    return -1;
6561
9
                }
6562
23.0k
                return 0;
6563
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6538
1
            concurrent_delete_executor.add([&]() {
6539
1
                int ret = delete_recycle_txn_kv(k);
6540
1
                if (ret == 1) {
6541
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6542
0
                    for (int i = 1; i <= max_retry; ++i) {
6543
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6544
0
                        ret = delete_recycle_txn_kv(k);
6545
                        // clang-format off
6546
0
                        TEST_SYNC_POINT_CALLBACK(
6547
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6548
                        // clang-format off
6549
0
                        if (ret != 1) {
6550
0
                            break;
6551
0
                        }
6552
                        // random sleep 0-100 ms to retry
6553
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6554
0
                    }
6555
0
                }
6556
1
                if (ret != 0) {
6557
0
                    LOG_WARNING("failed to delete recycle txn kv")
6558
0
                            .tag("instance id", instance_id_)
6559
0
                            .tag("key", hex(k));
6560
0
                    return -1;
6561
0
                }
6562
1
                return 0;
6563
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6538
23.0k
            concurrent_delete_executor.add([&]() {
6539
23.0k
                int ret = delete_recycle_txn_kv(k);
6540
23.0k
                if (ret == 1) {
6541
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6542
54
                    for (int i = 1; i <= max_retry; ++i) {
6543
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6544
54
                        ret = delete_recycle_txn_kv(k);
6545
                        // clang-format off
6546
54
                        TEST_SYNC_POINT_CALLBACK(
6547
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6548
                        // clang-format off
6549
54
                        if (ret != 1) {
6550
18
                            break;
6551
18
                        }
6552
                        // random sleep 0-100 ms to retry
6553
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6554
36
                    }
6555
18
                }
6556
23.0k
                if (ret != 0) {
6557
9
                    LOG_WARNING("failed to delete recycle txn kv")
6558
9
                            .tag("instance id", instance_id_)
6559
9
                            .tag("key", hex(k));
6560
9
                    return -1;
6561
9
                }
6562
23.0k
                return 0;
6563
23.0k
            });
6564
23.0k
        }
6565
10
        bool finished = true;
6566
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6567
23.0k
        for (int r : rets) {
6568
23.0k
            if (r != 0) {
6569
9
                ret = -1;
6570
9
            }
6571
23.0k
        }
6572
6573
10
        ret = finished ? ret : -1;
6574
6575
        // Update metrics after all concurrent tasks completed
6576
10
        metrics_context.total_recycled_num = num_recycled.load();
6577
10
        metrics_context.report();
6578
6579
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6580
6581
10
        if (ret != 0) {
6582
3
            LOG_WARNING("recycle txn kv ret!=0")
6583
3
                    .tag("finished", finished)
6584
3
                    .tag("ret", ret)
6585
3
                    .tag("instance_id", instance_id_);
6586
3
            return ret;
6587
3
        }
6588
7
        return ret;
6589
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6530
1
    auto loop_done = [&]() -> int {
6531
1
        DORIS_CLOUD_DEFER {
6532
1
            recycle_txn_info_keys.clear();
6533
1
        };
6534
1
        TEST_SYNC_POINT_CALLBACK(
6535
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6536
1
                &recycle_txn_info_keys);
6537
1
        for (const auto& k : recycle_txn_info_keys) {
6538
1
            concurrent_delete_executor.add([&]() {
6539
1
                int ret = delete_recycle_txn_kv(k);
6540
1
                if (ret == 1) {
6541
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6542
1
                    for (int i = 1; i <= max_retry; ++i) {
6543
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6544
1
                        ret = delete_recycle_txn_kv(k);
6545
                        // clang-format off
6546
1
                        TEST_SYNC_POINT_CALLBACK(
6547
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6548
                        // clang-format off
6549
1
                        if (ret != 1) {
6550
1
                            break;
6551
1
                        }
6552
                        // random sleep 0-100 ms to retry
6553
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6554
1
                    }
6555
1
                }
6556
1
                if (ret != 0) {
6557
1
                    LOG_WARNING("failed to delete recycle txn kv")
6558
1
                            .tag("instance id", instance_id_)
6559
1
                            .tag("key", hex(k));
6560
1
                    return -1;
6561
1
                }
6562
1
                return 0;
6563
1
            });
6564
1
        }
6565
1
        bool finished = true;
6566
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6567
1
        for (int r : rets) {
6568
1
            if (r != 0) {
6569
0
                ret = -1;
6570
0
            }
6571
1
        }
6572
6573
1
        ret = finished ? ret : -1;
6574
6575
        // Update metrics after all concurrent tasks completed
6576
1
        metrics_context.total_recycled_num = num_recycled.load();
6577
1
        metrics_context.report();
6578
6579
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6580
6581
1
        if (ret != 0) {
6582
0
            LOG_WARNING("recycle txn kv ret!=0")
6583
0
                    .tag("finished", finished)
6584
0
                    .tag("ret", ret)
6585
0
                    .tag("instance_id", instance_id_);
6586
0
            return ret;
6587
0
        }
6588
1
        return ret;
6589
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6530
9
    auto loop_done = [&]() -> int {
6531
9
        DORIS_CLOUD_DEFER {
6532
9
            recycle_txn_info_keys.clear();
6533
9
        };
6534
9
        TEST_SYNC_POINT_CALLBACK(
6535
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6536
9
                &recycle_txn_info_keys);
6537
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6538
23.0k
            concurrent_delete_executor.add([&]() {
6539
23.0k
                int ret = delete_recycle_txn_kv(k);
6540
23.0k
                if (ret == 1) {
6541
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6542
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6543
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6544
23.0k
                        ret = delete_recycle_txn_kv(k);
6545
                        // clang-format off
6546
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6547
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6548
                        // clang-format off
6549
23.0k
                        if (ret != 1) {
6550
23.0k
                            break;
6551
23.0k
                        }
6552
                        // random sleep 0-100 ms to retry
6553
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6554
23.0k
                    }
6555
23.0k
                }
6556
23.0k
                if (ret != 0) {
6557
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6558
23.0k
                            .tag("instance id", instance_id_)
6559
23.0k
                            .tag("key", hex(k));
6560
23.0k
                    return -1;
6561
23.0k
                }
6562
23.0k
                return 0;
6563
23.0k
            });
6564
23.0k
        }
6565
9
        bool finished = true;
6566
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6567
23.0k
        for (int r : rets) {
6568
23.0k
            if (r != 0) {
6569
9
                ret = -1;
6570
9
            }
6571
23.0k
        }
6572
6573
9
        ret = finished ? ret : -1;
6574
6575
        // Update metrics after all concurrent tasks completed
6576
9
        metrics_context.total_recycled_num = num_recycled.load();
6577
9
        metrics_context.report();
6578
6579
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6580
6581
9
        if (ret != 0) {
6582
3
            LOG_WARNING("recycle txn kv ret!=0")
6583
3
                    .tag("finished", finished)
6584
3
                    .tag("ret", ret)
6585
3
                    .tag("instance_id", instance_id_);
6586
3
            return ret;
6587
3
        }
6588
6
        return ret;
6589
9
    };
6590
6591
19
    if (config::enable_recycler_stats_metrics) {
6592
0
        scan_and_statistics_expired_txn_label();
6593
0
    }
6594
    // recycle_func and loop_done for scan and recycle
6595
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6596
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6597
19
}
6598
6599
struct CopyJobIdTuple {
6600
    std::string instance_id;
6601
    std::string stage_id;
6602
    long table_id;
6603
    std::string copy_id;
6604
    std::string stage_path;
6605
};
6606
struct BatchObjStoreAccessor {
6607
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6608
                          TxnKv* txn_kv)
6609
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6610
3
    ~BatchObjStoreAccessor() {
6611
3
        if (!paths_.empty()) {
6612
3
            consume();
6613
3
        }
6614
3
    }
6615
6616
    /**
6617
    * To implicitely do batch work and submit the batch delete task to s3
6618
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6619
    *
6620
    * @param copy_job The protubuf struct consists of the copy job files.
6621
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6622
    *            it would last until we finish the delete task, here we need pass one string value
6623
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6624
    */
6625
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6626
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6627
5
        auto& file_keys = copy_file_keys_[key];
6628
5
        file_keys.log_trace =
6629
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6630
5
                            instance_id, stage_id, table_id, copy_id, path);
6631
5
        std::string_view log_trace = file_keys.log_trace;
6632
2.03k
        for (const auto& file : copy_job.object_files()) {
6633
2.03k
            auto relative_path = file.relative_path();
6634
2.03k
            paths_.push_back(relative_path);
6635
2.03k
            file_keys.keys.push_back(copy_file_key(
6636
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6637
2.03k
            LOG_INFO(log_trace)
6638
2.03k
                    .tag("relative_path", relative_path)
6639
2.03k
                    .tag("batch_count", batch_count_);
6640
2.03k
        }
6641
5
        LOG_INFO(log_trace)
6642
5
                .tag("objects_num", copy_job.object_files().size())
6643
5
                .tag("batch_count", batch_count_);
6644
        // 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
6645
        // recommend using delete objects when objects num is less than 10)
6646
5
        if (paths_.size() < 1000) {
6647
3
            return;
6648
3
        }
6649
2
        consume();
6650
2
    }
6651
6652
private:
6653
5
    void consume() {
6654
5
        DORIS_CLOUD_DEFER {
6655
5
            paths_.clear();
6656
5
            copy_file_keys_.clear();
6657
5
            batch_count_++;
6658
6659
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6660
5
                        batch_count_);
6661
5
        };
6662
6663
5
        StopWatch sw;
6664
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6665
5
        if (0 != accessor_->delete_files(paths_)) {
6666
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6667
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6668
2
            return;
6669
2
        }
6670
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6671
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6672
        // delete fdb's keys
6673
3
        for (auto& file_keys : copy_file_keys_) {
6674
3
            auto& [log_trace, keys] = file_keys.second;
6675
3
            std::unique_ptr<Transaction> txn;
6676
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6677
0
                LOG(WARNING) << "failed to create txn";
6678
0
                continue;
6679
0
            }
6680
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6681
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6682
            // limited, should not cause the txn commit failed.
6683
1.02k
            for (const auto& key : keys) {
6684
1.02k
                txn->remove(key);
6685
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6686
1.02k
            }
6687
3
            txn->remove(file_keys.first);
6688
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6689
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6690
0
                continue;
6691
0
            }
6692
3
        }
6693
3
    }
6694
    std::shared_ptr<StorageVaultAccessor> accessor_;
6695
    // the path of the s3 files to be deleted
6696
    std::vector<std::string> paths_;
6697
    struct CopyFiles {
6698
        std::string log_trace;
6699
        std::vector<std::string> keys;
6700
    };
6701
    // pair<std::string, std::vector<std::string>>
6702
    // first: instance_id_ stage_id table_id query_id
6703
    // second: keys to be deleted
6704
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6705
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6706
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6707
    // which can together uniquely identifies different tasks for tracing log
6708
    uint64_t& batch_count_;
6709
    TxnKv* txn_kv_;
6710
};
6711
6712
13
int InstanceRecycler::recycle_copy_jobs() {
6713
13
    int64_t num_scanned = 0;
6714
13
    int64_t num_finished = 0;
6715
13
    int64_t num_expired = 0;
6716
13
    int64_t num_recycled = 0;
6717
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6718
13
    uint64_t batch_count = 0;
6719
13
    const std::string task_name = "recycle_copy_jobs";
6720
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6721
6722
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6723
6724
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6725
13
    register_recycle_task(task_name, start_time);
6726
6727
13
    DORIS_CLOUD_DEFER {
6728
13
        unregister_recycle_task(task_name);
6729
13
        int64_t cost =
6730
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6731
13
        metrics_context.finish_report();
6732
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6733
13
                .tag("instance_id", instance_id_)
6734
13
                .tag("num_scanned", num_scanned)
6735
13
                .tag("num_finished", num_finished)
6736
13
                .tag("num_expired", num_expired)
6737
13
                .tag("num_recycled", num_recycled);
6738
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6727
13
    DORIS_CLOUD_DEFER {
6728
13
        unregister_recycle_task(task_name);
6729
13
        int64_t cost =
6730
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6731
13
        metrics_context.finish_report();
6732
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6733
13
                .tag("instance_id", instance_id_)
6734
13
                .tag("num_scanned", num_scanned)
6735
13
                .tag("num_finished", num_finished)
6736
13
                .tag("num_expired", num_expired)
6737
13
                .tag("num_recycled", num_recycled);
6738
13
    };
6739
6740
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6741
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6742
13
    std::string key0;
6743
13
    std::string key1;
6744
13
    copy_job_key(key_info0, &key0);
6745
13
    copy_job_key(key_info1, &key1);
6746
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6747
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6748
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6749
16
                         this](std::string_view k, std::string_view v) -> int {
6750
16
        ++num_scanned;
6751
16
        CopyJobPB copy_job;
6752
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6753
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6754
0
            return -1;
6755
0
        }
6756
6757
        // decode copy job key
6758
16
        auto k1 = k;
6759
16
        k1.remove_prefix(1);
6760
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6761
16
        decode_key(&k1, &out);
6762
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6763
        // -> CopyJobPB
6764
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6765
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6766
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6767
6768
16
        bool check_storage = true;
6769
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6770
12
            ++num_finished;
6771
6772
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6773
7
                auto it = stage_accessor_map.find(stage_id);
6774
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6775
7
                std::string_view path;
6776
7
                if (it != stage_accessor_map.end()) {
6777
2
                    accessor = it->second;
6778
5
                } else {
6779
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6780
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6781
5
                                                      &inner_accessor);
6782
5
                    if (ret < 0) { // error
6783
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6784
0
                        return -1;
6785
5
                    } else if (ret == 0) {
6786
3
                        path = inner_accessor->uri();
6787
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6788
3
                                inner_accessor, batch_count, txn_kv_.get());
6789
3
                        stage_accessor_map.emplace(stage_id, accessor);
6790
3
                    } else { // stage not found, skip check storage
6791
2
                        check_storage = false;
6792
2
                    }
6793
5
                }
6794
7
                if (check_storage) {
6795
                    // TODO delete objects with key and etag is not supported
6796
5
                    accessor->add(std::move(copy_job), std::string(k),
6797
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6798
5
                    return 0;
6799
5
                }
6800
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6801
5
                int64_t current_time =
6802
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6803
5
                if (copy_job.finish_time_ms() > 0) {
6804
2
                    if (!config::force_immediate_recycle &&
6805
2
                        current_time < copy_job.finish_time_ms() +
6806
2
                                               config::copy_job_max_retention_second * 1000) {
6807
1
                        return 0;
6808
1
                    }
6809
3
                } else {
6810
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6811
3
                    if (!config::force_immediate_recycle &&
6812
3
                        current_time < copy_job.start_time_ms() +
6813
3
                                               config::copy_job_max_retention_second * 1000) {
6814
1
                        return 0;
6815
1
                    }
6816
3
                }
6817
5
            }
6818
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6819
4
            int64_t current_time =
6820
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6821
            // if copy job is timeout: delete all copy file kvs and copy job kv
6822
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6823
2
                return 0;
6824
2
            }
6825
2
            ++num_expired;
6826
2
        }
6827
6828
        // delete all copy files
6829
7
        std::vector<std::string> copy_file_keys;
6830
70
        for (auto& file : copy_job.object_files()) {
6831
70
            copy_file_keys.push_back(copy_file_key(
6832
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6833
70
        }
6834
7
        std::unique_ptr<Transaction> txn;
6835
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6836
0
            LOG(WARNING) << "failed to create txn";
6837
0
            return -1;
6838
0
        }
6839
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6840
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6841
        // limited, should not cause the txn commit failed.
6842
70
        for (const auto& key : copy_file_keys) {
6843
70
            txn->remove(key);
6844
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6845
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6846
70
                      << ", query_id=" << copy_id;
6847
70
        }
6848
7
        txn->remove(k);
6849
7
        TxnErrorCode err = txn->commit();
6850
7
        if (err != TxnErrorCode::TXN_OK) {
6851
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6852
0
            return -1;
6853
0
        }
6854
6855
7
        metrics_context.total_recycled_num = ++num_recycled;
6856
7
        metrics_context.report();
6857
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6858
7
        return 0;
6859
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
6749
16
                         this](std::string_view k, std::string_view v) -> int {
6750
16
        ++num_scanned;
6751
16
        CopyJobPB copy_job;
6752
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6753
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6754
0
            return -1;
6755
0
        }
6756
6757
        // decode copy job key
6758
16
        auto k1 = k;
6759
16
        k1.remove_prefix(1);
6760
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6761
16
        decode_key(&k1, &out);
6762
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6763
        // -> CopyJobPB
6764
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6765
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6766
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6767
6768
16
        bool check_storage = true;
6769
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6770
12
            ++num_finished;
6771
6772
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6773
7
                auto it = stage_accessor_map.find(stage_id);
6774
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6775
7
                std::string_view path;
6776
7
                if (it != stage_accessor_map.end()) {
6777
2
                    accessor = it->second;
6778
5
                } else {
6779
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6780
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6781
5
                                                      &inner_accessor);
6782
5
                    if (ret < 0) { // error
6783
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6784
0
                        return -1;
6785
5
                    } else if (ret == 0) {
6786
3
                        path = inner_accessor->uri();
6787
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6788
3
                                inner_accessor, batch_count, txn_kv_.get());
6789
3
                        stage_accessor_map.emplace(stage_id, accessor);
6790
3
                    } else { // stage not found, skip check storage
6791
2
                        check_storage = false;
6792
2
                    }
6793
5
                }
6794
7
                if (check_storage) {
6795
                    // TODO delete objects with key and etag is not supported
6796
5
                    accessor->add(std::move(copy_job), std::string(k),
6797
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6798
5
                    return 0;
6799
5
                }
6800
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6801
5
                int64_t current_time =
6802
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6803
5
                if (copy_job.finish_time_ms() > 0) {
6804
2
                    if (!config::force_immediate_recycle &&
6805
2
                        current_time < copy_job.finish_time_ms() +
6806
2
                                               config::copy_job_max_retention_second * 1000) {
6807
1
                        return 0;
6808
1
                    }
6809
3
                } else {
6810
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6811
3
                    if (!config::force_immediate_recycle &&
6812
3
                        current_time < copy_job.start_time_ms() +
6813
3
                                               config::copy_job_max_retention_second * 1000) {
6814
1
                        return 0;
6815
1
                    }
6816
3
                }
6817
5
            }
6818
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6819
4
            int64_t current_time =
6820
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6821
            // if copy job is timeout: delete all copy file kvs and copy job kv
6822
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6823
2
                return 0;
6824
2
            }
6825
2
            ++num_expired;
6826
2
        }
6827
6828
        // delete all copy files
6829
7
        std::vector<std::string> copy_file_keys;
6830
70
        for (auto& file : copy_job.object_files()) {
6831
70
            copy_file_keys.push_back(copy_file_key(
6832
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6833
70
        }
6834
7
        std::unique_ptr<Transaction> txn;
6835
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6836
0
            LOG(WARNING) << "failed to create txn";
6837
0
            return -1;
6838
0
        }
6839
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6840
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6841
        // limited, should not cause the txn commit failed.
6842
70
        for (const auto& key : copy_file_keys) {
6843
70
            txn->remove(key);
6844
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6845
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6846
70
                      << ", query_id=" << copy_id;
6847
70
        }
6848
7
        txn->remove(k);
6849
7
        TxnErrorCode err = txn->commit();
6850
7
        if (err != TxnErrorCode::TXN_OK) {
6851
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6852
0
            return -1;
6853
0
        }
6854
6855
7
        metrics_context.total_recycled_num = ++num_recycled;
6856
7
        metrics_context.report();
6857
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6858
7
        return 0;
6859
7
    };
6860
6861
13
    if (config::enable_recycler_stats_metrics) {
6862
0
        scan_and_statistics_copy_jobs();
6863
0
    }
6864
    // recycle_func and loop_done for scan and recycle
6865
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6866
13
}
6867
6868
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6869
                                             const StagePB::StageType& stage_type,
6870
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6871
5
#ifdef UNIT_TEST
6872
    // In unit test, external use the same accessor as the internal stage
6873
5
    auto it = accessor_map_.find(stage_id);
6874
5
    if (it != accessor_map_.end()) {
6875
3
        *accessor = it->second;
6876
3
    } else {
6877
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6878
2
        return 1;
6879
2
    }
6880
#else
6881
    // init s3 accessor and add to accessor map
6882
    auto stage_it =
6883
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6884
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6885
6886
    if (stage_it == instance_info_.stages().end()) {
6887
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6888
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6889
        return 1;
6890
    }
6891
6892
    const auto& object_store_info = stage_it->obj_info();
6893
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6894
6895
    S3Conf s3_conf;
6896
    if (stage_type == StagePB::EXTERNAL) {
6897
        if (stage_access_type == StagePB::AKSK) {
6898
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6899
            if (!conf) {
6900
                return -1;
6901
            }
6902
6903
            s3_conf = std::move(*conf);
6904
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6905
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6906
            if (!conf) {
6907
                return -1;
6908
            }
6909
6910
            s3_conf = std::move(*conf);
6911
            if (instance_info_.ram_user().has_encryption_info()) {
6912
                AkSkPair plain_ak_sk_pair;
6913
                int ret = decrypt_ak_sk_helper(
6914
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6915
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6916
                if (ret != 0) {
6917
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6918
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6919
                    return -1;
6920
                }
6921
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6922
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6923
            } else {
6924
                s3_conf.ak = instance_info_.ram_user().ak();
6925
                s3_conf.sk = instance_info_.ram_user().sk();
6926
            }
6927
        } else {
6928
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6929
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6930
            return -1;
6931
        }
6932
    } else if (stage_type == StagePB::INTERNAL) {
6933
        int idx = stoi(object_store_info.id());
6934
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6935
            LOG(WARNING) << "invalid idx: " << idx;
6936
            return -1;
6937
        }
6938
6939
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6940
        auto conf = S3Conf::from_obj_store_info(old_obj);
6941
        if (!conf) {
6942
            return -1;
6943
        }
6944
6945
        s3_conf = std::move(*conf);
6946
        s3_conf.prefix = object_store_info.prefix();
6947
    } else {
6948
        LOG(WARNING) << "unknown stage type " << stage_type;
6949
        return -1;
6950
    }
6951
6952
    std::shared_ptr<S3Accessor> s3_accessor;
6953
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6954
    if (ret != 0) {
6955
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6956
        return -1;
6957
    }
6958
6959
    *accessor = std::move(s3_accessor);
6960
#endif
6961
3
    return 0;
6962
5
}
6963
6964
11
int InstanceRecycler::recycle_stage() {
6965
11
    int64_t num_scanned = 0;
6966
11
    int64_t num_recycled = 0;
6967
11
    const std::string task_name = "recycle_stage";
6968
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6969
6970
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6971
6972
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6973
11
    register_recycle_task(task_name, start_time);
6974
6975
11
    DORIS_CLOUD_DEFER {
6976
11
        unregister_recycle_task(task_name);
6977
11
        int64_t cost =
6978
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6979
11
        metrics_context.finish_report();
6980
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6981
11
                .tag("instance_id", instance_id_)
6982
11
                .tag("num_scanned", num_scanned)
6983
11
                .tag("num_recycled", num_recycled);
6984
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6975
11
    DORIS_CLOUD_DEFER {
6976
11
        unregister_recycle_task(task_name);
6977
11
        int64_t cost =
6978
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6979
11
        metrics_context.finish_report();
6980
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6981
11
                .tag("instance_id", instance_id_)
6982
11
                .tag("num_scanned", num_scanned)
6983
11
                .tag("num_recycled", num_recycled);
6984
11
    };
6985
6986
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6987
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6988
11
    std::string key0 = recycle_stage_key(key_info0);
6989
11
    std::string key1 = recycle_stage_key(key_info1);
6990
6991
11
    std::vector<std::string_view> stage_keys;
6992
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6993
11
                         this](std::string_view k, std::string_view v) -> int {
6994
1
        ++num_scanned;
6995
1
        RecycleStagePB recycle_stage;
6996
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6997
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6998
0
            return -1;
6999
0
        }
7000
7001
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7002
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7003
0
            LOG(WARNING) << "invalid idx: " << idx;
7004
0
            return -1;
7005
0
        }
7006
7007
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7008
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7009
1
                [&] {
7010
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7011
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7012
1
                    if (!s3_conf) {
7013
1
                        return -1;
7014
1
                    }
7015
7016
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7017
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7018
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7019
1
                    if (ret != 0) {
7020
1
                        return -1;
7021
1
                    }
7022
7023
1
                    accessor = std::move(s3_accessor);
7024
1
                    return 0;
7025
1
                }(),
7026
1
                "recycle_stage:get_accessor", &accessor);
7027
7028
1
        if (ret != 0) {
7029
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7030
0
            return ret;
7031
0
        }
7032
7033
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7034
1
                .tag("instance_id", instance_id_)
7035
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7036
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7037
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7038
1
                .tag("obj_info_id", idx)
7039
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7040
1
        ret = accessor->delete_all();
7041
1
        if (ret != 0) {
7042
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7043
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7044
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7045
0
                         << ", ret=" << ret;
7046
0
            return -1;
7047
0
        }
7048
1
        metrics_context.total_recycled_num = ++num_recycled;
7049
1
        metrics_context.report();
7050
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7051
1
        stage_keys.push_back(k);
7052
1
        return 0;
7053
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6993
1
                         this](std::string_view k, std::string_view v) -> int {
6994
1
        ++num_scanned;
6995
1
        RecycleStagePB recycle_stage;
6996
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6997
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6998
0
            return -1;
6999
0
        }
7000
7001
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7002
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7003
0
            LOG(WARNING) << "invalid idx: " << idx;
7004
0
            return -1;
7005
0
        }
7006
7007
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7008
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7009
1
                [&] {
7010
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7011
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7012
1
                    if (!s3_conf) {
7013
1
                        return -1;
7014
1
                    }
7015
7016
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7017
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7018
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7019
1
                    if (ret != 0) {
7020
1
                        return -1;
7021
1
                    }
7022
7023
1
                    accessor = std::move(s3_accessor);
7024
1
                    return 0;
7025
1
                }(),
7026
1
                "recycle_stage:get_accessor", &accessor);
7027
7028
1
        if (ret != 0) {
7029
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7030
0
            return ret;
7031
0
        }
7032
7033
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7034
1
                .tag("instance_id", instance_id_)
7035
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7036
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7037
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7038
1
                .tag("obj_info_id", idx)
7039
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7040
1
        ret = accessor->delete_all();
7041
1
        if (ret != 0) {
7042
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7043
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7044
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7045
0
                         << ", ret=" << ret;
7046
0
            return -1;
7047
0
        }
7048
1
        metrics_context.total_recycled_num = ++num_recycled;
7049
1
        metrics_context.report();
7050
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7051
1
        stage_keys.push_back(k);
7052
1
        return 0;
7053
1
    };
7054
7055
11
    auto loop_done = [&stage_keys, this]() -> int {
7056
1
        if (stage_keys.empty()) return 0;
7057
1
        DORIS_CLOUD_DEFER {
7058
1
            stage_keys.clear();
7059
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7057
1
        DORIS_CLOUD_DEFER {
7058
1
            stage_keys.clear();
7059
1
        };
7060
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7061
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7062
0
            return -1;
7063
0
        }
7064
1
        return 0;
7065
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7055
1
    auto loop_done = [&stage_keys, this]() -> int {
7056
1
        if (stage_keys.empty()) return 0;
7057
1
        DORIS_CLOUD_DEFER {
7058
1
            stage_keys.clear();
7059
1
        };
7060
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7061
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7062
0
            return -1;
7063
0
        }
7064
1
        return 0;
7065
1
    };
7066
11
    if (config::enable_recycler_stats_metrics) {
7067
0
        scan_and_statistics_stage();
7068
0
    }
7069
    // recycle_func and loop_done for scan and recycle
7070
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7071
11
}
7072
7073
10
int InstanceRecycler::recycle_expired_stage_objects() {
7074
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7075
7076
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7077
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7078
7079
10
    DORIS_CLOUD_DEFER {
7080
10
        int64_t cost =
7081
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7082
10
        metrics_context.finish_report();
7083
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7084
10
                .tag("instance_id", instance_id_);
7085
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7079
10
    DORIS_CLOUD_DEFER {
7080
10
        int64_t cost =
7081
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7082
10
        metrics_context.finish_report();
7083
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7084
10
                .tag("instance_id", instance_id_);
7085
10
    };
7086
7087
10
    int ret = 0;
7088
7089
10
    if (config::enable_recycler_stats_metrics) {
7090
0
        scan_and_statistics_expired_stage_objects();
7091
0
    }
7092
7093
10
    for (const auto& stage : instance_info_.stages()) {
7094
0
        std::stringstream ss;
7095
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7096
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7097
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7098
0
           << ", prefix=" << stage.obj_info().prefix();
7099
7100
0
        if (stopped()) {
7101
0
            break;
7102
0
        }
7103
0
        if (stage.type() == StagePB::EXTERNAL) {
7104
0
            continue;
7105
0
        }
7106
0
        int idx = stoi(stage.obj_info().id());
7107
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7108
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7109
0
            continue;
7110
0
        }
7111
7112
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7113
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7114
0
        if (!s3_conf) {
7115
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7116
0
            continue;
7117
0
        }
7118
7119
0
        s3_conf->prefix = stage.obj_info().prefix();
7120
0
        std::shared_ptr<S3Accessor> accessor;
7121
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7122
0
        if (ret1 != 0) {
7123
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7124
0
            ret = -1;
7125
0
            continue;
7126
0
        }
7127
7128
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7129
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7130
0
            ret = -1;
7131
0
            continue;
7132
0
        }
7133
7134
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7135
0
        int64_t expiration_time =
7136
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7137
0
                config::internal_stage_objects_expire_time_second;
7138
0
        if (config::force_immediate_recycle) {
7139
0
            expiration_time = INT64_MAX;
7140
0
        }
7141
0
        ret1 = accessor->delete_all(expiration_time);
7142
0
        if (ret1 != 0) {
7143
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7144
0
                         << ss.str();
7145
0
            ret = -1;
7146
0
            continue;
7147
0
        }
7148
0
        metrics_context.total_recycled_num++;
7149
0
        metrics_context.report();
7150
0
    }
7151
10
    return ret;
7152
10
}
7153
7154
190
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7155
190
    std::lock_guard lock(recycle_tasks_mutex);
7156
190
    running_recycle_tasks[task_name] = start_time;
7157
190
}
7158
7159
190
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7160
190
    std::lock_guard lock(recycle_tasks_mutex);
7161
190
    DCHECK(running_recycle_tasks[task_name] > 0);
7162
190
    running_recycle_tasks.erase(task_name);
7163
190
}
7164
7165
21
bool InstanceRecycler::check_recycle_tasks() {
7166
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7167
21
    {
7168
21
        std::lock_guard lock(recycle_tasks_mutex);
7169
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7170
21
    }
7171
7172
21
    bool found = false;
7173
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7174
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7175
20
        int64_t cost = now - start_time;
7176
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7177
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7178
20
                    .tag("instance_id", instance_id_)
7179
20
                    .tag("task", task_name);
7180
20
            found = true;
7181
20
        }
7182
20
    }
7183
7184
21
    return found;
7185
21
}
7186
7187
// Scan and statistics indexes that need to be recycled
7188
0
int InstanceRecycler::scan_and_statistics_indexes() {
7189
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7190
7191
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7192
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7193
0
    std::string index_key0;
7194
0
    std::string index_key1;
7195
0
    recycle_index_key(index_key_info0, &index_key0);
7196
0
    recycle_index_key(index_key_info1, &index_key1);
7197
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7198
7199
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7200
0
        RecycleIndexPB index_pb;
7201
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7202
0
            return 0;
7203
0
        }
7204
0
        int64_t current_time = ::time(nullptr);
7205
0
        if (current_time <
7206
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7207
0
            return 0;
7208
0
        }
7209
        // decode index_id
7210
0
        auto k1 = k;
7211
0
        k1.remove_prefix(1);
7212
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7213
0
        decode_key(&k1, &out);
7214
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7215
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7216
0
        std::unique_ptr<Transaction> txn;
7217
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7218
0
        if (err != TxnErrorCode::TXN_OK) {
7219
0
            return 0;
7220
0
        }
7221
0
        std::string val;
7222
0
        err = txn->get(k, &val);
7223
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7224
0
            return 0;
7225
0
        }
7226
0
        if (err != TxnErrorCode::TXN_OK) {
7227
0
            return 0;
7228
0
        }
7229
0
        index_pb.Clear();
7230
0
        if (!index_pb.ParseFromString(val)) {
7231
0
            return 0;
7232
0
        }
7233
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7234
0
            return 0;
7235
0
        }
7236
0
        metrics_context.total_need_recycle_num++;
7237
0
        return 0;
7238
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7239
7240
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7241
0
    metrics_context.report(true);
7242
0
    segment_metrics_context_.report(true);
7243
0
    tablet_metrics_context_.report(true);
7244
0
    return ret;
7245
0
}
7246
7247
// Scan and statistics partitions that need to be recycled
7248
0
int InstanceRecycler::scan_and_statistics_partitions() {
7249
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7250
7251
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7252
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7253
0
    std::string part_key0;
7254
0
    std::string part_key1;
7255
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7256
7257
0
    recycle_partition_key(part_key_info0, &part_key0);
7258
0
    recycle_partition_key(part_key_info1, &part_key1);
7259
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7260
0
        RecyclePartitionPB part_pb;
7261
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7262
0
            return 0;
7263
0
        }
7264
0
        int64_t current_time = ::time(nullptr);
7265
0
        if (current_time <
7266
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7267
0
            return 0;
7268
0
        }
7269
        // decode partition_id
7270
0
        auto k1 = k;
7271
0
        k1.remove_prefix(1);
7272
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7273
0
        decode_key(&k1, &out);
7274
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7275
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7276
        // Change state to RECYCLING
7277
0
        std::unique_ptr<Transaction> txn;
7278
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7279
0
        if (err != TxnErrorCode::TXN_OK) {
7280
0
            return 0;
7281
0
        }
7282
0
        std::string val;
7283
0
        err = txn->get(k, &val);
7284
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7285
0
            return 0;
7286
0
        }
7287
0
        if (err != TxnErrorCode::TXN_OK) {
7288
0
            return 0;
7289
0
        }
7290
0
        part_pb.Clear();
7291
0
        if (!part_pb.ParseFromString(val)) {
7292
0
            return 0;
7293
0
        }
7294
        // Partitions with PREPARED state MUST have no data
7295
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7296
0
        int ret = 0;
7297
0
        for (int64_t index_id : part_pb.index_id()) {
7298
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7299
0
                                            partition_id, is_empty_tablet) != 0) {
7300
0
                ret = 0;
7301
0
            }
7302
0
        }
7303
0
        metrics_context.total_need_recycle_num++;
7304
0
        return ret;
7305
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_
7306
7307
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7308
0
    metrics_context.report(true);
7309
0
    segment_metrics_context_.report(true);
7310
0
    tablet_metrics_context_.report(true);
7311
0
    return ret;
7312
0
}
7313
7314
// Scan and statistics rowsets that need to be recycled
7315
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7316
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7317
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7318
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7319
0
    std::string recyc_rs_key0;
7320
0
    std::string recyc_rs_key1;
7321
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7322
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7323
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7324
7325
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7326
0
        RecycleRowsetPB rowset;
7327
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7328
0
            return 0;
7329
0
        }
7330
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7331
0
        int64_t current_time = ::time(nullptr);
7332
0
        if (current_time <
7333
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7334
0
            return 0;
7335
0
        }
7336
7337
0
        if (!rowset.has_type()) {
7338
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7339
0
                return 0;
7340
0
            }
7341
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7342
0
                return 0;
7343
0
            }
7344
0
            metrics_context.total_need_recycle_num++;
7345
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7346
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7347
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7348
0
            return 0;
7349
0
        }
7350
7351
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7352
0
            return 0;
7353
0
        }
7354
7355
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7356
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7357
0
                return 0;
7358
0
            }
7359
0
        }
7360
0
        metrics_context.total_need_recycle_num++;
7361
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7362
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7363
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7364
0
        return 0;
7365
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_
7366
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7367
0
    metrics_context.report(true);
7368
0
    segment_metrics_context_.report(true);
7369
0
    return ret;
7370
0
}
7371
7372
// Scan and statistics tmp_rowsets that need to be recycled
7373
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7374
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7375
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7376
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7377
0
    std::string tmp_rs_key0;
7378
0
    std::string tmp_rs_key1;
7379
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7380
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7381
7382
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7383
7384
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7385
0
        doris::RowsetMetaCloudPB rowset;
7386
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7387
0
            return 0;
7388
0
        }
7389
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7390
0
        int64_t current_time = ::time(nullptr);
7391
0
        if (current_time < expiration) {
7392
0
            return 0;
7393
0
        }
7394
7395
0
        DCHECK_GT(rowset.txn_id(), 0)
7396
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7397
7398
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7399
0
            return 0;
7400
0
        }
7401
7402
0
        if (!rowset.has_resource_id()) {
7403
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7404
0
                return 0;
7405
0
            }
7406
0
            return 0;
7407
0
        }
7408
7409
0
        metrics_context.total_need_recycle_num++;
7410
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7411
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7412
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7413
0
        return 0;
7414
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_
7415
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7416
0
    metrics_context.report(true);
7417
0
    segment_metrics_context_.report(true);
7418
0
    return ret;
7419
0
}
7420
7421
// Scan and statistics abort_timeout_txn that need to be recycled
7422
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7423
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7424
7425
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7426
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7427
0
    std::string begin_txn_running_key;
7428
0
    std::string end_txn_running_key;
7429
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7430
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7431
7432
0
    int64_t current_time =
7433
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7434
7435
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7436
0
                                               std::string_view k, std::string_view v) -> int {
7437
0
        std::unique_ptr<Transaction> txn;
7438
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7439
0
        if (err != TxnErrorCode::TXN_OK) {
7440
0
            return 0;
7441
0
        }
7442
0
        std::string_view k1 = k;
7443
0
        k1.remove_prefix(1);
7444
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7445
0
        if (decode_key(&k1, &out) != 0) {
7446
0
            return 0;
7447
0
        }
7448
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7449
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7450
        // Update txn_info
7451
0
        std::string txn_inf_key, txn_inf_val;
7452
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7453
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7454
0
        if (err != TxnErrorCode::TXN_OK) {
7455
0
            return 0;
7456
0
        }
7457
0
        TxnInfoPB txn_info;
7458
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7459
0
            return 0;
7460
0
        }
7461
7462
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7463
0
            TxnRunningPB txn_running_pb;
7464
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7465
0
                return 0;
7466
0
            }
7467
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7468
0
                return 0;
7469
0
            }
7470
0
            metrics_context.total_need_recycle_num++;
7471
0
        }
7472
0
        return 0;
7473
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_
7474
7475
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7476
0
    metrics_context.report(true);
7477
0
    return ret;
7478
0
}
7479
7480
// Scan and statistics expired_txn_label that need to be recycled
7481
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7482
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7483
7484
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7485
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7486
0
    std::string begin_recycle_txn_key;
7487
0
    std::string end_recycle_txn_key;
7488
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7489
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7490
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7491
0
    int64_t current_time_ms =
7492
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7493
7494
    // for calculate the total num or bytes of recyled objects
7495
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7496
0
        RecycleTxnPB recycle_txn_pb;
7497
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7498
0
            return 0;
7499
0
        }
7500
0
        if ((config::force_immediate_recycle) ||
7501
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7502
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7503
0
             current_time_ms)) {
7504
0
            metrics_context.total_need_recycle_num++;
7505
0
        }
7506
0
        return 0;
7507
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_
7508
7509
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7510
0
    metrics_context.report(true);
7511
0
    return ret;
7512
0
}
7513
7514
// Scan and statistics copy_jobs that need to be recycled
7515
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7516
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7517
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7518
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7519
0
    std::string key0;
7520
0
    std::string key1;
7521
0
    copy_job_key(key_info0, &key0);
7522
0
    copy_job_key(key_info1, &key1);
7523
7524
    // for calculate the total num or bytes of recyled objects
7525
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7526
0
        CopyJobPB copy_job;
7527
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7528
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7529
0
            return 0;
7530
0
        }
7531
7532
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7533
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7534
0
                int64_t current_time =
7535
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7536
0
                if (copy_job.finish_time_ms() > 0) {
7537
0
                    if (!config::force_immediate_recycle &&
7538
0
                        current_time < copy_job.finish_time_ms() +
7539
0
                                               config::copy_job_max_retention_second * 1000) {
7540
0
                        return 0;
7541
0
                    }
7542
0
                } else {
7543
0
                    if (!config::force_immediate_recycle &&
7544
0
                        current_time < copy_job.start_time_ms() +
7545
0
                                               config::copy_job_max_retention_second * 1000) {
7546
0
                        return 0;
7547
0
                    }
7548
0
                }
7549
0
            }
7550
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7551
0
            int64_t current_time =
7552
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7553
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7554
0
                return 0;
7555
0
            }
7556
0
        }
7557
0
        metrics_context.total_need_recycle_num++;
7558
0
        return 0;
7559
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_
7560
7561
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7562
0
    metrics_context.report(true);
7563
0
    return ret;
7564
0
}
7565
7566
// Scan and statistics stage that need to be recycled
7567
0
int InstanceRecycler::scan_and_statistics_stage() {
7568
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7569
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7570
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7571
0
    std::string key0 = recycle_stage_key(key_info0);
7572
0
    std::string key1 = recycle_stage_key(key_info1);
7573
7574
    // for calculate the total num or bytes of recyled objects
7575
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7576
0
                                                        std::string_view v) -> int {
7577
0
        RecycleStagePB recycle_stage;
7578
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7579
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7580
0
            return 0;
7581
0
        }
7582
7583
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7584
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7585
0
            LOG(WARNING) << "invalid idx: " << idx;
7586
0
            return 0;
7587
0
        }
7588
7589
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7590
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7591
0
                [&] {
7592
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7593
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7594
0
                    if (!s3_conf) {
7595
0
                        return 0;
7596
0
                    }
7597
7598
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7599
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7600
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7601
0
                    if (ret != 0) {
7602
0
                        return 0;
7603
0
                    }
7604
7605
0
                    accessor = std::move(s3_accessor);
7606
0
                    return 0;
7607
0
                }(),
7608
0
                "recycle_stage:get_accessor", &accessor);
7609
7610
0
        if (ret != 0) {
7611
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7612
0
            return 0;
7613
0
        }
7614
7615
0
        metrics_context.total_need_recycle_num++;
7616
0
        return 0;
7617
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_
7618
7619
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7620
0
    metrics_context.report(true);
7621
0
    return ret;
7622
0
}
7623
7624
// Scan and statistics expired_stage_objects that need to be recycled
7625
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7626
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7627
7628
    // for calculate the total num or bytes of recyled objects
7629
0
    auto scan_and_statistics = [&metrics_context, this]() {
7630
0
        for (const auto& stage : instance_info_.stages()) {
7631
0
            if (stopped()) {
7632
0
                break;
7633
0
            }
7634
0
            if (stage.type() == StagePB::EXTERNAL) {
7635
0
                continue;
7636
0
            }
7637
0
            int idx = stoi(stage.obj_info().id());
7638
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7639
0
                continue;
7640
0
            }
7641
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7642
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7643
0
            if (!s3_conf) {
7644
0
                continue;
7645
0
            }
7646
0
            s3_conf->prefix = stage.obj_info().prefix();
7647
0
            std::shared_ptr<S3Accessor> accessor;
7648
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7649
0
            if (ret1 != 0) {
7650
0
                continue;
7651
0
            }
7652
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7653
0
                continue;
7654
0
            }
7655
0
            metrics_context.total_need_recycle_num++;
7656
0
        }
7657
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7658
7659
0
    scan_and_statistics();
7660
0
    metrics_context.report(true);
7661
0
    return 0;
7662
0
}
7663
7664
// Scan and statistics versions that need to be recycled
7665
0
int InstanceRecycler::scan_and_statistics_versions() {
7666
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7667
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7668
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7669
7670
0
    int64_t last_scanned_table_id = 0;
7671
0
    bool is_recycled = false; // Is last scanned kv recycled
7672
    // for calculate the total num or bytes of recyled objects
7673
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7674
0
                                       std::string_view k, std::string_view) {
7675
0
        auto k1 = k;
7676
0
        k1.remove_prefix(1);
7677
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7678
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7679
0
        decode_key(&k1, &out);
7680
0
        DCHECK_EQ(out.size(), 6) << k;
7681
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7682
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7683
0
            metrics_context.total_need_recycle_num +=
7684
0
                    is_recycled; // Version kv of this table has been recycled
7685
0
            return 0;
7686
0
        }
7687
0
        last_scanned_table_id = table_id;
7688
0
        is_recycled = false;
7689
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7690
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7691
0
        std::unique_ptr<Transaction> txn;
7692
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7693
0
        if (err != TxnErrorCode::TXN_OK) {
7694
0
            return 0;
7695
0
        }
7696
0
        std::unique_ptr<RangeGetIterator> iter;
7697
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7698
0
        if (err != TxnErrorCode::TXN_OK) {
7699
0
            return 0;
7700
0
        }
7701
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7702
0
            return 0;
7703
0
        }
7704
0
        metrics_context.total_need_recycle_num++;
7705
0
        is_recycled = true;
7706
0
        return 0;
7707
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_
7708
7709
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7710
0
    metrics_context.report(true);
7711
0
    return ret;
7712
0
}
7713
7714
// Scan and statistics restore jobs that need to be recycled
7715
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7716
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7717
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7718
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7719
0
    std::string restore_job_key0;
7720
0
    std::string restore_job_key1;
7721
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7722
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7723
7724
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7725
7726
    // for calculate the total num or bytes of recyled objects
7727
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7728
0
        RestoreJobCloudPB restore_job_pb;
7729
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7730
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7731
0
            return 0;
7732
0
        }
7733
0
        int64_t expiration =
7734
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7735
0
        int64_t current_time = ::time(nullptr);
7736
0
        if (current_time < expiration) { // not expired
7737
0
            return 0;
7738
0
        }
7739
0
        metrics_context.total_need_recycle_num++;
7740
0
        if(restore_job_pb.need_recycle_data()) {
7741
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7742
0
        }
7743
0
        return 0;
7744
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_
7745
7746
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7747
0
    metrics_context.report(true);
7748
0
    return ret;
7749
0
}
7750
7751
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7752
3
    if (!should_recycle_versioned_keys()) {
7753
0
        return;
7754
0
    }
7755
7756
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7757
7758
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7759
3
    if (recycle_checker.init() != 0) {
7760
0
        return;
7761
0
    }
7762
7763
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7764
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7765
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7766
7767
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7768
8
    for (; iter->valid(); iter->next()) {
7769
5
        OperationLogPB operation_log;
7770
5
        if (!iter->parse_value(&operation_log)) {
7771
0
            continue;
7772
0
        }
7773
7774
5
        std::string_view key = iter->key();
7775
5
        Versionstamp log_versionstamp;
7776
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7777
0
            continue;
7778
0
        }
7779
7780
5
        OperationLogReferenceInfo ref_info;
7781
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7782
5
                                         &ref_info)) {
7783
4
            metrics_context.total_need_recycle_num++;
7784
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7785
4
        }
7786
5
    }
7787
7788
3
    metrics_context.report(true);
7789
3
}
7790
7791
int InstanceRecycler::classify_rowset_task_by_ref_count(
7792
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7793
60
    constexpr int MAX_RETRY = 10;
7794
60
    const auto& rowset_meta = task.rowset_meta;
7795
60
    int64_t tablet_id = rowset_meta.tablet_id();
7796
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7797
60
    std::string_view reference_instance_id = instance_id_;
7798
60
    if (rowset_meta.has_reference_instance_id()) {
7799
5
        reference_instance_id = rowset_meta.reference_instance_id();
7800
5
    }
7801
7802
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7803
61
        std::unique_ptr<Transaction> txn;
7804
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7805
61
        if (err != TxnErrorCode::TXN_OK) {
7806
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7807
0
                    .tag("instance_id", instance_id_)
7808
0
                    .tag("tablet_id", tablet_id)
7809
0
                    .tag("rowset_id", rowset_id)
7810
0
                    .tag("err", err);
7811
0
            return -1;
7812
0
        }
7813
7814
61
        std::string rowset_ref_count_key =
7815
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7816
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7817
7818
61
        int64_t ref_count = 0;
7819
61
        {
7820
61
            std::string value;
7821
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7822
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7823
0
                ref_count = 1;
7824
61
            } else if (err != TxnErrorCode::TXN_OK) {
7825
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7826
0
                        .tag("instance_id", instance_id_)
7827
0
                        .tag("tablet_id", tablet_id)
7828
0
                        .tag("rowset_id", rowset_id)
7829
0
                        .tag("err", err);
7830
0
                return -1;
7831
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7832
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7833
0
                        .tag("instance_id", instance_id_)
7834
0
                        .tag("tablet_id", tablet_id)
7835
0
                        .tag("rowset_id", rowset_id)
7836
0
                        .tag("value", hex(value));
7837
0
                return -1;
7838
0
            }
7839
61
        }
7840
7841
61
        if (ref_count > 1) {
7842
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7843
12
            txn->atomic_add(rowset_ref_count_key, -1);
7844
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7845
12
                    .tag("instance_id", instance_id_)
7846
12
                    .tag("tablet_id", tablet_id)
7847
12
                    .tag("rowset_id", rowset_id)
7848
12
                    .tag("ref_count", ref_count - 1)
7849
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7850
7851
12
            if (!task.recycle_rowset_key.empty()) {
7852
0
                txn->remove(task.recycle_rowset_key);
7853
0
                LOG_INFO("remove recycle rowset key in classification phase")
7854
0
                        .tag("key", hex(task.recycle_rowset_key));
7855
0
            }
7856
12
            if (!task.non_versioned_rowset_key.empty()) {
7857
12
                txn->remove(task.non_versioned_rowset_key);
7858
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7859
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7860
12
            }
7861
7862
12
            err = txn->commit();
7863
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7864
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7865
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7866
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7867
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7868
1
                continue;
7869
11
            } else if (err != TxnErrorCode::TXN_OK) {
7870
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7871
0
                        .tag("instance_id", instance_id_)
7872
0
                        .tag("tablet_id", tablet_id)
7873
0
                        .tag("rowset_id", rowset_id)
7874
0
                        .tag("err", err);
7875
0
                return -1;
7876
0
            }
7877
11
            return 1; // handled, not added to batch delete
7878
49
        } else {
7879
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7880
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7881
49
            LOG_INFO("add rowset to batch delete plan")
7882
49
                    .tag("instance_id", instance_id_)
7883
49
                    .tag("tablet_id", tablet_id)
7884
49
                    .tag("rowset_id", rowset_id)
7885
49
                    .tag("resource_id", rowset_meta.resource_id())
7886
49
                    .tag("ref_count", ref_count);
7887
7888
49
            batch_delete_tasks.push_back(std::move(task));
7889
49
            return 0; // added to batch delete
7890
49
        }
7891
61
    }
7892
7893
0
    LOG_WARNING("failed to classify rowset task after retry")
7894
0
            .tag("instance_id", instance_id_)
7895
0
            .tag("tablet_id", tablet_id)
7896
0
            .tag("rowset_id", rowset_id)
7897
0
            .tag("retry", MAX_RETRY);
7898
0
    return -1;
7899
60
}
7900
7901
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7902
10
    int ret = 0;
7903
49
    for (const auto& task : tasks) {
7904
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7905
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7906
7907
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7908
        // so we don't need to call it again here.
7909
7910
        // Remove all metadata keys in one transaction
7911
49
        std::unique_ptr<Transaction> txn;
7912
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7913
49
        if (err != TxnErrorCode::TXN_OK) {
7914
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7915
0
                    .tag("instance_id", instance_id_)
7916
0
                    .tag("tablet_id", tablet_id)
7917
0
                    .tag("rowset_id", rowset_id)
7918
0
                    .tag("err", err);
7919
0
            ret = -1;
7920
0
            continue;
7921
0
        }
7922
7923
49
        std::string_view reference_instance_id = instance_id_;
7924
49
        if (task.rowset_meta.has_reference_instance_id()) {
7925
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
7926
0
        }
7927
7928
49
        txn->remove(task.rowset_ref_count_key);
7929
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7930
49
                .tag("instance_id", instance_id_)
7931
49
                .tag("tablet_id", tablet_id)
7932
49
                .tag("rowset_id", rowset_id)
7933
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7934
7935
49
        std::string dbm_start_key =
7936
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7937
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7938
49
                {reference_instance_id, tablet_id, rowset_id,
7939
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7940
49
        txn->remove(dbm_start_key, dbm_end_key);
7941
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7942
49
                .tag("instance_id", instance_id_)
7943
49
                .tag("tablet_id", tablet_id)
7944
49
                .tag("rowset_id", rowset_id)
7945
49
                .tag("begin", hex(dbm_start_key))
7946
49
                .tag("end", hex(dbm_end_key));
7947
7948
49
        std::string versioned_dbm_start_key =
7949
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7950
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7951
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7952
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7953
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7954
49
                .tag("instance_id", instance_id_)
7955
49
                .tag("tablet_id", tablet_id)
7956
49
                .tag("rowset_id", rowset_id)
7957
49
                .tag("begin", hex(versioned_dbm_start_key))
7958
49
                .tag("end", hex(versioned_dbm_end_key));
7959
7960
        // Remove versioned meta rowset key
7961
49
        if (!task.versioned_rowset_key.empty()) {
7962
49
            versioned::document_remove<RowsetMetaCloudPB>(
7963
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
7964
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7965
49
                    .tag("instance_id", instance_id_)
7966
49
                    .tag("tablet_id", tablet_id)
7967
49
                    .tag("rowset_id", rowset_id)
7968
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7969
49
        }
7970
7971
49
        if (!task.non_versioned_rowset_key.empty()) {
7972
49
            txn->remove(task.non_versioned_rowset_key);
7973
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7974
49
                    .tag("instance_id", instance_id_)
7975
49
                    .tag("tablet_id", tablet_id)
7976
49
                    .tag("rowset_id", rowset_id)
7977
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7978
49
        }
7979
7980
        // Remove recycle_rowset_key last to ensure retry safety:
7981
        // if cleanup fails, this key remains and triggers next round retry.
7982
49
        if (!task.recycle_rowset_key.empty()) {
7983
0
            txn->remove(task.recycle_rowset_key);
7984
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7985
0
                    .tag("instance_id", instance_id_)
7986
0
                    .tag("tablet_id", tablet_id)
7987
0
                    .tag("rowset_id", rowset_id)
7988
0
                    .tag("key", hex(task.recycle_rowset_key));
7989
0
        }
7990
7991
49
        err = txn->commit();
7992
49
        if (err != TxnErrorCode::TXN_OK) {
7993
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7994
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7995
0
                    .tag("instance_id", instance_id_)
7996
0
                    .tag("tablet_id", tablet_id)
7997
0
                    .tag("rowset_id", rowset_id)
7998
0
                    .tag("err", err);
7999
0
            ret = -1;
8000
0
            continue;
8001
0
        }
8002
8003
49
        LOG_INFO("cleanup rowset metadata success")
8004
49
                .tag("instance_id", instance_id_)
8005
49
                .tag("tablet_id", tablet_id)
8006
49
                .tag("rowset_id", rowset_id);
8007
49
    }
8008
10
    return ret;
8009
10
}
8010
8011
} // namespace doris::cloud