Coverage Report

Created: 2026-07-29 18:49

/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
81
namespace doris::cloud {
82
83
using namespace std::chrono;
84
85
namespace {
86
87
0
int64_t packed_file_retry_sleep_ms() {
88
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
89
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
90
0
    thread_local std::mt19937_64 gen(std::random_device {}());
91
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
92
0
    return dist(gen);
93
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
94
95
0
void sleep_for_packed_file_retry() {
96
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
97
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
98
99
37
bool filter_out_instance(const std::string& instance_id) {
100
37
    if (config::recycle_whitelist.empty()) {
101
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
102
35
               config::recycle_blacklist.end();
103
35
    }
104
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
105
2
           config::recycle_whitelist.end();
106
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
99
37
bool filter_out_instance(const std::string& instance_id) {
100
37
    if (config::recycle_whitelist.empty()) {
101
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
102
35
               config::recycle_blacklist.end();
103
35
    }
104
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
105
2
           config::recycle_whitelist.end();
106
37
}
107
108
867k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
109
867k
    const auto& locations = rowset.packed_slice_locations();
110
867k
    auto it = locations.find(path);
111
867k
    return it != locations.end() && it->second.has_packed_file_path() &&
112
867k
           !it->second.packed_file_path().empty();
113
867k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
108
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
109
7
    const auto& locations = rowset.packed_slice_locations();
110
7
    auto it = locations.find(path);
111
7
    return it != locations.end() && it->second.has_packed_file_path() &&
112
7
           !it->second.packed_file_path().empty();
113
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
108
867k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
109
867k
    const auto& locations = rowset.packed_slice_locations();
110
867k
    auto it = locations.find(path);
111
867k
    return it != locations.end() && it->second.has_packed_file_path() &&
112
867k
           !it->second.packed_file_path().empty();
113
867k
}
114
115
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
116
                                      const std::string& path,
117
866k
                                      std::vector<std::string>* file_paths) {
118
867k
    if (!is_packed_slice_path(rowset, path)) {
119
867k
        file_paths->push_back(path);
120
867k
    }
121
866k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
117
7
                                      std::vector<std::string>* file_paths) {
118
7
    if (!is_packed_slice_path(rowset, path)) {
119
7
        file_paths->push_back(path);
120
7
    }
121
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
117
866k
                                      std::vector<std::string>* file_paths) {
118
867k
    if (!is_packed_slice_path(rowset, path)) {
119
867k
        file_paths->push_back(path);
120
867k
    }
121
866k
}
122
123
} // namespace
124
125
// return 0 for success get a key, 1 for key not found, negative for error
126
0
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
127
0
    std::unique_ptr<Transaction> txn;
128
0
    TxnErrorCode err = txn_kv->create_txn(&txn);
129
0
    if (err != TxnErrorCode::TXN_OK) {
130
0
        return -1;
131
0
    }
132
0
    switch (txn->get(key, &val, true)) {
133
0
    case TxnErrorCode::TXN_OK:
134
0
        return 0;
135
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
136
0
        return 1;
137
0
    default:
138
0
        return -1;
139
0
    };
140
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
141
142
// 0 for success, negative for error
143
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
144
303
                   std::unique_ptr<RangeGetIterator>& it) {
145
303
    std::unique_ptr<Transaction> txn;
146
303
    TxnErrorCode err = txn_kv->create_txn(&txn);
147
303
    if (err != TxnErrorCode::TXN_OK) {
148
0
        return -1;
149
0
    }
150
303
    switch (txn->get(begin, end, &it, true)) {
151
303
    case TxnErrorCode::TXN_OK:
152
303
        return 0;
153
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
154
0
        return 1;
155
0
    default:
156
0
        return -1;
157
303
    };
158
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
144
31
                   std::unique_ptr<RangeGetIterator>& it) {
145
31
    std::unique_ptr<Transaction> txn;
146
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
147
31
    if (err != TxnErrorCode::TXN_OK) {
148
0
        return -1;
149
0
    }
150
31
    switch (txn->get(begin, end, &it, true)) {
151
31
    case TxnErrorCode::TXN_OK:
152
31
        return 0;
153
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
154
0
        return 1;
155
0
    default:
156
0
        return -1;
157
31
    };
158
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
144
272
                   std::unique_ptr<RangeGetIterator>& it) {
145
272
    std::unique_ptr<Transaction> txn;
146
272
    TxnErrorCode err = txn_kv->create_txn(&txn);
147
272
    if (err != TxnErrorCode::TXN_OK) {
148
0
        return -1;
149
0
    }
150
272
    switch (txn->get(begin, end, &it, true)) {
151
272
    case TxnErrorCode::TXN_OK:
152
272
        return 0;
153
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
154
0
        return 1;
155
0
    default:
156
0
        return -1;
157
272
    };
158
0
}
159
160
// return 0 for success otherwise error
161
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
162
6
    std::unique_ptr<Transaction> txn;
163
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
164
6
    if (err != TxnErrorCode::TXN_OK) {
165
0
        return -1;
166
0
    }
167
10
    for (auto k : keys) {
168
10
        txn->remove(k);
169
10
    }
170
6
    switch (txn->commit()) {
171
6
    case TxnErrorCode::TXN_OK:
172
6
        return 0;
173
0
    case TxnErrorCode::TXN_CONFLICT:
174
0
        return -1;
175
0
    default:
176
0
        return -1;
177
6
    }
178
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
161
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
162
1
    std::unique_ptr<Transaction> txn;
163
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
164
1
    if (err != TxnErrorCode::TXN_OK) {
165
0
        return -1;
166
0
    }
167
1
    for (auto k : keys) {
168
1
        txn->remove(k);
169
1
    }
170
1
    switch (txn->commit()) {
171
1
    case TxnErrorCode::TXN_OK:
172
1
        return 0;
173
0
    case TxnErrorCode::TXN_CONFLICT:
174
0
        return -1;
175
0
    default:
176
0
        return -1;
177
1
    }
178
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
161
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
162
5
    std::unique_ptr<Transaction> txn;
163
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
164
5
    if (err != TxnErrorCode::TXN_OK) {
165
0
        return -1;
166
0
    }
167
9
    for (auto k : keys) {
168
9
        txn->remove(k);
169
9
    }
170
5
    switch (txn->commit()) {
171
5
    case TxnErrorCode::TXN_OK:
172
5
        return 0;
173
0
    case TxnErrorCode::TXN_CONFLICT:
174
0
        return -1;
175
0
    default:
176
0
        return -1;
177
5
    }
178
5
}
179
180
// return 0 for success otherwise error
181
99
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
182
99
    std::unique_ptr<Transaction> txn;
183
99
    TxnErrorCode err = txn_kv->create_txn(&txn);
184
99
    if (err != TxnErrorCode::TXN_OK) {
185
0
        return -1;
186
0
    }
187
106k
    for (auto& k : keys) {
188
106k
        txn->remove(k);
189
106k
    }
190
99
    switch (txn->commit()) {
191
99
    case TxnErrorCode::TXN_OK:
192
99
        return 0;
193
0
    case TxnErrorCode::TXN_CONFLICT:
194
0
        return -1;
195
0
    default:
196
0
        return -1;
197
99
    }
198
99
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
181
34
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
182
34
    std::unique_ptr<Transaction> txn;
183
34
    TxnErrorCode err = txn_kv->create_txn(&txn);
184
34
    if (err != TxnErrorCode::TXN_OK) {
185
0
        return -1;
186
0
    }
187
34
    for (auto& k : keys) {
188
17
        txn->remove(k);
189
17
    }
190
34
    switch (txn->commit()) {
191
34
    case TxnErrorCode::TXN_OK:
192
34
        return 0;
193
0
    case TxnErrorCode::TXN_CONFLICT:
194
0
        return -1;
195
0
    default:
196
0
        return -1;
197
34
    }
198
34
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
181
65
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
182
65
    std::unique_ptr<Transaction> txn;
183
65
    TxnErrorCode err = txn_kv->create_txn(&txn);
184
65
    if (err != TxnErrorCode::TXN_OK) {
185
0
        return -1;
186
0
    }
187
105k
    for (auto& k : keys) {
188
105k
        txn->remove(k);
189
105k
    }
190
65
    switch (txn->commit()) {
191
65
    case TxnErrorCode::TXN_OK:
192
65
        return 0;
193
0
    case TxnErrorCode::TXN_CONFLICT:
194
0
        return -1;
195
0
    default:
196
0
        return -1;
197
65
    }
198
65
}
199
200
// return 0 for success otherwise error
201
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
202
106k
                                       std::string_view end) {
203
106k
    std::unique_ptr<Transaction> txn;
204
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
205
106k
    if (err != TxnErrorCode::TXN_OK) {
206
0
        return -1;
207
0
    }
208
106k
    txn->remove(begin, end);
209
106k
    switch (txn->commit()) {
210
106k
    case TxnErrorCode::TXN_OK:
211
106k
        return 0;
212
0
    case TxnErrorCode::TXN_CONFLICT:
213
0
        return -1;
214
0
    default:
215
0
        return -1;
216
106k
    }
217
106k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
202
17
                                       std::string_view end) {
203
17
    std::unique_ptr<Transaction> txn;
204
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
205
17
    if (err != TxnErrorCode::TXN_OK) {
206
0
        return -1;
207
0
    }
208
17
    txn->remove(begin, end);
209
17
    switch (txn->commit()) {
210
17
    case TxnErrorCode::TXN_OK:
211
17
        return 0;
212
0
    case TxnErrorCode::TXN_CONFLICT:
213
0
        return -1;
214
0
    default:
215
0
        return -1;
216
17
    }
217
17
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
202
106k
                                       std::string_view end) {
203
106k
    std::unique_ptr<Transaction> txn;
204
106k
    TxnErrorCode err = txn_kv->create_txn(&txn);
205
106k
    if (err != TxnErrorCode::TXN_OK) {
206
0
        return -1;
207
0
    }
208
106k
    txn->remove(begin, end);
209
106k
    switch (txn->commit()) {
210
106k
    case TxnErrorCode::TXN_OK:
211
106k
        return 0;
212
0
    case TxnErrorCode::TXN_CONFLICT:
213
0
        return -1;
214
0
    default:
215
0
        return -1;
216
106k
    }
217
106k
}
218
219
void scan_restore_job_rowset(
220
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
221
        std::string& msg,
222
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
223
224
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
225
                                      int64_t num_scanned, int64_t num_recycled,
226
47
                                      int64_t start_time) {
227
47
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
228
0
        int64_t cost =
229
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
230
0
        if (cost > config::recycle_task_threshold_seconds) {
231
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
232
0
                    .tag("instance_id", instance_id)
233
0
                    .tag("task", task_name)
234
0
                    .tag("num_scanned", num_scanned)
235
0
                    .tag("num_recycled", num_recycled);
236
0
        }
237
0
    }
238
47
    return;
239
47
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
226
2
                                      int64_t start_time) {
227
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
228
0
        int64_t cost =
229
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
230
0
        if (cost > config::recycle_task_threshold_seconds) {
231
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
232
0
                    .tag("instance_id", instance_id)
233
0
                    .tag("task", task_name)
234
0
                    .tag("num_scanned", num_scanned)
235
0
                    .tag("num_recycled", num_recycled);
236
0
        }
237
0
    }
238
2
    return;
239
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
226
45
                                      int64_t start_time) {
227
45
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
228
0
        int64_t cost =
229
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
230
0
        if (cost > config::recycle_task_threshold_seconds) {
231
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
232
0
                    .tag("instance_id", instance_id)
233
0
                    .tag("task", task_name)
234
0
                    .tag("num_scanned", num_scanned)
235
0
                    .tag("num_recycled", num_recycled);
236
0
        }
237
0
    }
238
45
    return;
239
45
}
240
241
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
242
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
243
244
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
245
6
                                                               "s3_producer_pool");
246
6
    s3_producer_pool->start();
247
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
248
6
                                                                  "recycle_tablet_pool");
249
6
    recycle_tablet_pool->start();
250
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
251
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
252
6
    group_recycle_function_pool->start();
253
6
    _thread_pool_group =
254
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
255
6
                                    std::move(group_recycle_function_pool));
256
257
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
258
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
259
6
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
260
6
}
261
262
6
Recycler::~Recycler() {
263
6
    if (!stopped()) {
264
0
        stop();
265
0
    }
266
6
}
267
268
5
void Recycler::instance_scanner_callback() {
269
    // sleep 60 seconds before scheduling for the launch procedure to complete:
270
    // some bad hdfs connection may cause some log to stdout stderr
271
    // which may pollute .out file and affect the script to check success
272
5
    std::this_thread::sleep_for(
273
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
274
1.25k
    while (!stopped()) {
275
1.25k
        if (config::enable_recycler) {
276
4
            std::vector<InstanceInfoPB> instances;
277
4
            get_all_instances(txn_kv_.get(), instances);
278
            // TODO(plat1ko): delete job recycle kv of non-existent instances
279
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
280
4
                std::stringstream ss;
281
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
282
4
                return ss.str();
283
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
279
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
280
4
                std::stringstream ss;
281
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
282
4
                return ss.str();
283
4
            }();
284
4
            if (!instances.empty()) {
285
                // enqueue instances
286
3
                std::lock_guard lock(mtx_);
287
30
                for (auto& instance : instances) {
288
30
                    if (filter_out_instance(instance.instance_id())) continue;
289
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
290
                    // skip instance already in pending queue
291
30
                    if (success) {
292
30
                        pending_instance_queue_.push_back(std::move(instance));
293
30
                    }
294
30
                }
295
3
                pending_instance_cond_.notify_all();
296
3
            }
297
1.25k
        } else {
298
1.25k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
299
1.25k
        }
300
1.25k
        {
301
1.25k
            std::unique_lock lock(mtx_);
302
1.25k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
303
2.50k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
303
2.50k
                               [&]() { return stopped(); });
304
1.25k
        }
305
1.25k
    }
306
5
}
307
308
7
void Recycler::recycle_callback() {
309
37
    while (!stopped()) {
310
37
        InstanceInfoPB instance;
311
37
        {
312
37
            std::unique_lock lock(mtx_);
313
37
            pending_instance_cond_.wait(
314
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
314
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
315
37
            if (stopped()) {
316
8
                return;
317
8
            }
318
29
            instance = std::move(pending_instance_queue_.front());
319
29
            pending_instance_queue_.pop_front();
320
29
            pending_instance_set_.erase(instance.instance_id());
321
29
        }
322
0
        auto& instance_id = instance.instance_id();
323
29
        {
324
29
            std::lock_guard lock(mtx_);
325
            // skip instance in recycling
326
29
            if (recycling_instance_map_.count(instance_id)) continue;
327
29
        }
328
29
        if (!config::enable_recycler) {
329
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
330
1
                         << " since enable_recycler is false";
331
1
            continue;
332
1
        }
333
28
        auto instance_recycler = std::make_shared<InstanceRecycler>(
334
28
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
335
336
28
        if (int r = instance_recycler->init(); r != 0) {
337
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
338
0
                         << " ret=" << r;
339
0
            continue;
340
0
        }
341
28
        std::string recycle_job_key;
342
28
        job_recycle_key({instance_id}, &recycle_job_key);
343
28
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
344
28
                                               ip_port_, config::recycle_interval_seconds * 1000);
345
28
        if (ret != 0) { // Prepare failed
346
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
347
20
                         << " ret=" << ret;
348
20
            continue;
349
20
        } else {
350
8
            std::lock_guard lock(mtx_);
351
8
            recycling_instance_map_.emplace(instance_id, instance_recycler);
352
8
        }
353
8
        if (stopped()) return;
354
8
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
355
8
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
356
8
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
357
8
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
358
8
        ret = instance_recycler->do_recycle();
359
        // If instance recycler has been aborted, don't finish this job
360
361
10
        if (!instance_recycler->stopped()) {
362
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
363
10
                                        ret == 0, ctime_ms);
364
10
        }
365
10
        if (instance_recycler->stopped() || ret != 0) {
366
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
367
0
        }
368
8
        {
369
8
            std::lock_guard lock(mtx_);
370
8
            recycling_instance_map_.erase(instance_id);
371
8
        }
372
373
8
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
374
8
        auto elpased_ms = now - ctime_ms;
375
8
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
376
8
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
377
8
        g_bvar_recycler_instance_next_ts.put({instance_id},
378
8
                                             now + config::recycle_interval_seconds * 1000);
379
8
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
380
8
        LOG(INFO) << "recycle instance done, "
381
8
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
382
8
                  << " now: " << now;
383
384
8
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
385
386
8
        LOG_WARNING("finish recycle instance")
387
8
                .tag("instance_id", instance_id)
388
8
                .tag("cost_ms", elpased_ms);
389
8
    }
390
7
}
391
392
4
void Recycler::lease_recycle_jobs() {
393
54
    while (!stopped()) {
394
50
        std::vector<std::string> instances;
395
50
        instances.reserve(recycling_instance_map_.size());
396
50
        {
397
50
            std::lock_guard lock(mtx_);
398
50
            for (auto& [id, _] : recycling_instance_map_) {
399
30
                instances.push_back(id);
400
30
            }
401
50
        }
402
50
        for (auto& i : instances) {
403
30
            std::string recycle_job_key;
404
30
            job_recycle_key({i}, &recycle_job_key);
405
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
406
30
            if (ret == 1) {
407
0
                std::lock_guard lock(mtx_);
408
0
                if (auto it = recycling_instance_map_.find(i);
409
0
                    it != recycling_instance_map_.end()) {
410
0
                    it->second->stop();
411
0
                }
412
0
            }
413
30
        }
414
50
        {
415
50
            std::unique_lock lock(mtx_);
416
50
            notifier_.wait_for(lock,
417
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
418
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
418
100
                               [&]() { return stopped(); });
419
50
        }
420
50
    }
421
4
}
422
423
4
void Recycler::check_recycle_tasks() {
424
7
    while (!stopped()) {
425
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
426
3
        {
427
3
            std::lock_guard lock(mtx_);
428
3
            recycling_instance_map = recycling_instance_map_;
429
3
        }
430
3
        for (auto& entry : recycling_instance_map) {
431
0
            entry.second->check_recycle_tasks();
432
0
        }
433
434
3
        std::unique_lock lock(mtx_);
435
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
436
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
436
6
                           [&]() { return stopped(); });
437
3
    }
438
4
}
439
440
4
int Recycler::start(brpc::Server* server) {
441
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
442
4
    S3Environment::getInstance();
443
444
4
    if (config::enable_checker) {
445
0
        checker_ = std::make_unique<Checker>(txn_kv_);
446
0
        int ret = checker_->start();
447
0
        std::string msg;
448
0
        if (ret != 0) {
449
0
            msg = "failed to start checker";
450
0
            LOG(ERROR) << msg;
451
0
            std::cerr << msg << std::endl;
452
0
            return ret;
453
0
        }
454
0
        msg = "checker started";
455
0
        LOG(INFO) << msg;
456
0
        std::cout << msg << std::endl;
457
0
    }
458
459
4
    if (server) {
460
        // Add service
461
1
        auto recycler_service =
462
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
463
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
464
1
    }
465
466
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
466
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
467
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
468
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
468
7
        workers_.emplace_back([this] { recycle_callback(); });
469
8
    }
470
471
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
472
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
473
474
4
    if (config::enable_snapshot_data_migrator) {
475
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
476
0
        int ret = snapshot_data_migrator_->start();
477
0
        if (ret != 0) {
478
0
            LOG(ERROR) << "failed to start snapshot data migrator";
479
0
            return ret;
480
0
        }
481
0
        LOG(INFO) << "snapshot data migrator started";
482
0
    }
483
484
4
    if (config::enable_snapshot_chain_compactor) {
485
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
486
0
        int ret = snapshot_chain_compactor_->start();
487
0
        if (ret != 0) {
488
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
489
0
            return ret;
490
0
        }
491
0
        LOG(INFO) << "snapshot chain compactor started";
492
0
    }
493
494
4
    return 0;
495
4
}
496
497
4
void Recycler::stop() {
498
4
    stopped_ = true;
499
4
    notifier_.notify_all();
500
4
    pending_instance_cond_.notify_all();
501
4
    {
502
4
        std::lock_guard lock(mtx_);
503
4
        for (auto& [_, recycler] : recycling_instance_map_) {
504
0
            recycler->stop();
505
0
        }
506
4
    }
507
20
    for (auto& w : workers_) {
508
20
        if (w.joinable()) w.join();
509
20
    }
510
4
    if (checker_) {
511
0
        checker_->stop();
512
0
    }
513
4
    if (snapshot_data_migrator_) {
514
0
        snapshot_data_migrator_->stop();
515
0
    }
516
4
    if (snapshot_chain_compactor_) {
517
0
        snapshot_chain_compactor_->stop();
518
0
    }
519
4
}
520
521
class InstanceRecycler::InvertedIndexIdCache {
522
public:
523
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
524
135
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
525
526
    // Return 0 if success, 1 if schema kv not found, negative for error
527
    // For the same index_id, schema_version, res, since `get` is not completely atomic
528
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
529
    // resulting in repeated addition and inaccuracy.
530
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
531
    // repeated addition does not affect correctness.
532
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
533
28.4k
        {
534
28.4k
            std::lock_guard lock(mtx_);
535
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
536
3.97k
                return 0;
537
3.97k
            }
538
24.4k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
539
24.4k
                it != inverted_index_id_map_.end()) {
540
17.7k
                res = it->second;
541
17.7k
                return 0;
542
17.7k
            }
543
24.4k
        }
544
        // Get schema from kv
545
        // TODO(plat1ko): Single flight
546
6.65k
        std::unique_ptr<Transaction> txn;
547
6.65k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
548
6.65k
        if (err != TxnErrorCode::TXN_OK) {
549
0
            LOG(WARNING) << "failed to create txn, err=" << err;
550
0
            return -1;
551
0
        }
552
6.65k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
553
6.65k
        ValueBuf val_buf;
554
6.65k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
555
6.65k
        if (err != TxnErrorCode::TXN_OK) {
556
500
            LOG(WARNING) << "failed to get schema, err=" << err;
557
500
            return static_cast<int>(err);
558
500
        }
559
6.15k
        doris::TabletSchemaCloudPB schema;
560
6.15k
        if (!parse_schema_value(val_buf, &schema)) {
561
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
562
0
            return -1;
563
0
        }
564
6.15k
        if (schema.index_size() > 0) {
565
4.42k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
566
4.42k
            if (schema.has_inverted_index_storage_format()) {
567
4.41k
                index_format = schema.inverted_index_storage_format();
568
4.41k
            }
569
4.42k
            res.first = index_format;
570
4.42k
            res.second.reserve(schema.index_size());
571
11.2k
            for (auto& i : schema.index()) {
572
11.2k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
573
11.2k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
574
11.2k
                }
575
11.2k
            }
576
4.42k
        }
577
6.15k
        insert(index_id, schema_version, res);
578
6.15k
        return 0;
579
6.15k
    }
580
581
    // Empty `ids` means this schema has no inverted index
582
6.15k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
583
6.15k
        if (index_info.second.empty()) {
584
1.72k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
585
1.72k
            std::lock_guard lock(mtx_);
586
1.72k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
587
4.42k
        } else {
588
4.42k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
589
4.42k
            std::lock_guard lock(mtx_);
590
4.42k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
591
4.42k
        }
592
6.15k
    }
593
594
private:
595
    std::string instance_id_;
596
    std::shared_ptr<TxnKv> txn_kv_;
597
598
    std::mutex mtx_;
599
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
600
    struct HashOfKey {
601
58.9k
        size_t operator()(const Key& key) const {
602
58.9k
            size_t seed = 0;
603
58.9k
            seed = std::hash<int64_t> {}(key.first);
604
58.9k
            seed = std::hash<int32_t> {}(key.second);
605
58.9k
            return seed;
606
58.9k
        }
607
    };
608
    // <index_id, schema_version> -> inverted_index_ids
609
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
610
    // Store <index_id, schema_version> of schema which doesn't have inverted index
611
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
612
};
613
614
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
615
                                   RecyclerThreadPoolGroup thread_pool_group,
616
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
617
        : txn_kv_(std::move(txn_kv)),
618
          instance_id_(instance.instance_id()),
619
          instance_info_(instance),
620
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
621
          _thread_pool_group(std::move(thread_pool_group)),
622
          txn_lazy_committer_(std::move(txn_lazy_committer)),
623
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
624
135
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
625
135
    delete_bitmap_lock_white_list_->init();
626
135
    resource_mgr_->init();
627
135
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv_);
628
629
    // Since the recycler's resource manager could not be notified when instance info changes,
630
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
631
135
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
632
135
};
633
634
135
InstanceRecycler::~InstanceRecycler() = default;
635
636
119
int InstanceRecycler::init_obj_store_accessors() {
637
119
    for (const auto& obj_info : instance_info_.obj_info()) {
638
77
#ifdef UNIT_TEST
639
77
        auto accessor = std::make_shared<MockAccessor>();
640
#else
641
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
642
        if (!s3_conf) {
643
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
644
            return -1;
645
        }
646
647
        std::shared_ptr<S3Accessor> accessor;
648
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
649
        if (ret != 0) {
650
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
651
                         << " resource_id=" << obj_info.id();
652
            return ret;
653
        }
654
#endif
655
77
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
656
77
    }
657
658
119
    return 0;
659
119
}
660
661
119
int InstanceRecycler::init_storage_vault_accessors() {
662
119
    if (instance_info_.resource_ids().empty()) {
663
112
        return 0;
664
112
    }
665
666
7
    FullRangeGetOptions opts(txn_kv_);
667
7
    opts.prefetch = true;
668
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
669
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
670
671
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
672
18
        auto [k, v] = *kv;
673
18
        StorageVaultPB vault;
674
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
675
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
676
0
            return -1;
677
0
        }
678
18
        std::string recycler_storage_vault_white_list = accumulate(
679
18
                config::recycler_storage_vault_white_list.begin(),
680
18
                config::recycler_storage_vault_white_list.end(), std::string(),
681
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
681
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
682
18
        LOG_INFO("config::recycler_storage_vault_white_list")
683
18
                .tag("", recycler_storage_vault_white_list);
684
18
        if (!config::recycler_storage_vault_white_list.empty()) {
685
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
686
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
687
8
                it == config::recycler_storage_vault_white_list.end()) {
688
2
                LOG_WARNING(
689
2
                        "failed to init accessor for vault because this vault is not in "
690
2
                        "config::recycler_storage_vault_white_list. ")
691
2
                        .tag(" vault name:", vault.name())
692
2
                        .tag(" config::recycler_storage_vault_white_list:",
693
2
                             recycler_storage_vault_white_list);
694
2
                continue;
695
2
            }
696
8
        }
697
16
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
698
16
                                 &accessor_map_, &vault);
699
16
        if (vault.has_hdfs_info()) {
700
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
701
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
702
9
            int ret = accessor->init();
703
9
            if (ret != 0) {
704
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
705
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
706
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
707
4
                continue;
708
4
            }
709
5
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
710
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
711
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
712
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
713
#else
714
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
715
                       << "but HDFS storage vaults were detected";
716
#endif
717
7
        } else if (vault.has_obj_info()) {
718
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
719
7
            if (!s3_conf) {
720
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
721
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
722
1
                continue;
723
1
            }
724
725
6
            std::shared_ptr<S3Accessor> accessor;
726
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
727
6
            if (ret != 0) {
728
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
729
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
730
0
                             << " ret=" << ret
731
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
732
0
                continue;
733
0
            }
734
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
735
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
736
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
737
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
738
6
        }
739
16
    }
740
741
7
    if (!it->is_valid()) {
742
0
        LOG_WARNING("failed to get storage vault kv");
743
0
        return -1;
744
0
    }
745
746
7
    if (accessor_map_.empty()) {
747
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
748
1
        return -2;
749
1
    }
750
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
751
6
             instance_id_);
752
753
6
    return 0;
754
7
}
755
756
119
int InstanceRecycler::init() {
757
119
    int ret = init_obj_store_accessors();
758
119
    if (ret != 0) {
759
0
        return ret;
760
0
    }
761
762
119
    return init_storage_vault_accessors();
763
119
}
764
765
template <typename... Func>
766
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
120
    return [funcs...]() {
768
120
        return [](std::initializer_list<int> ret_vals) {
769
120
            int i = 0;
770
140
            for (int ret : ret_vals) {
771
140
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
140
            }
775
120
            return i;
776
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
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
20
            for (int ret : ret_vals) {
771
20
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
20
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
20
            for (int ret : ret_vals) {
771
20
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
20
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
0
                    i = ret;
773
0
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
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
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
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
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
766
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
767
10
    return [funcs...]() {
768
10
        return [](std::initializer_list<int> ret_vals) {
769
10
            int i = 0;
770
10
            for (int ret : ret_vals) {
771
10
                if (ret != 0) {
772
10
                    i = ret;
773
10
                }
774
10
            }
775
10
            return i;
776
10
        }({funcs()...});
777
10
    };
778
10
}
779
780
10
int InstanceRecycler::do_recycle() {
781
10
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
782
10
    tablet_metrics_context_.reset();
783
10
    segment_metrics_context_.reset();
784
10
    DORIS_CLOUD_DEFER {
785
10
        tablet_metrics_context_.finish_report();
786
10
        segment_metrics_context_.finish_report();
787
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
784
10
    DORIS_CLOUD_DEFER {
785
10
        tablet_metrics_context_.finish_report();
786
10
        segment_metrics_context_.finish_report();
787
10
    };
788
10
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
789
0
        int res = recycle_cluster_snapshots();
790
0
        if (res != 0) {
791
0
            return -1;
792
0
        }
793
0
        return recycle_deleted_instance();
794
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
795
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
796
10
                                        fmt::format("instance id {}", instance_id_),
797
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
797
120
                                        [](int r) { return r != 0; });
798
10
        sync_executor
799
10
                .add(task_wrapper(
800
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
800
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
801
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
801
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
802
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
803
                                   // becase they may both recycle the same set of tablets
804
                        // recycle dropped table or idexes(mv, rollup)
805
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
805
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
806
                        // recycle dropped partitions
807
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
807
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
808
10
                .add(task_wrapper(
809
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
809
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
810
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
810
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
811
10
                .add(task_wrapper(
812
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
812
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
813
10
                .add(task_wrapper(
814
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
814
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
815
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
815
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
816
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
816
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
817
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
817
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
818
10
                .add(task_wrapper(
819
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
819
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
820
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
820
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
821
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
821
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
822
10
        bool finished = true;
823
10
        std::vector<int> rets = sync_executor.when_all(&finished);
824
120
        for (int ret : rets) {
825
120
            if (ret != 0) {
826
0
                return ret;
827
0
            }
828
120
        }
829
10
        return finished ? 0 : -1;
830
10
    } else {
831
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
832
0
                     << " instance_id=" << instance_id_;
833
0
        return -1;
834
0
    }
835
10
}
836
837
/**
838
* 1. delete all remote data
839
* 2. delete all kv
840
* 3. remove instance kv
841
*/
842
4
int InstanceRecycler::recycle_deleted_instance() {
843
4
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
844
845
4
    int ret = 0;
846
4
    auto start_time = steady_clock::now();
847
848
4
    DORIS_CLOUD_DEFER {
849
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
850
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
851
4
                     << " recycle deleted instance, cost=" << cost
852
4
                     << "s, instance_id=" << instance_id_;
853
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
848
4
    DORIS_CLOUD_DEFER {
849
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
850
4
        LOG(WARNING) << (ret == 0 ? "successfully" : "failed to")
851
4
                     << " recycle deleted instance, cost=" << cost
852
4
                     << "s, instance_id=" << instance_id_;
853
4
    };
854
855
    // Step 1: Recycle versioned rowsets in recycle space (already marked for deletion)
856
4
    if (recycle_versioned_rowsets() != 0) {
857
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
858
0
        return -1;
859
0
    }
860
861
    // Step 2: Recycle operation logs (can recycle logs not referenced by snapshots)
862
4
    if (recycle_operation_logs() != 0) {
863
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
864
0
        return -1;
865
0
    }
866
867
    // Step 3: Check if there are still cluster snapshots
868
4
    bool has_snapshots = false;
869
4
    if (has_cluster_snapshots(&has_snapshots) != 0) {
870
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
871
0
        return -1;
872
4
    } else if (has_snapshots) {
873
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
874
1
        return 0;
875
1
    }
876
877
3
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
878
3
                            instance_info().snapshot_switch_status() !=
879
0
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
880
3
    if (snapshot_enabled) {
881
0
        bool has_unrecycled_rowsets = false;
882
0
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
883
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
884
0
            return -1;
885
0
        } else if (has_unrecycled_rowsets) {
886
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
887
0
                    .tag("instance_id", instance_id_);
888
0
            return ret;
889
0
        }
890
3
    } else { // delete all remote data if snapshot is disabled
891
3
        for (auto& [_, accessor] : accessor_map_) {
892
3
            if (stopped()) {
893
0
                return ret;
894
0
            }
895
896
3
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
897
3
            int del_ret = accessor->delete_all();
898
3
            if (del_ret == 0) {
899
3
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
900
3
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
901
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
902
                // so the recycling has been successful.
903
0
                ret = -1;
904
0
            }
905
3
        }
906
907
3
        if (ret != 0) {
908
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
909
0
            return ret;
910
0
        }
911
3
    }
912
913
    // delete all kv
914
3
    std::unique_ptr<Transaction> txn;
915
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
916
3
    if (err != TxnErrorCode::TXN_OK) {
917
0
        LOG(WARNING) << "failed to create txn";
918
0
        ret = -1;
919
0
        return -1;
920
0
    }
921
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
922
    // delete kv before deleting objects to prevent the checker from misjudging data loss
923
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
924
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
925
3
    txn->remove(start_txn_key, end_txn_key);
926
3
    std::string start_version_key = version_key_prefix(instance_id_);
927
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
928
3
    txn->remove(start_version_key, end_version_key);
929
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
930
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
931
3
    txn->remove(start_meta_key, end_meta_key);
932
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
933
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
934
3
    txn->remove(start_recycle_key, end_recycle_key);
935
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
936
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
937
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
938
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
939
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
940
3
    txn->remove(start_copy_key, end_copy_key);
941
    // should not remove job key range, because we need to reserve job recycle kv
942
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
943
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
944
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
945
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
946
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
947
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
948
3
    std::string start_vault_key = storage_vault_key(key_info0);
949
3
    std::string end_vault_key = storage_vault_key(key_info1);
950
3
    txn->remove(start_vault_key, end_vault_key);
951
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
952
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
953
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
954
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
955
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
956
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
957
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
958
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
959
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
960
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
961
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
962
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
963
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
964
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
965
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
966
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
967
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
968
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
969
3
    err = txn->commit();
970
3
    if (err != TxnErrorCode::TXN_OK) {
971
0
        LOG(WARNING) << "failed to delete all kv, instance_id=" << instance_id_ << ", err=" << err;
972
0
        ret = -1;
973
0
    }
974
975
3
    if (ret == 0) {
976
        // remove instance kv
977
        // ATTN: MUST ensure that cloud platform won't regenerate the same instance id
978
3
        err = txn_kv_->create_txn(&txn);
979
3
        if (err != TxnErrorCode::TXN_OK) {
980
0
            LOG(WARNING) << "failed to create txn";
981
0
            ret = -1;
982
0
            return ret;
983
0
        }
984
3
        std::string key;
985
3
        instance_key({instance_id_}, &key);
986
3
        txn->atomic_add(system_meta_service_instance_update_key(), 1);
987
3
        txn->remove(key);
988
3
        err = txn->commit();
989
3
        if (err != TxnErrorCode::TXN_OK) {
990
0
            LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
991
0
                         << " err=" << err;
992
0
            ret = -1;
993
0
        }
994
3
    }
995
3
    return ret;
996
3
}
997
998
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
999
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1000
9
    if (exists == nullptr) {
1001
0
        return -1;
1002
0
    }
1003
9
    *exists = false;
1004
1005
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1006
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1007
9
    std::string scan_begin = begin;
1008
1009
9
    while (true) {
1010
9
        std::unique_ptr<RangeGetIterator> it_range;
1011
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1012
9
        if (get_ret < 0) {
1013
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1014
0
                    .tag("instance_id", instance_id_)
1015
0
                    .tag("tablet_id", tablet_id)
1016
0
                    .tag("ret", get_ret);
1017
0
            return -1;
1018
0
        }
1019
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1020
6
            return 0;
1021
6
        }
1022
1023
3
        std::string last_key;
1024
3
        while (it_range->has_next()) {
1025
3
            auto [k, v] = it_range->next();
1026
3
            last_key.assign(k.data(), k.size());
1027
3
            doris::RowsetMetaCloudPB rowset_meta;
1028
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1029
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1030
0
                        .tag("instance_id", instance_id_)
1031
0
                        .tag("tablet_id", tablet_id)
1032
0
                        .tag("key", hex(k));
1033
0
                continue;
1034
0
            }
1035
3
            if (stats) {
1036
3
                ++stats->rowset_scan_count;
1037
3
            }
1038
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1039
3
                *exists = true;
1040
3
                return 0;
1041
3
            }
1042
3
        }
1043
1044
0
        if (!it_range->more()) {
1045
0
            return 0;
1046
0
        }
1047
1048
        // Continue scanning from the next key to keep each transaction short.
1049
0
        scan_begin = std::move(last_key);
1050
0
        scan_begin.push_back('\x00');
1051
0
    }
1052
9
}
1053
1054
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1055
                                                          const std::string& rowset_id,
1056
                                                          int64_t txn_id, bool* recycle_exists,
1057
11
                                                          bool* tmp_exists) {
1058
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1059
0
        return -1;
1060
0
    }
1061
11
    *recycle_exists = false;
1062
11
    *tmp_exists = false;
1063
1064
11
    if (txn_id <= 0) {
1065
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1066
0
                .tag("instance_id", instance_id_)
1067
0
                .tag("tablet_id", tablet_id)
1068
0
                .tag("rowset_id", rowset_id)
1069
0
                .tag("txn_id", txn_id);
1070
0
        return -1;
1071
0
    }
1072
1073
11
    std::unique_ptr<Transaction> txn;
1074
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1075
11
    if (err != TxnErrorCode::TXN_OK) {
1076
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1077
0
                .tag("instance_id", instance_id_)
1078
0
                .tag("tablet_id", tablet_id)
1079
0
                .tag("rowset_id", rowset_id)
1080
0
                .tag("txn_id", txn_id)
1081
0
                .tag("err", err);
1082
0
        return -1;
1083
0
    }
1084
1085
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1086
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1087
11
    if (ret == TxnErrorCode::TXN_OK) {
1088
1
        *recycle_exists = true;
1089
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1090
0
        LOG_WARNING("failed to check recycle rowset existence")
1091
0
                .tag("instance_id", instance_id_)
1092
0
                .tag("tablet_id", tablet_id)
1093
0
                .tag("rowset_id", rowset_id)
1094
0
                .tag("key", hex(recycle_key))
1095
0
                .tag("err", ret);
1096
0
        return -1;
1097
0
    }
1098
1099
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1100
11
    ret = key_exists(txn.get(), tmp_key, true);
1101
11
    if (ret == TxnErrorCode::TXN_OK) {
1102
1
        *tmp_exists = true;
1103
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1104
0
        LOG_WARNING("failed to check tmp rowset existence")
1105
0
                .tag("instance_id", instance_id_)
1106
0
                .tag("tablet_id", tablet_id)
1107
0
                .tag("txn_id", txn_id)
1108
0
                .tag("key", hex(tmp_key))
1109
0
                .tag("err", ret);
1110
0
        return -1;
1111
0
    }
1112
1113
11
    return 0;
1114
11
}
1115
1116
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1117
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1118
8
    if (!hint.empty()) {
1119
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1120
8
            return {hint, it->second};
1121
8
        }
1122
8
    }
1123
1124
0
    return {"", nullptr};
1125
8
}
1126
1127
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1128
                                               const std::string& packed_file_path,
1129
3
                                               PackedFileRecycleStats* stats) {
1130
3
    bool local_changed = false;
1131
3
    int64_t left_num = 0;
1132
3
    int64_t left_bytes = 0;
1133
3
    bool all_small_files_confirmed = true;
1134
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1135
1136
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1137
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1138
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1139
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1140
14
        LOG_INFO("packed slice correction status")
1141
14
                .tag("instance_id", instance_id_)
1142
14
                .tag("packed_file_path", packed_file_path)
1143
14
                .tag("small_file_path", file.path())
1144
14
                .tag("tablet_id", tablet_id)
1145
14
                .tag("rowset_id", rowset_id)
1146
14
                .tag("txn_id", txn_id)
1147
14
                .tag("size", file.size())
1148
14
                .tag("deleted", file.deleted())
1149
14
                .tag("corrected", file.corrected())
1150
14
                .tag("confirmed_this_round", confirmed_this_round);
1151
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
1136
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1137
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1138
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1139
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1140
14
        LOG_INFO("packed slice correction status")
1141
14
                .tag("instance_id", instance_id_)
1142
14
                .tag("packed_file_path", packed_file_path)
1143
14
                .tag("small_file_path", file.path())
1144
14
                .tag("tablet_id", tablet_id)
1145
14
                .tag("rowset_id", rowset_id)
1146
14
                .tag("txn_id", txn_id)
1147
14
                .tag("size", file.size())
1148
14
                .tag("deleted", file.deleted())
1149
14
                .tag("corrected", file.corrected())
1150
14
                .tag("confirmed_this_round", confirmed_this_round);
1151
14
    };
1152
1153
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1154
14
        auto* small_file = packed_info->mutable_slices(i);
1155
14
        if (small_file->deleted()) {
1156
3
            log_small_file_status(*small_file, small_file->corrected());
1157
3
            continue;
1158
3
        }
1159
1160
11
        if (small_file->corrected()) {
1161
0
            left_num++;
1162
0
            left_bytes += small_file->size();
1163
0
            log_small_file_status(*small_file, true);
1164
0
            continue;
1165
0
        }
1166
1167
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1168
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1169
0
                    .tag("instance_id", instance_id_)
1170
0
                    .tag("small_file_path", small_file->path())
1171
0
                    .tag("index", i);
1172
0
            return -1;
1173
0
        }
1174
1175
11
        int64_t tablet_id = small_file->tablet_id();
1176
11
        const std::string& rowset_id = small_file->rowset_id();
1177
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1178
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1179
0
                    .tag("instance_id", instance_id_)
1180
0
                    .tag("small_file_path", small_file->path())
1181
0
                    .tag("index", i)
1182
0
                    .tag("tablet_id", tablet_id)
1183
0
                    .tag("rowset_id", rowset_id)
1184
0
                    .tag("has_txn_id", small_file->has_txn_id())
1185
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1186
0
            return -1;
1187
0
        }
1188
11
        int64_t txn_id = small_file->txn_id();
1189
11
        bool recycle_exists = false;
1190
11
        bool tmp_exists = false;
1191
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1192
11
                                                &tmp_exists) != 0) {
1193
0
            return -1;
1194
0
        }
1195
1196
11
        bool small_file_confirmed = false;
1197
11
        if (tmp_exists) {
1198
1
            left_num++;
1199
1
            left_bytes += small_file->size();
1200
1
            small_file_confirmed = true;
1201
10
        } else if (recycle_exists) {
1202
1
            left_num++;
1203
1
            left_bytes += small_file->size();
1204
            // keep small_file_confirmed=false so the packed file remains uncorrected
1205
9
        } else {
1206
9
            bool rowset_exists = false;
1207
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1208
0
                return -1;
1209
0
            }
1210
1211
9
            if (!rowset_exists) {
1212
6
                if (!small_file->deleted()) {
1213
6
                    small_file->set_deleted(true);
1214
6
                    local_changed = true;
1215
6
                }
1216
6
                if (!small_file->corrected()) {
1217
6
                    small_file->set_corrected(true);
1218
6
                    local_changed = true;
1219
6
                }
1220
6
                small_file_confirmed = true;
1221
6
            } else {
1222
3
                left_num++;
1223
3
                left_bytes += small_file->size();
1224
3
                small_file_confirmed = true;
1225
3
            }
1226
9
        }
1227
1228
11
        if (!small_file_confirmed) {
1229
1
            all_small_files_confirmed = false;
1230
1
        }
1231
1232
11
        if (small_file->corrected() != small_file_confirmed) {
1233
4
            small_file->set_corrected(small_file_confirmed);
1234
4
            local_changed = true;
1235
4
        }
1236
1237
11
        log_small_file_status(*small_file, small_file_confirmed);
1238
11
    }
1239
1240
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1241
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1242
3
        local_changed = true;
1243
3
    }
1244
3
    if (packed_info->ref_cnt() != left_num) {
1245
3
        auto old_ref_cnt = packed_info->ref_cnt();
1246
3
        packed_info->set_ref_cnt(left_num);
1247
3
        LOG_INFO("corrected packed file ref count")
1248
3
                .tag("instance_id", instance_id_)
1249
3
                .tag("resource_id", packed_info->resource_id())
1250
3
                .tag("packed_file_path", packed_file_path)
1251
3
                .tag("old_ref_cnt", old_ref_cnt)
1252
3
                .tag("new_ref_cnt", left_num);
1253
3
        local_changed = true;
1254
3
    }
1255
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1256
2
        packed_info->set_corrected(all_small_files_confirmed);
1257
2
        local_changed = true;
1258
2
    }
1259
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1260
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1261
1
        local_changed = true;
1262
1
    }
1263
1264
3
    if (changed != nullptr) {
1265
3
        *changed = local_changed;
1266
3
    }
1267
3
    return 0;
1268
3
}
1269
1270
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1271
                                                 const std::string& packed_file_path,
1272
4
                                                 PackedFileRecycleStats* stats) {
1273
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1274
4
    bool correction_ok = false;
1275
4
    cloud::PackedFileInfoPB packed_info;
1276
1277
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1278
4
        if (stopped()) {
1279
0
            LOG_WARNING("recycler stopped before processing packed file")
1280
0
                    .tag("instance_id", instance_id_)
1281
0
                    .tag("packed_file_path", packed_file_path)
1282
0
                    .tag("attempt", attempt);
1283
0
            return -1;
1284
0
        }
1285
1286
4
        std::unique_ptr<Transaction> txn;
1287
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1288
4
        if (err != TxnErrorCode::TXN_OK) {
1289
0
            LOG_WARNING("failed to create txn when processing packed file")
1290
0
                    .tag("instance_id", instance_id_)
1291
0
                    .tag("packed_file_path", packed_file_path)
1292
0
                    .tag("attempt", attempt)
1293
0
                    .tag("err", err);
1294
0
            return -1;
1295
0
        }
1296
1297
4
        std::string packed_val;
1298
4
        err = txn->get(packed_key, &packed_val);
1299
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1300
0
            return 0;
1301
0
        }
1302
4
        if (err != TxnErrorCode::TXN_OK) {
1303
0
            LOG_WARNING("failed to get packed file kv")
1304
0
                    .tag("instance_id", instance_id_)
1305
0
                    .tag("packed_file_path", packed_file_path)
1306
0
                    .tag("attempt", attempt)
1307
0
                    .tag("err", err);
1308
0
            return -1;
1309
0
        }
1310
1311
4
        if (!packed_info.ParseFromString(packed_val)) {
1312
0
            LOG_WARNING("failed to parse packed file info")
1313
0
                    .tag("instance_id", instance_id_)
1314
0
                    .tag("packed_file_path", packed_file_path)
1315
0
                    .tag("attempt", attempt);
1316
0
            return -1;
1317
0
        }
1318
1319
4
        int64_t now_sec = ::time(nullptr);
1320
4
        bool corrected = packed_info.corrected();
1321
4
        bool due = config::force_immediate_recycle ||
1322
4
                   now_sec - packed_info.created_at_sec() >=
1323
4
                           config::packed_file_correction_delay_seconds;
1324
1325
4
        if (!corrected && due) {
1326
3
            bool changed = false;
1327
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1328
0
                LOG_WARNING("correct_packed_file_info failed")
1329
0
                        .tag("instance_id", instance_id_)
1330
0
                        .tag("packed_file_path", packed_file_path)
1331
0
                        .tag("attempt", attempt);
1332
0
                return -1;
1333
0
            }
1334
3
            if (changed) {
1335
3
                std::string updated;
1336
3
                if (!packed_info.SerializeToString(&updated)) {
1337
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1338
0
                            .tag("instance_id", instance_id_)
1339
0
                            .tag("packed_file_path", packed_file_path)
1340
0
                            .tag("attempt", attempt);
1341
0
                    return -1;
1342
0
                }
1343
3
                txn->put(packed_key, updated);
1344
3
                err = txn->commit();
1345
3
                if (err == TxnErrorCode::TXN_OK) {
1346
3
                    if (stats) {
1347
3
                        ++stats->num_corrected;
1348
3
                    }
1349
3
                } else {
1350
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1351
0
                        LOG_WARNING(
1352
0
                                "failed to commit correction for packed file due to conflict, "
1353
0
                                "retrying")
1354
0
                                .tag("instance_id", instance_id_)
1355
0
                                .tag("packed_file_path", packed_file_path)
1356
0
                                .tag("attempt", attempt);
1357
0
                        sleep_for_packed_file_retry();
1358
0
                        packed_info.Clear();
1359
0
                        continue;
1360
0
                    }
1361
0
                    LOG_WARNING("failed to commit correction for packed file")
1362
0
                            .tag("instance_id", instance_id_)
1363
0
                            .tag("packed_file_path", packed_file_path)
1364
0
                            .tag("attempt", attempt)
1365
0
                            .tag("err", err);
1366
0
                    return -1;
1367
0
                }
1368
3
            }
1369
3
        }
1370
1371
4
        correction_ok = true;
1372
4
        break;
1373
4
    }
1374
1375
4
    if (!correction_ok) {
1376
0
        return -1;
1377
0
    }
1378
1379
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1380
4
          packed_info.ref_cnt() == 0)) {
1381
3
        return 0;
1382
3
    }
1383
1384
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1385
0
        LOG_WARNING("packed file missing resource id when recycling")
1386
0
                .tag("instance_id", instance_id_)
1387
0
                .tag("packed_file_path", packed_file_path);
1388
0
        return -1;
1389
0
    }
1390
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1391
1
    if (!accessor) {
1392
0
        LOG_WARNING("no accessor available to delete packed file")
1393
0
                .tag("instance_id", instance_id_)
1394
0
                .tag("packed_file_path", packed_file_path)
1395
0
                .tag("resource_id", packed_info.resource_id());
1396
0
        return -1;
1397
0
    }
1398
1
    int del_ret = accessor->delete_file(packed_file_path);
1399
1
    if (del_ret != 0 && del_ret != 1) {
1400
0
        LOG_WARNING("failed to delete packed file")
1401
0
                .tag("instance_id", instance_id_)
1402
0
                .tag("packed_file_path", packed_file_path)
1403
0
                .tag("resource_id", resource_id)
1404
0
                .tag("ret", del_ret);
1405
0
        return -1;
1406
0
    }
1407
1
    if (del_ret == 1) {
1408
0
        LOG_INFO("packed file already removed")
1409
0
                .tag("instance_id", instance_id_)
1410
0
                .tag("packed_file_path", packed_file_path)
1411
0
                .tag("resource_id", resource_id);
1412
1
    } else {
1413
1
        LOG_INFO("deleted packed file")
1414
1
                .tag("instance_id", instance_id_)
1415
1
                .tag("packed_file_path", packed_file_path)
1416
1
                .tag("resource_id", resource_id);
1417
1
    }
1418
1419
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1420
1
        std::unique_ptr<Transaction> del_txn;
1421
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1422
1
        if (err != TxnErrorCode::TXN_OK) {
1423
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1424
0
                    .tag("instance_id", instance_id_)
1425
0
                    .tag("packed_file_path", packed_file_path)
1426
0
                    .tag("del_attempt", del_attempt)
1427
0
                    .tag("err", err);
1428
0
            return -1;
1429
0
        }
1430
1431
1
        std::string latest_val;
1432
1
        err = del_txn->get(packed_key, &latest_val);
1433
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1434
0
            return 0;
1435
0
        }
1436
1
        if (err != TxnErrorCode::TXN_OK) {
1437
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1438
0
                    .tag("instance_id", instance_id_)
1439
0
                    .tag("packed_file_path", packed_file_path)
1440
0
                    .tag("del_attempt", del_attempt)
1441
0
                    .tag("err", err);
1442
0
            return -1;
1443
0
        }
1444
1445
1
        cloud::PackedFileInfoPB latest_info;
1446
1
        if (!latest_info.ParseFromString(latest_val)) {
1447
0
            LOG_WARNING("failed to parse packed file info before removal")
1448
0
                    .tag("instance_id", instance_id_)
1449
0
                    .tag("packed_file_path", packed_file_path)
1450
0
                    .tag("del_attempt", del_attempt);
1451
0
            return -1;
1452
0
        }
1453
1454
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1455
1
              latest_info.ref_cnt() == 0)) {
1456
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1457
0
                    .tag("instance_id", instance_id_)
1458
0
                    .tag("packed_file_path", packed_file_path)
1459
0
                    .tag("del_attempt", del_attempt);
1460
0
            return 0;
1461
0
        }
1462
1463
1
        del_txn->remove(packed_key);
1464
1
        err = del_txn->commit();
1465
1
        if (err == TxnErrorCode::TXN_OK) {
1466
1
            if (stats) {
1467
1
                ++stats->num_deleted;
1468
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1469
1
                                        static_cast<int64_t>(latest_val.size());
1470
1
                if (del_ret == 0 || del_ret == 1) {
1471
1
                    ++stats->num_object_deleted;
1472
1
                    int64_t object_size = latest_info.total_slice_bytes();
1473
1
                    if (object_size <= 0) {
1474
0
                        object_size = packed_info.total_slice_bytes();
1475
0
                    }
1476
1
                    stats->bytes_object_deleted += object_size;
1477
1
                }
1478
1
            }
1479
1
            LOG_INFO("removed packed file metadata")
1480
1
                    .tag("instance_id", instance_id_)
1481
1
                    .tag("packed_file_path", packed_file_path);
1482
1
            return 0;
1483
1
        }
1484
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1485
0
            if (del_attempt >= max_retry_times) {
1486
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1487
0
                        .tag("instance_id", instance_id_)
1488
0
                        .tag("packed_file_path", packed_file_path)
1489
0
                        .tag("del_attempt", del_attempt);
1490
0
                return -1;
1491
0
            }
1492
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1493
0
                    .tag("instance_id", instance_id_)
1494
0
                    .tag("packed_file_path", packed_file_path)
1495
0
                    .tag("del_attempt", del_attempt);
1496
0
            sleep_for_packed_file_retry();
1497
0
            continue;
1498
0
        }
1499
0
        LOG_WARNING("failed to remove packed file kv")
1500
0
                .tag("instance_id", instance_id_)
1501
0
                .tag("packed_file_path", packed_file_path)
1502
0
                .tag("del_attempt", del_attempt)
1503
0
                .tag("err", err);
1504
0
        return -1;
1505
0
    }
1506
1507
0
    return -1;
1508
1
}
1509
1510
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1511
4
                                            PackedFileRecycleStats* stats, int* ret) {
1512
4
    if (stats) {
1513
4
        ++stats->num_scanned;
1514
4
    }
1515
4
    std::string packed_file_path;
1516
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1517
0
        LOG_WARNING("failed to decode packed file key")
1518
0
                .tag("instance_id", instance_id_)
1519
0
                .tag("key", hex(key));
1520
0
        if (stats) {
1521
0
            ++stats->num_failed;
1522
0
        }
1523
0
        if (ret) {
1524
0
            *ret = -1;
1525
0
        }
1526
0
        return 0;
1527
0
    }
1528
1529
4
    std::string packed_key(key);
1530
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1531
4
    if (process_ret != 0) {
1532
0
        if (stats) {
1533
0
            ++stats->num_failed;
1534
0
        }
1535
0
        if (ret) {
1536
0
            *ret = -1;
1537
0
        }
1538
0
    }
1539
4
    return 0;
1540
4
}
1541
1542
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1543
6.02k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1544
6.02k
    if (config::force_immediate_recycle) {
1545
15
        return 0L;
1546
15
    }
1547
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1548
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1549
6.00k
    int64_t retention_seconds = config::retention_seconds;
1550
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1551
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1552
4.70k
    }
1553
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1554
6.00k
    if (*earlest_ts > final_expiration) {
1555
5
        *earlest_ts = final_expiration;
1556
5
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1557
5
    }
1558
6.00k
    return final_expiration;
1559
6.02k
}
1560
1561
int64_t calculate_partition_expired_time(
1562
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1563
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1564
9
    if (config::force_immediate_recycle) {
1565
3
        return 0L;
1566
3
    }
1567
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1568
6
                                                            : partition_meta_pb.creation_time();
1569
6
    int64_t retention_seconds = config::retention_seconds;
1570
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1571
6
        retention_seconds =
1572
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1573
6
    }
1574
6
    int64_t final_expiration = expiration + retention_seconds;
1575
6
    if (*earlest_ts > final_expiration) {
1576
2
        *earlest_ts = final_expiration;
1577
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1578
2
    }
1579
6
    return final_expiration;
1580
9
}
1581
1582
int64_t calculate_index_expired_time(const std::string& instance_id_,
1583
                                     const RecycleIndexPB& index_meta_pb,
1584
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1585
10
    if (config::force_immediate_recycle) {
1586
4
        return 0L;
1587
4
    }
1588
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1589
6
                                                        : index_meta_pb.creation_time();
1590
6
    int64_t retention_seconds = config::retention_seconds;
1591
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1592
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1593
6
    }
1594
6
    int64_t final_expiration = expiration + retention_seconds;
1595
6
    if (*earlest_ts > final_expiration) {
1596
2
        *earlest_ts = final_expiration;
1597
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1598
2
    }
1599
6
    return final_expiration;
1600
10
}
1601
1602
int64_t calculate_tmp_rowset_expired_time(
1603
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1604
51.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1605
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1606
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1607
    //  duration or timeout always < `retention_time` in practice.
1608
51.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1609
51.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1610
51.0k
                                 : tmp_rowset_meta_pb.creation_time();
1611
51.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1612
51.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1613
51.0k
    if (*earlest_ts > final_expiration) {
1614
15
        *earlest_ts = final_expiration;
1615
15
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1616
15
    }
1617
51.0k
    return final_expiration;
1618
51.0k
}
1619
1620
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1621
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1622
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1623
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1624
8
        *earlest_ts = final_expiration / 1000;
1625
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1626
8
    }
1627
30.0k
    return final_expiration;
1628
30.0k
}
1629
1630
int64_t calculate_restore_job_expired_time(
1631
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1632
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1633
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1634
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1635
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1636
        // final state, recycle immediately
1637
41
        return 0L;
1638
41
    }
1639
    // not final state, wait much longer than the FE's timeout(1 day)
1640
0
    int64_t last_modified_s =
1641
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1642
0
    int64_t expiration = restore_job.expired_at_s() > 0
1643
0
                                 ? last_modified_s + restore_job.expired_at_s()
1644
0
                                 : last_modified_s;
1645
0
    int64_t final_expiration = expiration + config::retention_seconds;
1646
0
    if (*earlest_ts > final_expiration) {
1647
0
        *earlest_ts = final_expiration;
1648
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1649
0
    }
1650
0
    return final_expiration;
1651
41
}
1652
1653
int get_meta_rowset_key(Transaction* txn, const std::string& instance_id, int64_t tablet_id,
1654
                        const std::string& rowset_id, int64_t start_version, int64_t end_version,
1655
0
                        bool load_key, bool* exist) {
1656
0
    std::string key =
1657
0
            load_key ? versioned::meta_rowset_load_key({instance_id, tablet_id, end_version})
1658
0
                     : versioned::meta_rowset_compact_key({instance_id, tablet_id, end_version});
1659
0
    RowsetMetaCloudPB rowset_meta;
1660
0
    Versionstamp version;
1661
0
    TxnErrorCode err = versioned::document_get(txn, key, &rowset_meta, &version);
1662
0
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1663
0
        VLOG_DEBUG << "not found load or compact meta_rowset_key."
1664
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1665
0
                   << " end_version=" << end_version << " key=" << hex(key);
1666
0
    } else if (err != TxnErrorCode::TXN_OK) {
1667
0
        LOG_INFO("failed to get load or compact meta_rowset_key.")
1668
0
                .tag("rowset_id", rowset_id)
1669
0
                .tag("start_version", start_version)
1670
0
                .tag("end_version", end_version)
1671
0
                .tag("key", hex(key))
1672
0
                .tag("error_code", err);
1673
0
        return -1;
1674
0
    } else if (rowset_meta.rowset_id_v2() == rowset_id) {
1675
0
        *exist = true;
1676
0
        VLOG_DEBUG << "found load or compact meta_rowset_key."
1677
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1678
0
                   << " end_version=" << end_version << " key=" << hex(key);
1679
0
    } else {
1680
0
        VLOG_DEBUG << "rowset_id does not match when find load or compact meta_rowset_key."
1681
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1682
0
                   << " end_version=" << end_version << " key=" << hex(key)
1683
0
                   << " found_rowset_id=" << rowset_meta.rowset_id_v2();
1684
0
    }
1685
0
    return 0;
1686
0
}
1687
1688
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1689
2
    AbortTxnRequest req;
1690
2
    TxnInfoPB txn_info;
1691
2
    MetaServiceCode code = MetaServiceCode::OK;
1692
2
    std::string msg;
1693
2
    std::stringstream ss;
1694
2
    std::unique_ptr<Transaction> txn;
1695
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1696
2
    if (err != TxnErrorCode::TXN_OK) {
1697
0
        LOG_WARNING("failed to create txn").tag("err", err);
1698
0
        return -1;
1699
0
    }
1700
1701
    // get txn index
1702
2
    TxnIndexPB txn_idx_pb;
1703
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1704
2
    std::string index_val;
1705
2
    err = txn->get(index_key, &index_val);
1706
2
    if (err != TxnErrorCode::TXN_OK) {
1707
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1708
            // maybe recycled
1709
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1710
0
                    .tag("key", hex(index_key))
1711
0
                    .tag("txn_id", txn_id);
1712
0
            return 0;
1713
0
        }
1714
0
        LOG_WARNING("failed to get txn index")
1715
0
                .tag("err", err)
1716
0
                .tag("key", hex(index_key))
1717
0
                .tag("txn_id", txn_id);
1718
0
        return -1;
1719
0
    }
1720
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1721
0
        LOG_WARNING("failed to parse txn index")
1722
0
                .tag("err", err)
1723
0
                .tag("key", hex(index_key))
1724
0
                .tag("txn_id", txn_id);
1725
0
        return -1;
1726
0
    }
1727
1728
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1729
2
    std::string info_val;
1730
2
    err = txn->get(info_key, &info_val);
1731
2
    if (err != TxnErrorCode::TXN_OK) {
1732
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1733
            // maybe recycled
1734
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1735
0
                    .tag("key", hex(info_key))
1736
0
                    .tag("txn_id", txn_id);
1737
0
            return 0;
1738
0
        }
1739
0
        LOG_WARNING("failed to get txn info")
1740
0
                .tag("err", err)
1741
0
                .tag("key", hex(info_key))
1742
0
                .tag("txn_id", txn_id);
1743
0
        return -1;
1744
0
    }
1745
2
    if (!txn_info.ParseFromString(info_val)) {
1746
0
        LOG_WARNING("failed to parse txn info")
1747
0
                .tag("err", err)
1748
0
                .tag("key", hex(info_key))
1749
0
                .tag("txn_id", txn_id);
1750
0
        return -1;
1751
0
    }
1752
1753
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1754
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1755
0
                .tag("key", hex(info_key))
1756
0
                .tag("txn_id", txn_id);
1757
0
        return 0;
1758
0
    }
1759
1760
2
    req.set_txn_id(txn_id);
1761
1762
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1763
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1764
1765
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1766
2
    err = txn->commit();
1767
2
    if (err != TxnErrorCode::TXN_OK) {
1768
0
        code = cast_as<ErrCategory::COMMIT>(err);
1769
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1770
0
        msg = ss.str();
1771
0
        return -1;
1772
0
    }
1773
1774
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1775
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1776
2
              << " code=" << code << " msg=" << msg;
1777
1778
2
    return 0;
1779
2
}
1780
1781
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
1782
4
    FinishTabletJobRequest req;
1783
4
    FinishTabletJobResponse res;
1784
4
    req.set_action(FinishTabletJobRequest::ABORT);
1785
4
    MetaServiceCode code = MetaServiceCode::OK;
1786
4
    std::string msg;
1787
4
    std::stringstream ss;
1788
1789
4
    TabletIndexPB tablet_idx;
1790
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
1791
4
    if (ret == 1) {
1792
        // tablet maybe recycled, directly return 0
1793
1
        return 0;
1794
3
    } else if (ret != 0) {
1795
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
1796
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
1797
0
        return ret;
1798
0
    }
1799
1800
3
    std::unique_ptr<Transaction> txn;
1801
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1802
3
    if (err != TxnErrorCode::TXN_OK) {
1803
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
1804
0
        return -1;
1805
0
    }
1806
1807
3
    std::string job_key =
1808
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
1809
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
1810
3
    std::string job_val;
1811
3
    err = txn->get(job_key, &job_val);
1812
3
    if (err != TxnErrorCode::TXN_OK) {
1813
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1814
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
1815
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1816
0
            return 0;
1817
0
        }
1818
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
1819
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
1820
0
                     << " key=" << hex(job_key);
1821
0
        return -1;
1822
0
    }
1823
1824
3
    TabletJobInfoPB job_pb;
1825
3
    if (!job_pb.ParseFromString(job_val)) {
1826
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
1827
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
1828
0
        return -1;
1829
0
    }
1830
1831
3
    std::string job_id {};
1832
3
    if (!job_pb.compaction().empty()) {
1833
2
        for (const auto& c : job_pb.compaction()) {
1834
2
            if (c.id() == rowset_meta.job_id()) {
1835
2
                job_id = c.id();
1836
2
                break;
1837
2
            }
1838
2
        }
1839
2
    } else if (job_pb.has_schema_change()) {
1840
1
        job_id = job_pb.schema_change().id();
1841
1
    }
1842
1843
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
1844
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
1845
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
1846
3
        req.mutable_job()->CopyFrom(job_pb);
1847
3
        req.set_action(FinishTabletJobRequest::ABORT);
1848
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
1849
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
1850
3
                           ss);
1851
3
        if (code != MetaServiceCode::OK) {
1852
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
1853
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
1854
0
                         << " msg=" << msg;
1855
0
            return -1;
1856
0
        }
1857
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
1858
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
1859
3
                  << " code=" << code << " msg=" << msg;
1860
3
    } else {
1861
        // clang-format off
1862
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
1863
0
                  << ", instance_id=" << instance_id_ 
1864
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
1865
0
                  << ", job_id=" << job_id
1866
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
1867
        // clang-format on
1868
0
    }
1869
1870
3
    return 0;
1871
3
}
1872
1873
template <typename T>
1874
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1875
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1876
9
        return rowset_meta_pb.mutable_rowset_meta();
1877
9
    } else {
1878
9
        return &rowset_meta_pb;
1879
9
    }
1880
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
1874
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1875
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1876
4
        return rowset_meta_pb.mutable_rowset_meta();
1877
4
    } else {
1878
4
        return &rowset_meta_pb;
1879
4
    }
1880
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
1874
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
1875
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1876
9
        return rowset_meta_pb.mutable_rowset_meta();
1877
9
    } else {
1878
9
        return &rowset_meta_pb;
1879
9
    }
1880
9
}
1881
1882
template <typename T>
1883
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1884
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1885
35
        return rowset_meta_pb.rowset_meta();
1886
35
    } else {
1887
35
        return rowset_meta_pb;
1888
35
    }
1889
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
1883
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1884
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1885
16
        return rowset_meta_pb.rowset_meta();
1886
16
    } else {
1887
16
        return rowset_meta_pb;
1888
16
    }
1889
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
1883
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
1884
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1885
35
        return rowset_meta_pb.rowset_meta();
1886
35
    } else {
1887
35
        return rowset_meta_pb;
1888
35
    }
1889
35
}
1890
1891
struct DeferredRecycleAbortTask {
1892
    enum class Type : uint8_t {
1893
        TXN,
1894
        JOB,
1895
    };
1896
1897
    Type type = Type::TXN;
1898
    int64_t txn_id = 0;
1899
    int64_t tablet_id = 0;
1900
    int64_t start_version = 0;
1901
    int64_t end_version = 0;
1902
    std::string rowset_id;
1903
    std::string job_id;
1904
};
1905
1906
struct DeferredRecyclePrepareDeleteTask {
1907
    std::string key;
1908
    std::string resource_id;
1909
    std::string rowset_id;
1910
    int64_t tablet_id = 0;
1911
};
1912
1913
template <typename T>
1914
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1915
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1916
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1917
0
            return std::nullopt;
1918
0
        }
1919
4
    }
1920
1921
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1922
4
    DeferredRecycleAbortTask task;
1923
4
    task.tablet_id = rs_meta.tablet_id();
1924
4
    task.start_version = rs_meta.start_version();
1925
4
    task.end_version = rs_meta.end_version();
1926
14
    if (rs_meta.has_load_id()) {
1927
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
1928
4
        task.txn_id = rs_meta.txn_id();
1929
4
        return task;
1930
4
    }
1931
10
    if (rs_meta.has_job_id()) {
1932
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
1933
6
        task.rowset_id = rs_meta.rowset_id_v2();
1934
6
        task.job_id = rs_meta.job_id();
1935
6
        return task;
1936
6
    }
1937
4
    return std::nullopt;
1938
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1914
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1915
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1916
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1917
0
            return std::nullopt;
1918
0
        }
1919
4
    }
1920
1921
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1922
4
    DeferredRecycleAbortTask task;
1923
4
    task.tablet_id = rs_meta.tablet_id();
1924
4
    task.start_version = rs_meta.start_version();
1925
4
    task.end_version = rs_meta.end_version();
1926
4
    if (rs_meta.has_load_id()) {
1927
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1928
2
        task.txn_id = rs_meta.txn_id();
1929
2
        return task;
1930
2
    }
1931
2
    if (rs_meta.has_job_id()) {
1932
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
1933
2
        task.rowset_id = rs_meta.rowset_id_v2();
1934
2
        task.job_id = rs_meta.job_id();
1935
2
        return task;
1936
2
    }
1937
0
    return std::nullopt;
1938
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
1914
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
1915
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
1916
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
1917
10
            return std::nullopt;
1918
10
        }
1919
10
    }
1920
1921
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1922
10
    DeferredRecycleAbortTask task;
1923
10
    task.tablet_id = rs_meta.tablet_id();
1924
10
    task.start_version = rs_meta.start_version();
1925
10
    task.end_version = rs_meta.end_version();
1926
10
    if (rs_meta.has_load_id()) {
1927
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
1928
2
        task.txn_id = rs_meta.txn_id();
1929
2
        return task;
1930
2
    }
1931
8
    if (rs_meta.has_job_id()) {
1932
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
1933
4
        task.rowset_id = rs_meta.rowset_id_v2();
1934
4
        task.job_id = rs_meta.job_id();
1935
4
        return task;
1936
4
    }
1937
4
    return std::nullopt;
1938
8
}
1939
1940
template <typename T>
1941
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1942
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1943
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1944
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
1941
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1942
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1943
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1944
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
1941
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
1942
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
1943
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
1944
25
}
1945
1946
template <typename T>
1947
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
1948
11
                                   const std::vector<std::string>& keys) {
1949
11
    std::unique_ptr<Transaction> txn;
1950
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
1951
11
    if (err != TxnErrorCode::TXN_OK) {
1952
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1953
0
        return -1;
1954
0
    }
1955
11
    std::vector<std::optional<std::string>> values;
1956
11
    err = txn->batch_get(&values, keys);
1957
11
    if (err != TxnErrorCode::TXN_OK) {
1958
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1959
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1960
0
        return -1;
1961
0
    }
1962
11
    size_t total_keys = keys.size();
1963
24
    for (size_t i = 0; i < total_keys; i++) {
1964
13
        if (!values[i].has_value()) {
1965
            // has already been removed by commit_rowset
1966
0
            continue;
1967
0
        }
1968
13
        auto key = keys[i];
1969
13
        auto val = values[i].value();
1970
13
        T rowset_meta_pb;
1971
13
        if (!rowset_meta_pb.ParseFromString(val)) {
1972
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1973
0
                         << " key=" << hex(key);
1974
0
            return -1;
1975
0
        }
1976
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1977
0
            continue;
1978
0
        }
1979
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1980
13
        val.clear();
1981
13
        rowset_meta_pb.SerializeToString(&val);
1982
13
        txn->put(key, val);
1983
13
    }
1984
11
    err = txn->commit();
1985
11
    if (err != TxnErrorCode::TXN_OK) {
1986
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1987
0
        return -1;
1988
0
    }
1989
1990
11
    return 0;
1991
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1948
4
                                   const std::vector<std::string>& keys) {
1949
4
    std::unique_ptr<Transaction> txn;
1950
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
1951
4
    if (err != TxnErrorCode::TXN_OK) {
1952
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1953
0
        return -1;
1954
0
    }
1955
4
    std::vector<std::optional<std::string>> values;
1956
4
    err = txn->batch_get(&values, keys);
1957
4
    if (err != TxnErrorCode::TXN_OK) {
1958
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1959
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1960
0
        return -1;
1961
0
    }
1962
4
    size_t total_keys = keys.size();
1963
8
    for (size_t i = 0; i < total_keys; i++) {
1964
4
        if (!values[i].has_value()) {
1965
            // has already been removed by commit_rowset
1966
0
            continue;
1967
0
        }
1968
4
        auto key = keys[i];
1969
4
        auto val = values[i].value();
1970
4
        T rowset_meta_pb;
1971
4
        if (!rowset_meta_pb.ParseFromString(val)) {
1972
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1973
0
                         << " key=" << hex(key);
1974
0
            return -1;
1975
0
        }
1976
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1977
0
            continue;
1978
0
        }
1979
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1980
4
        val.clear();
1981
4
        rowset_meta_pb.SerializeToString(&val);
1982
4
        txn->put(key, val);
1983
4
    }
1984
4
    err = txn->commit();
1985
4
    if (err != TxnErrorCode::TXN_OK) {
1986
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1987
0
        return -1;
1988
0
    }
1989
1990
4
    return 0;
1991
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
1948
7
                                   const std::vector<std::string>& keys) {
1949
7
    std::unique_ptr<Transaction> txn;
1950
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
1951
7
    if (err != TxnErrorCode::TXN_OK) {
1952
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
1953
0
        return -1;
1954
0
    }
1955
7
    std::vector<std::optional<std::string>> values;
1956
7
    err = txn->batch_get(&values, keys);
1957
7
    if (err != TxnErrorCode::TXN_OK) {
1958
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
1959
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
1960
0
        return -1;
1961
0
    }
1962
7
    size_t total_keys = keys.size();
1963
16
    for (size_t i = 0; i < total_keys; i++) {
1964
9
        if (!values[i].has_value()) {
1965
            // has already been removed by commit_rowset
1966
0
            continue;
1967
0
        }
1968
9
        auto key = keys[i];
1969
9
        auto val = values[i].value();
1970
9
        T rowset_meta_pb;
1971
9
        if (!rowset_meta_pb.ParseFromString(val)) {
1972
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
1973
0
                         << " key=" << hex(key);
1974
0
            return -1;
1975
0
        }
1976
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
1977
0
            continue;
1978
0
        }
1979
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
1980
9
        val.clear();
1981
9
        rowset_meta_pb.SerializeToString(&val);
1982
9
        txn->put(key, val);
1983
9
    }
1984
7
    err = txn->commit();
1985
7
    if (err != TxnErrorCode::TXN_OK) {
1986
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
1987
0
        return -1;
1988
0
    }
1989
1990
7
    return 0;
1991
7
}
1992
1993
template <typename T>
1994
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
1995
                                 const std::vector<std::string>& keys,
1996
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
1997
5
                                 bool skip_base_version) {
1998
5
    constexpr size_t kAbortCheckBatchSize = 256;
1999
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2000
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2001
5
        std::unique_ptr<Transaction> txn;
2002
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2003
5
        if (err != TxnErrorCode::TXN_OK) {
2004
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2005
0
            return -1;
2006
0
        }
2007
10
        for (size_t idx = offset; idx < limit; ++idx) {
2008
5
            const std::string& key = keys[idx];
2009
5
            std::string val;
2010
5
            err = txn->get(key, &val);
2011
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2012
                // has already been removed
2013
0
                continue;
2014
0
            }
2015
5
            if (err != TxnErrorCode::TXN_OK) {
2016
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2017
0
                             << " key=" << hex(key);
2018
0
                return -1;
2019
0
            }
2020
5
            T rowset_meta_pb;
2021
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2022
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2023
0
                             << " key=" << hex(key);
2024
0
                return -1;
2025
0
            }
2026
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2027
0
                continue;
2028
0
            }
2029
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2030
5
                abort_task.has_value()) {
2031
5
                abort_tasks->emplace_back(std::move(*abort_task));
2032
5
            }
2033
5
        }
2034
5
    }
2035
5
    return 0;
2036
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
1997
2
                                 bool skip_base_version) {
1998
2
    constexpr size_t kAbortCheckBatchSize = 256;
1999
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2000
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2001
2
        std::unique_ptr<Transaction> txn;
2002
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2003
2
        if (err != TxnErrorCode::TXN_OK) {
2004
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2005
0
            return -1;
2006
0
        }
2007
4
        for (size_t idx = offset; idx < limit; ++idx) {
2008
2
            const std::string& key = keys[idx];
2009
2
            std::string val;
2010
2
            err = txn->get(key, &val);
2011
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2012
                // has already been removed
2013
0
                continue;
2014
0
            }
2015
2
            if (err != TxnErrorCode::TXN_OK) {
2016
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2017
0
                             << " key=" << hex(key);
2018
0
                return -1;
2019
0
            }
2020
2
            T rowset_meta_pb;
2021
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2022
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2023
0
                             << " key=" << hex(key);
2024
0
                return -1;
2025
0
            }
2026
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2027
0
                continue;
2028
0
            }
2029
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2030
2
                abort_task.has_value()) {
2031
2
                abort_tasks->emplace_back(std::move(*abort_task));
2032
2
            }
2033
2
        }
2034
2
    }
2035
2
    return 0;
2036
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
1997
3
                                 bool skip_base_version) {
1998
3
    constexpr size_t kAbortCheckBatchSize = 256;
1999
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2000
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2001
3
        std::unique_ptr<Transaction> txn;
2002
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2003
3
        if (err != TxnErrorCode::TXN_OK) {
2004
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2005
0
            return -1;
2006
0
        }
2007
6
        for (size_t idx = offset; idx < limit; ++idx) {
2008
3
            const std::string& key = keys[idx];
2009
3
            std::string val;
2010
3
            err = txn->get(key, &val);
2011
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2012
                // has already been removed
2013
0
                continue;
2014
0
            }
2015
3
            if (err != TxnErrorCode::TXN_OK) {
2016
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2017
0
                             << " key=" << hex(key);
2018
0
                return -1;
2019
0
            }
2020
3
            T rowset_meta_pb;
2021
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2022
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2023
0
                             << " key=" << hex(key);
2024
0
                return -1;
2025
0
            }
2026
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2027
0
                continue;
2028
0
            }
2029
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2030
3
                abort_task.has_value()) {
2031
3
                abort_tasks->emplace_back(std::move(*abort_task));
2032
3
            }
2033
3
        }
2034
3
    }
2035
3
    return 0;
2036
3
}
2037
2038
template <typename T>
2039
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2040
5
                                                         bool skip_base_version) {
2041
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2042
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2043
5
                                        skip_base_version) != 0) {
2044
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2045
0
        return -1;
2046
0
    }
2047
5
    for (const auto& abort_task : abort_tasks) {
2048
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2049
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2050
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2051
5
        int abort_ret = 0;
2052
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2053
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2054
3
        } else {
2055
3
            RowsetMetaCloudPB rowset_meta;
2056
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2057
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2058
3
            rowset_meta.set_job_id(abort_task.job_id);
2059
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2060
3
        }
2061
5
        if (abort_ret != 0) {
2062
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2063
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2064
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2065
0
            return abort_ret;
2066
0
        }
2067
5
    }
2068
5
    return 0;
2069
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2040
2
                                                         bool skip_base_version) {
2041
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2042
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2043
2
                                        skip_base_version) != 0) {
2044
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2045
0
        return -1;
2046
0
    }
2047
2
    for (const auto& abort_task : abort_tasks) {
2048
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2049
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2050
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2051
2
        int abort_ret = 0;
2052
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2053
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2054
1
        } else {
2055
1
            RowsetMetaCloudPB rowset_meta;
2056
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2057
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2058
1
            rowset_meta.set_job_id(abort_task.job_id);
2059
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2060
1
        }
2061
2
        if (abort_ret != 0) {
2062
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2063
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2064
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2065
0
            return abort_ret;
2066
0
        }
2067
2
    }
2068
2
    return 0;
2069
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2040
3
                                                         bool skip_base_version) {
2041
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2042
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2043
3
                                        skip_base_version) != 0) {
2044
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2045
0
        return -1;
2046
0
    }
2047
3
    for (const auto& abort_task : abort_tasks) {
2048
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2049
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2050
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2051
3
        int abort_ret = 0;
2052
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2053
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2054
2
        } else {
2055
2
            RowsetMetaCloudPB rowset_meta;
2056
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2057
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2058
2
            rowset_meta.set_job_id(abort_task.job_id);
2059
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2060
2
        }
2061
3
        if (abort_ret != 0) {
2062
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2063
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2064
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2065
0
            return abort_ret;
2066
0
        }
2067
3
    }
2068
3
    return 0;
2069
3
}
2070
2071
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2072
                                 const std::vector<std::string>& keys,
2073
24
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2074
24
    constexpr size_t kPrepareCheckBatchSize = 256;
2075
48
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2076
24
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2077
24
        std::unique_ptr<Transaction> txn;
2078
24
        TxnErrorCode err = txn_kv->create_txn(&txn);
2079
24
        if (err != TxnErrorCode::TXN_OK) {
2080
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2081
0
            return -1;
2082
0
        }
2083
677
        for (size_t idx = offset; idx < limit; ++idx) {
2084
653
            const std::string& key = keys[idx];
2085
653
            std::string val;
2086
653
            err = txn->get(key, &val);
2087
653
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2088
                // has already been removed
2089
0
                continue;
2090
0
            }
2091
653
            if (err != TxnErrorCode::TXN_OK) {
2092
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2093
0
                             << " key=" << hex(key);
2094
0
                return -1;
2095
0
            }
2096
653
            RecycleRowsetPB rowset;
2097
653
            if (!rowset.ParseFromString(val)) {
2098
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2099
0
                             << " key=" << hex(key);
2100
0
                return -1;
2101
0
            }
2102
653
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2103
0
                continue;
2104
0
            }
2105
653
            const auto& rs_meta = rowset.rowset_meta();
2106
653
            delete_tasks->push_back(
2107
653
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2108
653
        }
2109
24
    }
2110
24
    return 0;
2111
24
}
2112
2113
0
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2114
0
    const std::string task_name = "recycle_ref_rowsets";
2115
0
    *has_unrecycled_rowsets = false;
2116
2117
0
    std::string data_rowset_ref_count_key_start =
2118
0
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2119
0
    std::string data_rowset_ref_count_key_end =
2120
0
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2121
2122
0
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2123
2124
0
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2125
0
    register_recycle_task(task_name, start_time);
2126
2127
0
    DORIS_CLOUD_DEFER {
2128
0
        unregister_recycle_task(task_name);
2129
0
        int64_t cost =
2130
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2131
0
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2132
0
                .tag("instance_id", instance_id_);
2133
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
2134
2135
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2136
0
    std::set<int64_t> tablets_with_refs;
2137
0
    int64_t num_scanned = 0;
2138
2139
0
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2140
0
        ++num_scanned;
2141
0
        int64_t tablet_id;
2142
0
        std::string rowset_id;
2143
0
        std::string_view key(k);
2144
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2145
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2146
0
            return 0; // Continue scanning
2147
0
        }
2148
2149
0
        tablets_with_refs.insert(tablet_id);
2150
0
        return 0;
2151
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2152
2153
0
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2154
0
                         std::move(scan_func)) != 0) {
2155
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2156
0
        return -1;
2157
0
    }
2158
2159
0
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2160
0
             tablets_with_refs.size(), num_scanned)
2161
0
            .tag("instance_id", instance_id_);
2162
2163
    // Phase 2: Recycle each tablet
2164
0
    int64_t num_recycled_tablets = 0;
2165
0
    for (int64_t tablet_id : tablets_with_refs) {
2166
0
        if (stopped()) {
2167
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2168
0
                    .tag("instance_id", instance_id_)
2169
0
                    .tag("tablets_processed", num_recycled_tablets)
2170
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2171
0
            break;
2172
0
        }
2173
2174
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2175
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2176
0
            LOG_WARNING("failed to recycle tablet")
2177
0
                    .tag("instance_id", instance_id_)
2178
0
                    .tag("tablet_id", tablet_id);
2179
0
            return -1;
2180
0
        }
2181
0
        ++num_recycled_tablets;
2182
0
    }
2183
2184
0
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2185
0
            .tag("instance_id", instance_id_)
2186
0
            .tag("total_tablets", tablets_with_refs.size());
2187
2188
    // Phase 3: Scan again to check if any ref count keys still exist
2189
0
    std::unique_ptr<Transaction> txn;
2190
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2191
0
    if (err != TxnErrorCode::TXN_OK) {
2192
0
        LOG_WARNING("failed to create txn for final check")
2193
0
                .tag("instance_id", instance_id_)
2194
0
                .tag("err", err);
2195
0
        return -1;
2196
0
    }
2197
2198
0
    std::unique_ptr<RangeGetIterator> iter;
2199
0
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2200
0
    if (err != TxnErrorCode::TXN_OK) {
2201
0
        LOG_WARNING("failed to create range iterator for final check")
2202
0
                .tag("instance_id", instance_id_)
2203
0
                .tag("err", err);
2204
0
        return -1;
2205
0
    }
2206
2207
0
    *has_unrecycled_rowsets = iter->has_next();
2208
0
    if (*has_unrecycled_rowsets) {
2209
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2210
0
                .tag("instance_id", instance_id_);
2211
0
    }
2212
2213
0
    return 0;
2214
0
}
2215
2216
17
int InstanceRecycler::recycle_indexes() {
2217
17
    const std::string task_name = "recycle_indexes";
2218
17
    int64_t num_scanned = 0;
2219
17
    int64_t num_expired = 0;
2220
17
    int64_t num_recycled = 0;
2221
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2222
2223
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2224
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2225
17
    std::string index_key0;
2226
17
    std::string index_key1;
2227
17
    recycle_index_key(index_key_info0, &index_key0);
2228
17
    recycle_index_key(index_key_info1, &index_key1);
2229
2230
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2231
2232
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2233
17
    register_recycle_task(task_name, start_time);
2234
2235
17
    DORIS_CLOUD_DEFER {
2236
17
        unregister_recycle_task(task_name);
2237
17
        int64_t cost =
2238
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2239
17
        metrics_context.finish_report();
2240
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2241
17
                .tag("instance_id", instance_id_)
2242
17
                .tag("num_scanned", num_scanned)
2243
17
                .tag("num_expired", num_expired)
2244
17
                .tag("num_recycled", num_recycled);
2245
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2235
2
    DORIS_CLOUD_DEFER {
2236
2
        unregister_recycle_task(task_name);
2237
2
        int64_t cost =
2238
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2239
2
        metrics_context.finish_report();
2240
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2241
2
                .tag("instance_id", instance_id_)
2242
2
                .tag("num_scanned", num_scanned)
2243
2
                .tag("num_expired", num_expired)
2244
2
                .tag("num_recycled", num_recycled);
2245
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2235
15
    DORIS_CLOUD_DEFER {
2236
15
        unregister_recycle_task(task_name);
2237
15
        int64_t cost =
2238
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2239
15
        metrics_context.finish_report();
2240
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2241
15
                .tag("instance_id", instance_id_)
2242
15
                .tag("num_scanned", num_scanned)
2243
15
                .tag("num_expired", num_expired)
2244
15
                .tag("num_recycled", num_recycled);
2245
15
    };
2246
2247
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2248
2249
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2250
17
    std::vector<std::string_view> index_keys;
2251
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2252
10
        ++num_scanned;
2253
10
        RecycleIndexPB index_pb;
2254
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2255
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2256
0
            return -1;
2257
0
        }
2258
10
        int64_t current_time = ::time(nullptr);
2259
10
        if (current_time <
2260
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2261
0
            return 0;
2262
0
        }
2263
10
        ++num_expired;
2264
        // decode index_id
2265
10
        auto k1 = k;
2266
10
        k1.remove_prefix(1);
2267
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2268
10
        decode_key(&k1, &out);
2269
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2270
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2271
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2272
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2273
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2274
        // Change state to RECYCLING
2275
10
        std::unique_ptr<Transaction> txn;
2276
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2277
10
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG_WARNING("failed to create txn").tag("err", err);
2279
0
            return -1;
2280
0
        }
2281
10
        std::string val;
2282
10
        err = txn->get(k, &val);
2283
10
        if (err ==
2284
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2285
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2286
0
            return 0;
2287
0
        }
2288
10
        if (err != TxnErrorCode::TXN_OK) {
2289
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2290
0
            return -1;
2291
0
        }
2292
10
        index_pb.Clear();
2293
10
        if (!index_pb.ParseFromString(val)) {
2294
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2295
0
            return -1;
2296
0
        }
2297
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2298
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2299
9
            txn->put(k, index_pb.SerializeAsString());
2300
9
            err = txn->commit();
2301
9
            if (err != TxnErrorCode::TXN_OK) {
2302
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2303
0
                return -1;
2304
0
            }
2305
9
        }
2306
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2307
1
            LOG_WARNING("failed to recycle tablets under index")
2308
1
                    .tag("table_id", index_pb.table_id())
2309
1
                    .tag("instance_id", instance_id_)
2310
1
                    .tag("index_id", index_id);
2311
1
            return -1;
2312
1
        }
2313
2314
9
        if (index_pb.has_db_id()) {
2315
            // Recycle the versioned keys
2316
3
            std::unique_ptr<Transaction> txn;
2317
3
            err = txn_kv_->create_txn(&txn);
2318
3
            if (err != TxnErrorCode::TXN_OK) {
2319
0
                LOG_WARNING("failed to create txn").tag("err", err);
2320
0
                return -1;
2321
0
            }
2322
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2323
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2324
3
            std::string index_inverted_key = versioned::index_inverted_key(
2325
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2326
3
            versioned_remove_all(txn.get(), meta_key);
2327
3
            txn->remove(index_key);
2328
3
            txn->remove(index_inverted_key);
2329
3
            err = txn->commit();
2330
3
            if (err != TxnErrorCode::TXN_OK) {
2331
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2332
0
                return -1;
2333
0
            }
2334
3
        }
2335
2336
9
        metrics_context.total_recycled_num = ++num_recycled;
2337
9
        metrics_context.report();
2338
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2339
9
        index_keys.push_back(k);
2340
9
        return 0;
2341
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2251
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2252
2
        ++num_scanned;
2253
2
        RecycleIndexPB index_pb;
2254
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2255
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2256
0
            return -1;
2257
0
        }
2258
2
        int64_t current_time = ::time(nullptr);
2259
2
        if (current_time <
2260
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2261
0
            return 0;
2262
0
        }
2263
2
        ++num_expired;
2264
        // decode index_id
2265
2
        auto k1 = k;
2266
2
        k1.remove_prefix(1);
2267
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2268
2
        decode_key(&k1, &out);
2269
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2270
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2271
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2272
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2273
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2274
        // Change state to RECYCLING
2275
2
        std::unique_ptr<Transaction> txn;
2276
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2277
2
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG_WARNING("failed to create txn").tag("err", err);
2279
0
            return -1;
2280
0
        }
2281
2
        std::string val;
2282
2
        err = txn->get(k, &val);
2283
2
        if (err ==
2284
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2285
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2286
0
            return 0;
2287
0
        }
2288
2
        if (err != TxnErrorCode::TXN_OK) {
2289
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2290
0
            return -1;
2291
0
        }
2292
2
        index_pb.Clear();
2293
2
        if (!index_pb.ParseFromString(val)) {
2294
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2295
0
            return -1;
2296
0
        }
2297
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2298
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2299
1
            txn->put(k, index_pb.SerializeAsString());
2300
1
            err = txn->commit();
2301
1
            if (err != TxnErrorCode::TXN_OK) {
2302
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2303
0
                return -1;
2304
0
            }
2305
1
        }
2306
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2307
1
            LOG_WARNING("failed to recycle tablets under index")
2308
1
                    .tag("table_id", index_pb.table_id())
2309
1
                    .tag("instance_id", instance_id_)
2310
1
                    .tag("index_id", index_id);
2311
1
            return -1;
2312
1
        }
2313
2314
1
        if (index_pb.has_db_id()) {
2315
            // Recycle the versioned keys
2316
1
            std::unique_ptr<Transaction> txn;
2317
1
            err = txn_kv_->create_txn(&txn);
2318
1
            if (err != TxnErrorCode::TXN_OK) {
2319
0
                LOG_WARNING("failed to create txn").tag("err", err);
2320
0
                return -1;
2321
0
            }
2322
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2323
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2324
1
            std::string index_inverted_key = versioned::index_inverted_key(
2325
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2326
1
            versioned_remove_all(txn.get(), meta_key);
2327
1
            txn->remove(index_key);
2328
1
            txn->remove(index_inverted_key);
2329
1
            err = txn->commit();
2330
1
            if (err != TxnErrorCode::TXN_OK) {
2331
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2332
0
                return -1;
2333
0
            }
2334
1
        }
2335
2336
1
        metrics_context.total_recycled_num = ++num_recycled;
2337
1
        metrics_context.report();
2338
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2339
1
        index_keys.push_back(k);
2340
1
        return 0;
2341
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2251
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2252
8
        ++num_scanned;
2253
8
        RecycleIndexPB index_pb;
2254
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2255
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2256
0
            return -1;
2257
0
        }
2258
8
        int64_t current_time = ::time(nullptr);
2259
8
        if (current_time <
2260
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2261
0
            return 0;
2262
0
        }
2263
8
        ++num_expired;
2264
        // decode index_id
2265
8
        auto k1 = k;
2266
8
        k1.remove_prefix(1);
2267
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2268
8
        decode_key(&k1, &out);
2269
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2270
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2271
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2272
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2273
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2274
        // Change state to RECYCLING
2275
8
        std::unique_ptr<Transaction> txn;
2276
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2277
8
        if (err != TxnErrorCode::TXN_OK) {
2278
0
            LOG_WARNING("failed to create txn").tag("err", err);
2279
0
            return -1;
2280
0
        }
2281
8
        std::string val;
2282
8
        err = txn->get(k, &val);
2283
8
        if (err ==
2284
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2285
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2286
0
            return 0;
2287
0
        }
2288
8
        if (err != TxnErrorCode::TXN_OK) {
2289
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2290
0
            return -1;
2291
0
        }
2292
8
        index_pb.Clear();
2293
8
        if (!index_pb.ParseFromString(val)) {
2294
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2295
0
            return -1;
2296
0
        }
2297
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2298
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2299
8
            txn->put(k, index_pb.SerializeAsString());
2300
8
            err = txn->commit();
2301
8
            if (err != TxnErrorCode::TXN_OK) {
2302
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2303
0
                return -1;
2304
0
            }
2305
8
        }
2306
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2307
0
            LOG_WARNING("failed to recycle tablets under index")
2308
0
                    .tag("table_id", index_pb.table_id())
2309
0
                    .tag("instance_id", instance_id_)
2310
0
                    .tag("index_id", index_id);
2311
0
            return -1;
2312
0
        }
2313
2314
8
        if (index_pb.has_db_id()) {
2315
            // Recycle the versioned keys
2316
2
            std::unique_ptr<Transaction> txn;
2317
2
            err = txn_kv_->create_txn(&txn);
2318
2
            if (err != TxnErrorCode::TXN_OK) {
2319
0
                LOG_WARNING("failed to create txn").tag("err", err);
2320
0
                return -1;
2321
0
            }
2322
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2323
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2324
2
            std::string index_inverted_key = versioned::index_inverted_key(
2325
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2326
2
            versioned_remove_all(txn.get(), meta_key);
2327
2
            txn->remove(index_key);
2328
2
            txn->remove(index_inverted_key);
2329
2
            err = txn->commit();
2330
2
            if (err != TxnErrorCode::TXN_OK) {
2331
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2332
0
                return -1;
2333
0
            }
2334
2
        }
2335
2336
8
        metrics_context.total_recycled_num = ++num_recycled;
2337
8
        metrics_context.report();
2338
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2339
8
        index_keys.push_back(k);
2340
8
        return 0;
2341
8
    };
2342
2343
17
    auto loop_done = [&index_keys, this]() -> int {
2344
6
        if (index_keys.empty()) return 0;
2345
5
        DORIS_CLOUD_DEFER {
2346
5
            index_keys.clear();
2347
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2345
1
        DORIS_CLOUD_DEFER {
2346
1
            index_keys.clear();
2347
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2345
4
        DORIS_CLOUD_DEFER {
2346
4
            index_keys.clear();
2347
4
        };
2348
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2349
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2350
0
            return -1;
2351
0
        }
2352
5
        return 0;
2353
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2343
2
    auto loop_done = [&index_keys, this]() -> int {
2344
2
        if (index_keys.empty()) return 0;
2345
1
        DORIS_CLOUD_DEFER {
2346
1
            index_keys.clear();
2347
1
        };
2348
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2349
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2350
0
            return -1;
2351
0
        }
2352
1
        return 0;
2353
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2343
4
    auto loop_done = [&index_keys, this]() -> int {
2344
4
        if (index_keys.empty()) return 0;
2345
4
        DORIS_CLOUD_DEFER {
2346
4
            index_keys.clear();
2347
4
        };
2348
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2349
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2350
0
            return -1;
2351
0
        }
2352
4
        return 0;
2353
4
    };
2354
2355
17
    if (config::enable_recycler_stats_metrics) {
2356
0
        scan_and_statistics_indexes();
2357
0
    }
2358
    // recycle_func and loop_done for scan and recycle
2359
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2360
17
}
2361
2362
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2363
8.25k
                             int64_t tablet_id) {
2364
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2365
2366
8.25k
    std::unique_ptr<Transaction> txn;
2367
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2368
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2369
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2370
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2371
0
        return false;
2372
0
    }
2373
2374
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2375
8.25k
    std::string tablet_idx_val;
2376
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2377
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2378
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2379
0
                     << " tablet_id=" << tablet_id << " err=" << err
2380
0
                     << " key=" << hex(tablet_idx_key);
2381
0
        return false;
2382
0
    }
2383
2384
8.25k
    TabletIndexPB tablet_idx_pb;
2385
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2386
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2387
0
                     << " tablet_id=" << tablet_id;
2388
0
        return false;
2389
0
    }
2390
2391
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2392
        // In the previous version, the db_id was not set in the index_pb.
2393
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2394
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2395
0
                  << " instance_id=" << instance_id
2396
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2397
0
        return true;
2398
0
    }
2399
2400
8.25k
    std::string ver_val;
2401
8.25k
    std::string ver_key =
2402
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2403
8.25k
                                   tablet_idx_pb.partition_id()});
2404
8.25k
    err = txn->get(ver_key, &ver_val);
2405
2406
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2407
214
        LOG(INFO) << ""
2408
214
                     "partition version not found, instance_id="
2409
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2410
214
                  << " table_id=" << tablet_idx_pb.table_id()
2411
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2412
214
                  << " key=" << hex(ver_key);
2413
214
        return true;
2414
214
    }
2415
2416
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2417
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2418
0
                     << " db_id=" << tablet_idx_pb.db_id()
2419
0
                     << " table_id=" << tablet_idx_pb.table_id()
2420
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2421
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2422
0
        return false;
2423
0
    }
2424
2425
8.03k
    VersionPB version_pb;
2426
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2427
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2428
0
                     << " db_id=" << tablet_idx_pb.db_id()
2429
0
                     << " table_id=" << tablet_idx_pb.table_id()
2430
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2431
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2432
0
        return false;
2433
0
    }
2434
2435
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2436
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2437
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2438
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2439
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2440
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2441
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2442
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2443
4.00k
                     << " key=" << hex(ver_key);
2444
4.00k
        return false;
2445
4.00k
    }
2446
4.03k
    return true;
2447
8.03k
}
2448
2449
15
int InstanceRecycler::recycle_partitions() {
2450
15
    const std::string task_name = "recycle_partitions";
2451
15
    int64_t num_scanned = 0;
2452
15
    int64_t num_expired = 0;
2453
15
    int64_t num_recycled = 0;
2454
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2455
2456
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2457
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2458
15
    std::string part_key0;
2459
15
    std::string part_key1;
2460
15
    recycle_partition_key(part_key_info0, &part_key0);
2461
15
    recycle_partition_key(part_key_info1, &part_key1);
2462
2463
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2464
2465
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2466
15
    register_recycle_task(task_name, start_time);
2467
2468
15
    DORIS_CLOUD_DEFER {
2469
15
        unregister_recycle_task(task_name);
2470
15
        int64_t cost =
2471
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2472
15
        metrics_context.finish_report();
2473
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2474
15
                .tag("instance_id", instance_id_)
2475
15
                .tag("num_scanned", num_scanned)
2476
15
                .tag("num_expired", num_expired)
2477
15
                .tag("num_recycled", num_recycled);
2478
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2468
2
    DORIS_CLOUD_DEFER {
2469
2
        unregister_recycle_task(task_name);
2470
2
        int64_t cost =
2471
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2472
2
        metrics_context.finish_report();
2473
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2474
2
                .tag("instance_id", instance_id_)
2475
2
                .tag("num_scanned", num_scanned)
2476
2
                .tag("num_expired", num_expired)
2477
2
                .tag("num_recycled", num_recycled);
2478
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2468
13
    DORIS_CLOUD_DEFER {
2469
13
        unregister_recycle_task(task_name);
2470
13
        int64_t cost =
2471
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2472
13
        metrics_context.finish_report();
2473
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2474
13
                .tag("instance_id", instance_id_)
2475
13
                .tag("num_scanned", num_scanned)
2476
13
                .tag("num_expired", num_expired)
2477
13
                .tag("num_recycled", num_recycled);
2478
13
    };
2479
2480
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2481
2482
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2483
15
    std::vector<std::string_view> partition_keys;
2484
15
    std::vector<std::string> partition_version_keys;
2485
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2486
9
        ++num_scanned;
2487
9
        RecyclePartitionPB part_pb;
2488
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2489
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2490
0
            return -1;
2491
0
        }
2492
9
        int64_t current_time = ::time(nullptr);
2493
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2494
9
                                                            &earlest_ts)) { // not expired
2495
0
            return 0;
2496
0
        }
2497
9
        ++num_expired;
2498
        // decode partition_id
2499
9
        auto k1 = k;
2500
9
        k1.remove_prefix(1);
2501
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2502
9
        decode_key(&k1, &out);
2503
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2504
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2505
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2506
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2507
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2508
        // Change state to RECYCLING
2509
9
        std::unique_ptr<Transaction> txn;
2510
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2511
9
        if (err != TxnErrorCode::TXN_OK) {
2512
0
            LOG_WARNING("failed to create txn").tag("err", err);
2513
0
            return -1;
2514
0
        }
2515
9
        std::string val;
2516
9
        err = txn->get(k, &val);
2517
9
        if (err ==
2518
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2519
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2520
0
            return 0;
2521
0
        }
2522
9
        if (err != TxnErrorCode::TXN_OK) {
2523
0
            LOG_WARNING("failed to get kv");
2524
0
            return -1;
2525
0
        }
2526
9
        part_pb.Clear();
2527
9
        if (!part_pb.ParseFromString(val)) {
2528
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2529
0
            return -1;
2530
0
        }
2531
        // Partitions with PREPARED state MUST have no data
2532
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2533
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2534
8
            txn->put(k, part_pb.SerializeAsString());
2535
8
            err = txn->commit();
2536
8
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to commit txn: {}", err);
2538
0
                return -1;
2539
0
            }
2540
8
        }
2541
2542
9
        int ret = 0;
2543
33
        for (int64_t index_id : part_pb.index_id()) {
2544
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2545
1
                LOG_WARNING("failed to recycle tablets under partition")
2546
1
                        .tag("table_id", part_pb.table_id())
2547
1
                        .tag("instance_id", instance_id_)
2548
1
                        .tag("index_id", index_id)
2549
1
                        .tag("partition_id", partition_id);
2550
1
                ret = -1;
2551
1
            }
2552
33
        }
2553
9
        if (ret == 0 && part_pb.has_db_id()) {
2554
            // Recycle the versioned keys
2555
8
            std::unique_ptr<Transaction> txn;
2556
8
            err = txn_kv_->create_txn(&txn);
2557
8
            if (err != TxnErrorCode::TXN_OK) {
2558
0
                LOG_WARNING("failed to create txn").tag("err", err);
2559
0
                return -1;
2560
0
            }
2561
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2562
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2563
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2564
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2565
8
            std::string partition_version_key =
2566
8
                    versioned::partition_version_key({instance_id_, partition_id});
2567
8
            versioned_remove_all(txn.get(), meta_key);
2568
8
            txn->remove(index_key);
2569
8
            txn->remove(inverted_index_key);
2570
8
            versioned_remove_all(txn.get(), partition_version_key);
2571
8
            err = txn->commit();
2572
8
            if (err != TxnErrorCode::TXN_OK) {
2573
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2574
0
                return -1;
2575
0
            }
2576
8
        }
2577
2578
9
        if (ret == 0) {
2579
8
            ++num_recycled;
2580
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2581
8
            partition_keys.push_back(k);
2582
8
            if (part_pb.db_id() > 0) {
2583
8
                partition_version_keys.push_back(partition_version_key(
2584
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2585
8
            }
2586
8
            metrics_context.total_recycled_num = num_recycled;
2587
8
            metrics_context.report();
2588
8
        }
2589
9
        return ret;
2590
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2485
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2486
2
        ++num_scanned;
2487
2
        RecyclePartitionPB part_pb;
2488
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2489
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2490
0
            return -1;
2491
0
        }
2492
2
        int64_t current_time = ::time(nullptr);
2493
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2494
2
                                                            &earlest_ts)) { // not expired
2495
0
            return 0;
2496
0
        }
2497
2
        ++num_expired;
2498
        // decode partition_id
2499
2
        auto k1 = k;
2500
2
        k1.remove_prefix(1);
2501
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2502
2
        decode_key(&k1, &out);
2503
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2504
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2505
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2506
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2507
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2508
        // Change state to RECYCLING
2509
2
        std::unique_ptr<Transaction> txn;
2510
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2511
2
        if (err != TxnErrorCode::TXN_OK) {
2512
0
            LOG_WARNING("failed to create txn").tag("err", err);
2513
0
            return -1;
2514
0
        }
2515
2
        std::string val;
2516
2
        err = txn->get(k, &val);
2517
2
        if (err ==
2518
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2519
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2520
0
            return 0;
2521
0
        }
2522
2
        if (err != TxnErrorCode::TXN_OK) {
2523
0
            LOG_WARNING("failed to get kv");
2524
0
            return -1;
2525
0
        }
2526
2
        part_pb.Clear();
2527
2
        if (!part_pb.ParseFromString(val)) {
2528
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2529
0
            return -1;
2530
0
        }
2531
        // Partitions with PREPARED state MUST have no data
2532
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2533
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2534
1
            txn->put(k, part_pb.SerializeAsString());
2535
1
            err = txn->commit();
2536
1
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to commit txn: {}", err);
2538
0
                return -1;
2539
0
            }
2540
1
        }
2541
2542
2
        int ret = 0;
2543
2
        for (int64_t index_id : part_pb.index_id()) {
2544
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2545
1
                LOG_WARNING("failed to recycle tablets under partition")
2546
1
                        .tag("table_id", part_pb.table_id())
2547
1
                        .tag("instance_id", instance_id_)
2548
1
                        .tag("index_id", index_id)
2549
1
                        .tag("partition_id", partition_id);
2550
1
                ret = -1;
2551
1
            }
2552
2
        }
2553
2
        if (ret == 0 && part_pb.has_db_id()) {
2554
            // Recycle the versioned keys
2555
1
            std::unique_ptr<Transaction> txn;
2556
1
            err = txn_kv_->create_txn(&txn);
2557
1
            if (err != TxnErrorCode::TXN_OK) {
2558
0
                LOG_WARNING("failed to create txn").tag("err", err);
2559
0
                return -1;
2560
0
            }
2561
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2562
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2563
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2564
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2565
1
            std::string partition_version_key =
2566
1
                    versioned::partition_version_key({instance_id_, partition_id});
2567
1
            versioned_remove_all(txn.get(), meta_key);
2568
1
            txn->remove(index_key);
2569
1
            txn->remove(inverted_index_key);
2570
1
            versioned_remove_all(txn.get(), partition_version_key);
2571
1
            err = txn->commit();
2572
1
            if (err != TxnErrorCode::TXN_OK) {
2573
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2574
0
                return -1;
2575
0
            }
2576
1
        }
2577
2578
2
        if (ret == 0) {
2579
1
            ++num_recycled;
2580
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2581
1
            partition_keys.push_back(k);
2582
1
            if (part_pb.db_id() > 0) {
2583
1
                partition_version_keys.push_back(partition_version_key(
2584
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2585
1
            }
2586
1
            metrics_context.total_recycled_num = num_recycled;
2587
1
            metrics_context.report();
2588
1
        }
2589
2
        return ret;
2590
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2485
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2486
7
        ++num_scanned;
2487
7
        RecyclePartitionPB part_pb;
2488
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2489
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2490
0
            return -1;
2491
0
        }
2492
7
        int64_t current_time = ::time(nullptr);
2493
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2494
7
                                                            &earlest_ts)) { // not expired
2495
0
            return 0;
2496
0
        }
2497
7
        ++num_expired;
2498
        // decode partition_id
2499
7
        auto k1 = k;
2500
7
        k1.remove_prefix(1);
2501
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2502
7
        decode_key(&k1, &out);
2503
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2504
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2505
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2506
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2507
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2508
        // Change state to RECYCLING
2509
7
        std::unique_ptr<Transaction> txn;
2510
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2511
7
        if (err != TxnErrorCode::TXN_OK) {
2512
0
            LOG_WARNING("failed to create txn").tag("err", err);
2513
0
            return -1;
2514
0
        }
2515
7
        std::string val;
2516
7
        err = txn->get(k, &val);
2517
7
        if (err ==
2518
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2519
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2520
0
            return 0;
2521
0
        }
2522
7
        if (err != TxnErrorCode::TXN_OK) {
2523
0
            LOG_WARNING("failed to get kv");
2524
0
            return -1;
2525
0
        }
2526
7
        part_pb.Clear();
2527
7
        if (!part_pb.ParseFromString(val)) {
2528
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2529
0
            return -1;
2530
0
        }
2531
        // Partitions with PREPARED state MUST have no data
2532
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2533
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2534
7
            txn->put(k, part_pb.SerializeAsString());
2535
7
            err = txn->commit();
2536
7
            if (err != TxnErrorCode::TXN_OK) {
2537
0
                LOG_WARNING("failed to commit txn: {}", err);
2538
0
                return -1;
2539
0
            }
2540
7
        }
2541
2542
7
        int ret = 0;
2543
31
        for (int64_t index_id : part_pb.index_id()) {
2544
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2545
0
                LOG_WARNING("failed to recycle tablets under partition")
2546
0
                        .tag("table_id", part_pb.table_id())
2547
0
                        .tag("instance_id", instance_id_)
2548
0
                        .tag("index_id", index_id)
2549
0
                        .tag("partition_id", partition_id);
2550
0
                ret = -1;
2551
0
            }
2552
31
        }
2553
7
        if (ret == 0 && part_pb.has_db_id()) {
2554
            // Recycle the versioned keys
2555
7
            std::unique_ptr<Transaction> txn;
2556
7
            err = txn_kv_->create_txn(&txn);
2557
7
            if (err != TxnErrorCode::TXN_OK) {
2558
0
                LOG_WARNING("failed to create txn").tag("err", err);
2559
0
                return -1;
2560
0
            }
2561
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2562
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2563
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2564
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2565
7
            std::string partition_version_key =
2566
7
                    versioned::partition_version_key({instance_id_, partition_id});
2567
7
            versioned_remove_all(txn.get(), meta_key);
2568
7
            txn->remove(index_key);
2569
7
            txn->remove(inverted_index_key);
2570
7
            versioned_remove_all(txn.get(), partition_version_key);
2571
7
            err = txn->commit();
2572
7
            if (err != TxnErrorCode::TXN_OK) {
2573
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2574
0
                return -1;
2575
0
            }
2576
7
        }
2577
2578
7
        if (ret == 0) {
2579
7
            ++num_recycled;
2580
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2581
7
            partition_keys.push_back(k);
2582
7
            if (part_pb.db_id() > 0) {
2583
7
                partition_version_keys.push_back(partition_version_key(
2584
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2585
7
            }
2586
7
            metrics_context.total_recycled_num = num_recycled;
2587
7
            metrics_context.report();
2588
7
        }
2589
7
        return ret;
2590
7
    };
2591
2592
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2593
5
        if (partition_keys.empty()) return 0;
2594
4
        DORIS_CLOUD_DEFER {
2595
4
            partition_keys.clear();
2596
4
            partition_version_keys.clear();
2597
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2594
1
        DORIS_CLOUD_DEFER {
2595
1
            partition_keys.clear();
2596
1
            partition_version_keys.clear();
2597
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2594
3
        DORIS_CLOUD_DEFER {
2595
3
            partition_keys.clear();
2596
3
            partition_version_keys.clear();
2597
3
        };
2598
4
        std::unique_ptr<Transaction> txn;
2599
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2600
4
        if (err != TxnErrorCode::TXN_OK) {
2601
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2602
0
            return -1;
2603
0
        }
2604
8
        for (auto& k : partition_keys) {
2605
8
            txn->remove(k);
2606
8
        }
2607
8
        for (auto& k : partition_version_keys) {
2608
8
            txn->remove(k);
2609
8
        }
2610
4
        err = txn->commit();
2611
4
        if (err != TxnErrorCode::TXN_OK) {
2612
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2613
0
                         << " err=" << err;
2614
0
            return -1;
2615
0
        }
2616
4
        return 0;
2617
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2592
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2593
2
        if (partition_keys.empty()) return 0;
2594
1
        DORIS_CLOUD_DEFER {
2595
1
            partition_keys.clear();
2596
1
            partition_version_keys.clear();
2597
1
        };
2598
1
        std::unique_ptr<Transaction> txn;
2599
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2600
1
        if (err != TxnErrorCode::TXN_OK) {
2601
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2602
0
            return -1;
2603
0
        }
2604
1
        for (auto& k : partition_keys) {
2605
1
            txn->remove(k);
2606
1
        }
2607
1
        for (auto& k : partition_version_keys) {
2608
1
            txn->remove(k);
2609
1
        }
2610
1
        err = txn->commit();
2611
1
        if (err != TxnErrorCode::TXN_OK) {
2612
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2613
0
                         << " err=" << err;
2614
0
            return -1;
2615
0
        }
2616
1
        return 0;
2617
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2592
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2593
3
        if (partition_keys.empty()) return 0;
2594
3
        DORIS_CLOUD_DEFER {
2595
3
            partition_keys.clear();
2596
3
            partition_version_keys.clear();
2597
3
        };
2598
3
        std::unique_ptr<Transaction> txn;
2599
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2600
3
        if (err != TxnErrorCode::TXN_OK) {
2601
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2602
0
            return -1;
2603
0
        }
2604
7
        for (auto& k : partition_keys) {
2605
7
            txn->remove(k);
2606
7
        }
2607
7
        for (auto& k : partition_version_keys) {
2608
7
            txn->remove(k);
2609
7
        }
2610
3
        err = txn->commit();
2611
3
        if (err != TxnErrorCode::TXN_OK) {
2612
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2613
0
                         << " err=" << err;
2614
0
            return -1;
2615
0
        }
2616
3
        return 0;
2617
3
    };
2618
2619
15
    if (config::enable_recycler_stats_metrics) {
2620
0
        scan_and_statistics_partitions();
2621
0
    }
2622
    // recycle_func and loop_done for scan and recycle
2623
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2624
15
}
2625
2626
14
int InstanceRecycler::recycle_versions() {
2627
14
    if (should_recycle_versioned_keys()) {
2628
2
        return recycle_orphan_partitions();
2629
2
    }
2630
2631
12
    int64_t num_scanned = 0;
2632
12
    int64_t num_recycled = 0;
2633
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2634
2635
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2636
2637
12
    auto start_time = steady_clock::now();
2638
2639
12
    DORIS_CLOUD_DEFER {
2640
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2641
12
        metrics_context.finish_report();
2642
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2643
12
                .tag("instance_id", instance_id_)
2644
12
                .tag("num_scanned", num_scanned)
2645
12
                .tag("num_recycled", num_recycled);
2646
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2639
12
    DORIS_CLOUD_DEFER {
2640
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2641
12
        metrics_context.finish_report();
2642
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2643
12
                .tag("instance_id", instance_id_)
2644
12
                .tag("num_scanned", num_scanned)
2645
12
                .tag("num_recycled", num_recycled);
2646
12
    };
2647
2648
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2649
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2650
12
    int64_t last_scanned_table_id = 0;
2651
12
    bool is_recycled = false; // Is last scanned kv recycled
2652
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2653
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2654
2
        ++num_scanned;
2655
2
        auto k1 = k;
2656
2
        k1.remove_prefix(1);
2657
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2658
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2659
2
        decode_key(&k1, &out);
2660
2
        DCHECK_EQ(out.size(), 6) << k;
2661
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2662
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2663
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2664
0
            return 0;
2665
0
        }
2666
2
        last_scanned_table_id = table_id;
2667
2
        is_recycled = false;
2668
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2669
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2670
2
        std::unique_ptr<Transaction> txn;
2671
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2672
2
        if (err != TxnErrorCode::TXN_OK) {
2673
0
            return -1;
2674
0
        }
2675
2
        std::unique_ptr<RangeGetIterator> iter;
2676
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2677
2
        if (err != TxnErrorCode::TXN_OK) {
2678
0
            return -1;
2679
0
        }
2680
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2681
1
            return 0;
2682
1
        }
2683
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2684
        // 1. Remove all partition version kvs of this table
2685
1
        auto partition_version_key_begin =
2686
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2687
1
        auto partition_version_key_end =
2688
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2689
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2690
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2691
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2692
1
                     << " table_id=" << table_id;
2693
        // 2. Remove the table version kv of this table
2694
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2695
1
        txn->remove(tbl_version_key);
2696
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2697
        // 3. Remove mow delete bitmap update lock and tablet job lock
2698
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2699
1
        txn->remove(lock_key);
2700
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2701
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2702
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2703
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2704
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2705
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2706
1
                     << " table_id=" << table_id;
2707
1
        err = txn->commit();
2708
1
        if (err != TxnErrorCode::TXN_OK) {
2709
0
            return -1;
2710
0
        }
2711
1
        metrics_context.total_recycled_num = ++num_recycled;
2712
1
        metrics_context.report();
2713
1
        is_recycled = true;
2714
1
        return 0;
2715
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2653
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2654
2
        ++num_scanned;
2655
2
        auto k1 = k;
2656
2
        k1.remove_prefix(1);
2657
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2658
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2659
2
        decode_key(&k1, &out);
2660
2
        DCHECK_EQ(out.size(), 6) << k;
2661
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2662
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2663
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2664
0
            return 0;
2665
0
        }
2666
2
        last_scanned_table_id = table_id;
2667
2
        is_recycled = false;
2668
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2669
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2670
2
        std::unique_ptr<Transaction> txn;
2671
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2672
2
        if (err != TxnErrorCode::TXN_OK) {
2673
0
            return -1;
2674
0
        }
2675
2
        std::unique_ptr<RangeGetIterator> iter;
2676
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2677
2
        if (err != TxnErrorCode::TXN_OK) {
2678
0
            return -1;
2679
0
        }
2680
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2681
1
            return 0;
2682
1
        }
2683
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2684
        // 1. Remove all partition version kvs of this table
2685
1
        auto partition_version_key_begin =
2686
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2687
1
        auto partition_version_key_end =
2688
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2689
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2690
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2691
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2692
1
                     << " table_id=" << table_id;
2693
        // 2. Remove the table version kv of this table
2694
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2695
1
        txn->remove(tbl_version_key);
2696
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2697
        // 3. Remove mow delete bitmap update lock and tablet job lock
2698
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2699
1
        txn->remove(lock_key);
2700
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2701
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2702
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2703
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2704
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2705
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2706
1
                     << " table_id=" << table_id;
2707
1
        err = txn->commit();
2708
1
        if (err != TxnErrorCode::TXN_OK) {
2709
0
            return -1;
2710
0
        }
2711
1
        metrics_context.total_recycled_num = ++num_recycled;
2712
1
        metrics_context.report();
2713
1
        is_recycled = true;
2714
1
        return 0;
2715
1
    };
2716
2717
12
    if (config::enable_recycler_stats_metrics) {
2718
0
        scan_and_statistics_versions();
2719
0
    }
2720
    // recycle_func and loop_done for scan and recycle
2721
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2722
14
}
2723
2724
3
int InstanceRecycler::recycle_orphan_partitions() {
2725
3
    int64_t num_scanned = 0;
2726
3
    int64_t num_recycled = 0;
2727
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2728
2729
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2730
3
            .tag("instance_id", instance_id_);
2731
2732
3
    auto start_time = steady_clock::now();
2733
2734
3
    DORIS_CLOUD_DEFER {
2735
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2736
3
        metrics_context.finish_report();
2737
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2738
3
                .tag("instance_id", instance_id_)
2739
3
                .tag("num_scanned", num_scanned)
2740
3
                .tag("num_recycled", num_recycled);
2741
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2734
3
    DORIS_CLOUD_DEFER {
2735
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2736
3
        metrics_context.finish_report();
2737
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2738
3
                .tag("instance_id", instance_id_)
2739
3
                .tag("num_scanned", num_scanned)
2740
3
                .tag("num_recycled", num_recycled);
2741
3
    };
2742
2743
3
    bool is_empty_table = false;        // whether the table has no indexes
2744
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2745
3
    int64_t current_table_id = 0;       // current scanning table id
2746
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2747
3
                         &current_table_id, &is_table_kvs_recycled,
2748
3
                         this](std::string_view k, std::string_view) {
2749
2
        ++num_scanned;
2750
2751
2
        std::string_view k1(k);
2752
2
        int64_t db_id, table_id, partition_id;
2753
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2754
2
                                                            &partition_id)) {
2755
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2756
0
            return -1;
2757
2
        } else if (table_id != current_table_id) {
2758
2
            current_table_id = table_id;
2759
2
            is_table_kvs_recycled = false;
2760
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2761
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2762
2
            if (err != TxnErrorCode::TXN_OK) {
2763
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2764
0
                             << " table_id=" << table_id << " err=" << err;
2765
0
                return -1;
2766
0
            }
2767
2
        }
2768
2769
2
        if (!is_empty_table) {
2770
            // table is not empty, skip recycle
2771
1
            return 0;
2772
1
        }
2773
2774
1
        std::unique_ptr<Transaction> txn;
2775
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2776
1
        if (err != TxnErrorCode::TXN_OK) {
2777
0
            return -1;
2778
0
        }
2779
2780
        // 1. Remove all partition related kvs
2781
1
        std::string partition_meta_key =
2782
1
                versioned::meta_partition_key({instance_id_, partition_id});
2783
1
        std::string partition_index_key =
2784
1
                versioned::partition_index_key({instance_id_, partition_id});
2785
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2786
1
                {instance_id_, db_id, table_id, partition_id});
2787
1
        std::string partition_version_key =
2788
1
                versioned::partition_version_key({instance_id_, partition_id});
2789
1
        txn->remove(partition_index_key);
2790
1
        txn->remove(partition_inverted_key);
2791
1
        versioned_remove_all(txn.get(), partition_meta_key);
2792
1
        versioned_remove_all(txn.get(), partition_version_key);
2793
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2794
1
                     << " table_id=" << table_id << " db_id=" << db_id
2795
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2796
1
                     << " partition_version_key=" << hex(partition_version_key);
2797
2798
1
        if (!is_table_kvs_recycled) {
2799
1
            is_table_kvs_recycled = true;
2800
2801
            // 2. Remove the table version kv of this table
2802
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2803
1
            versioned_remove_all(txn.get(), table_version_key);
2804
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2805
            // 3. Remove mow delete bitmap update lock and tablet job lock
2806
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2807
1
            txn->remove(lock_key);
2808
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2809
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2810
1
            std::string tablet_job_key_end =
2811
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2812
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2813
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2814
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2815
1
                         << " table_id=" << table_id;
2816
1
        }
2817
2818
1
        err = txn->commit();
2819
1
        if (err != TxnErrorCode::TXN_OK) {
2820
0
            return -1;
2821
0
        }
2822
1
        metrics_context.total_recycled_num = ++num_recycled;
2823
1
        metrics_context.report();
2824
1
        return 0;
2825
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
2748
2
                         this](std::string_view k, std::string_view) {
2749
2
        ++num_scanned;
2750
2751
2
        std::string_view k1(k);
2752
2
        int64_t db_id, table_id, partition_id;
2753
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2754
2
                                                            &partition_id)) {
2755
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2756
0
            return -1;
2757
2
        } else if (table_id != current_table_id) {
2758
2
            current_table_id = table_id;
2759
2
            is_table_kvs_recycled = false;
2760
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2761
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2762
2
            if (err != TxnErrorCode::TXN_OK) {
2763
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2764
0
                             << " table_id=" << table_id << " err=" << err;
2765
0
                return -1;
2766
0
            }
2767
2
        }
2768
2769
2
        if (!is_empty_table) {
2770
            // table is not empty, skip recycle
2771
1
            return 0;
2772
1
        }
2773
2774
1
        std::unique_ptr<Transaction> txn;
2775
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2776
1
        if (err != TxnErrorCode::TXN_OK) {
2777
0
            return -1;
2778
0
        }
2779
2780
        // 1. Remove all partition related kvs
2781
1
        std::string partition_meta_key =
2782
1
                versioned::meta_partition_key({instance_id_, partition_id});
2783
1
        std::string partition_index_key =
2784
1
                versioned::partition_index_key({instance_id_, partition_id});
2785
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
2786
1
                {instance_id_, db_id, table_id, partition_id});
2787
1
        std::string partition_version_key =
2788
1
                versioned::partition_version_key({instance_id_, partition_id});
2789
1
        txn->remove(partition_index_key);
2790
1
        txn->remove(partition_inverted_key);
2791
1
        versioned_remove_all(txn.get(), partition_meta_key);
2792
1
        versioned_remove_all(txn.get(), partition_version_key);
2793
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
2794
1
                     << " table_id=" << table_id << " db_id=" << db_id
2795
1
                     << " partition_meta_key=" << hex(partition_meta_key)
2796
1
                     << " partition_version_key=" << hex(partition_version_key);
2797
2798
1
        if (!is_table_kvs_recycled) {
2799
1
            is_table_kvs_recycled = true;
2800
2801
            // 2. Remove the table version kv of this table
2802
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
2803
1
            versioned_remove_all(txn.get(), table_version_key);
2804
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
2805
            // 3. Remove mow delete bitmap update lock and tablet job lock
2806
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2807
1
            txn->remove(lock_key);
2808
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2809
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2810
1
            std::string tablet_job_key_end =
2811
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2812
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
2813
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2814
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2815
1
                         << " table_id=" << table_id;
2816
1
        }
2817
2818
1
        err = txn->commit();
2819
1
        if (err != TxnErrorCode::TXN_OK) {
2820
0
            return -1;
2821
0
        }
2822
1
        metrics_context.total_recycled_num = ++num_recycled;
2823
1
        metrics_context.report();
2824
1
        return 0;
2825
1
    };
2826
2827
    // recycle_func and loop_done for scan and recycle
2828
3
    return scan_and_recycle(
2829
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
2830
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
2831
3
            std::move(recycle_func));
2832
3
}
2833
2834
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
2835
                                      RecyclerMetricsContext& metrics_context,
2836
52
                                      int64_t partition_id) {
2837
52
    bool is_multi_version =
2838
52
            instance_info_.has_multi_version_status() &&
2839
52
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
2840
52
    int64_t num_scanned = 0;
2841
52
    std::atomic_long num_recycled = 0;
2842
2843
52
    std::string tablet_key_begin, tablet_key_end;
2844
52
    std::string stats_key_begin, stats_key_end;
2845
52
    std::string job_key_begin, job_key_end;
2846
2847
52
    std::string tablet_belongs;
2848
52
    if (partition_id > 0) {
2849
        // recycle tablets in a partition belonging to the index
2850
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
2851
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
2852
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
2853
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
2854
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
2855
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
2856
33
        tablet_belongs = "partition";
2857
33
    } else {
2858
        // recycle tablets in the index
2859
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
2860
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
2861
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
2862
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
2863
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
2864
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
2865
19
        tablet_belongs = "index";
2866
19
    }
2867
2868
52
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
2869
52
            .tag("table_id", table_id)
2870
52
            .tag("index_id", index_id)
2871
52
            .tag("partition_id", partition_id);
2872
2873
52
    auto start_time = steady_clock::now();
2874
2875
52
    DORIS_CLOUD_DEFER {
2876
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2877
52
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2878
52
                .tag("instance_id", instance_id_)
2879
52
                .tag("table_id", table_id)
2880
52
                .tag("index_id", index_id)
2881
52
                .tag("partition_id", partition_id)
2882
52
                .tag("num_scanned", num_scanned)
2883
52
                .tag("num_recycled", num_recycled);
2884
52
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2875
4
    DORIS_CLOUD_DEFER {
2876
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2877
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2878
4
                .tag("instance_id", instance_id_)
2879
4
                .tag("table_id", table_id)
2880
4
                .tag("index_id", index_id)
2881
4
                .tag("partition_id", partition_id)
2882
4
                .tag("num_scanned", num_scanned)
2883
4
                .tag("num_recycled", num_recycled);
2884
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
2875
48
    DORIS_CLOUD_DEFER {
2876
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2877
48
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
2878
48
                .tag("instance_id", instance_id_)
2879
48
                .tag("table_id", table_id)
2880
48
                .tag("index_id", index_id)
2881
48
                .tag("partition_id", partition_id)
2882
48
                .tag("num_scanned", num_scanned)
2883
48
                .tag("num_recycled", num_recycled);
2884
48
    };
2885
2886
    // The tablet key and id which have been recycled.
2887
52
    struct TabletInfo {
2888
52
        std::string_view tablet_meta_key;
2889
52
        int64_t tablet_id;
2890
52
    };
2891
52
    SyncExecutor<TabletInfo> sync_executor(
2892
52
            _thread_pool_group.recycle_tablet_pool,
2893
52
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
2894
52
                        index_id, partition_id),
2895
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
2895
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
2895
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
2896
2897
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
2898
52
    std::vector<std::string> init_rs_keys;
2899
52
    bool has_failure = false;
2900
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2901
8.25k
        ++num_scanned;
2902
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
2903
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2904
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2905
0
            has_failure = true;
2906
0
            return -1;
2907
0
        }
2908
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2909
2910
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
2911
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2912
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2913
4.00k
            has_failure = true;
2914
4.00k
            return -1;
2915
4.00k
        }
2916
2917
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2918
4.25k
        sync_executor.add(
2919
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2920
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2921
2
                        LOG_WARNING("failed to recycle tablet")
2922
2
                                .tag("instance_id", instance_id_)
2923
2
                                .tag("tablet_id", tid);
2924
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2925
2
                    }
2926
4.25k
                    ++num_recycled;
2927
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2928
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2929
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
2919
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2920
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2921
0
                        LOG_WARNING("failed to recycle tablet")
2922
0
                                .tag("instance_id", instance_id_)
2923
0
                                .tag("tablet_id", tid);
2924
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2925
0
                    }
2926
4.00k
                    ++num_recycled;
2927
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2928
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2929
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
2919
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2920
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
2921
2
                        LOG_WARNING("failed to recycle tablet")
2922
2
                                .tag("instance_id", instance_id_)
2923
2
                                .tag("tablet_id", tid);
2924
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2925
2
                    }
2926
248
                    ++num_recycled;
2927
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2928
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
2929
250
                });
2930
4.25k
        return 0;
2931
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2900
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2901
8.00k
        ++num_scanned;
2902
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
2903
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2904
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2905
0
            has_failure = true;
2906
0
            return -1;
2907
0
        }
2908
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2909
2910
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
2911
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2912
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2913
4.00k
            has_failure = true;
2914
4.00k
            return -1;
2915
4.00k
        }
2916
2917
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2918
4.00k
        sync_executor.add(
2919
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2920
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
2921
4.00k
                        LOG_WARNING("failed to recycle tablet")
2922
4.00k
                                .tag("instance_id", instance_id_)
2923
4.00k
                                .tag("tablet_id", tid);
2924
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2925
4.00k
                    }
2926
4.00k
                    ++num_recycled;
2927
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2928
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
2929
4.00k
                });
2930
4.00k
        return 0;
2931
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
2900
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2901
251
        ++num_scanned;
2902
251
        doris::TabletMetaCloudPB tablet_meta_pb;
2903
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
2904
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
2905
0
            has_failure = true;
2906
0
            return -1;
2907
0
        }
2908
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
2909
2910
251
        if (config::enable_recycler_check_lazy_txn_finished &&
2911
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
2912
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
2913
1
            has_failure = true;
2914
1
            return -1;
2915
1
        }
2916
2917
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
2918
250
        sync_executor.add(
2919
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
2920
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
2921
250
                        LOG_WARNING("failed to recycle tablet")
2922
250
                                .tag("instance_id", instance_id_)
2923
250
                                .tag("tablet_id", tid);
2924
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
2925
250
                    }
2926
250
                    ++num_recycled;
2927
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
2928
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
2929
250
                });
2930
250
        return 0;
2931
250
    };
2932
2933
52
    auto loop_done = [&, this]() -> int {
2934
52
        int ret = 0;
2935
52
        bool finished = true;
2936
52
        bool has_empty_key = false;
2937
52
        DORIS_CLOUD_DEFER {
2938
52
            init_rs_keys.clear();
2939
52
            has_failure = false;
2940
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2937
4
        DORIS_CLOUD_DEFER {
2938
4
            init_rs_keys.clear();
2939
4
            has_failure = false;
2940
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2937
48
        DORIS_CLOUD_DEFER {
2938
48
            init_rs_keys.clear();
2939
48
            has_failure = false;
2940
48
        };
2941
52
        auto tablets_info = sync_executor.when_all(&finished);
2942
52
        if (!finished) {
2943
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2944
1
            return -1;
2945
1
        }
2946
2947
51
        size_t size_before_erase = tablets_info.size();
2948
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
2948
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
2948
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2949
51
        if (tablets_info.empty()) {
2950
2
            return size_before_erase == 0 ? 0 : -1;
2951
49
        } else if (size_before_erase != tablets_info.size()) {
2952
1
            has_empty_key = true;
2953
1
        }
2954
2955
49
        ret = has_empty_key ? -1 : 0;
2956
        // sort the vector using key's order
2957
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2958
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
2959
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
2957
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2958
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
2959
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
2957
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2958
958
            return prev.tablet_meta_key < last.tablet_meta_key;
2959
958
        });
2960
49
        std::unique_ptr<Transaction> txn;
2961
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2962
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2963
0
            return -1;
2964
0
        }
2965
49
        std::string tablet_key_end;
2966
49
        if (!tablets_info.empty()) {
2967
49
            if (!has_empty_key && !has_failure) {
2968
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2969
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2970
47
            } else {
2971
8
                for (auto& tablet_info : tablets_info) {
2972
8
                    txn->remove(tablet_info.tablet_meta_key);
2973
8
                }
2974
2
            }
2975
49
        }
2976
49
        if (is_multi_version) {
2977
6
            for (auto& tablet_info : tablets_info) {
2978
                // Remove all versions of tablet compact stats for recycled tablet
2979
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2980
6
                LOG_INFO("remove versioned tablet compact stats key")
2981
6
                        .tag("compact_stats_key", hex(k));
2982
6
                versioned_remove_all(txn.get(), k);
2983
6
            }
2984
6
            for (auto& tablet_info : tablets_info) {
2985
                // Remove all versions of tablet load stats for recycled tablet
2986
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
2987
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2988
6
                versioned_remove_all(txn.get(), k);
2989
6
            }
2990
6
            for (auto& tablet_info : tablets_info) {
2991
                // Remove all versions of meta tablet for recycled tablet
2992
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
2993
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2994
6
                versioned_remove_all(txn.get(), k);
2995
6
            }
2996
5
        }
2997
4.25k
        for (auto& tablet_info : tablets_info) {
2998
4.25k
            std::string k;
2999
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3000
4.25k
            txn->remove(k);
3001
4.25k
        }
3002
4.25k
        for (auto& tablet_info : tablets_info) {
3003
4.25k
            std::string k;
3004
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3005
4.25k
            txn->remove(k);
3006
4.25k
        }
3007
49
        for (auto& k : init_rs_keys) {
3008
0
            txn->remove(k);
3009
0
        }
3010
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3011
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3012
0
                         << ", err=" << err;
3013
0
            return -1;
3014
0
        }
3015
49
        return ret;
3016
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2933
4
    auto loop_done = [&, this]() -> int {
2934
4
        int ret = 0;
2935
4
        bool finished = true;
2936
4
        bool has_empty_key = false;
2937
4
        DORIS_CLOUD_DEFER {
2938
4
            init_rs_keys.clear();
2939
4
            has_failure = false;
2940
4
        };
2941
4
        auto tablets_info = sync_executor.when_all(&finished);
2942
4
        if (!finished) {
2943
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2944
0
            return -1;
2945
0
        }
2946
2947
4
        size_t size_before_erase = tablets_info.size();
2948
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2949
4
        if (tablets_info.empty()) {
2950
2
            return size_before_erase == 0 ? 0 : -1;
2951
2
        } else if (size_before_erase != tablets_info.size()) {
2952
0
            has_empty_key = true;
2953
0
        }
2954
2955
2
        ret = has_empty_key ? -1 : 0;
2956
        // sort the vector using key's order
2957
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2958
2
            return prev.tablet_meta_key < last.tablet_meta_key;
2959
2
        });
2960
2
        std::unique_ptr<Transaction> txn;
2961
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2962
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2963
0
            return -1;
2964
0
        }
2965
2
        std::string tablet_key_end;
2966
2
        if (!tablets_info.empty()) {
2967
2
            if (!has_empty_key && !has_failure) {
2968
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2969
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2970
2
            } else {
2971
0
                for (auto& tablet_info : tablets_info) {
2972
0
                    txn->remove(tablet_info.tablet_meta_key);
2973
0
                }
2974
0
            }
2975
2
        }
2976
2
        if (is_multi_version) {
2977
0
            for (auto& tablet_info : tablets_info) {
2978
                // Remove all versions of tablet compact stats for recycled tablet
2979
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2980
0
                LOG_INFO("remove versioned tablet compact stats key")
2981
0
                        .tag("compact_stats_key", hex(k));
2982
0
                versioned_remove_all(txn.get(), k);
2983
0
            }
2984
0
            for (auto& tablet_info : tablets_info) {
2985
                // Remove all versions of tablet load stats for recycled tablet
2986
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
2987
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2988
0
                versioned_remove_all(txn.get(), k);
2989
0
            }
2990
0
            for (auto& tablet_info : tablets_info) {
2991
                // Remove all versions of meta tablet for recycled tablet
2992
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
2993
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2994
0
                versioned_remove_all(txn.get(), k);
2995
0
            }
2996
0
        }
2997
4.00k
        for (auto& tablet_info : tablets_info) {
2998
4.00k
            std::string k;
2999
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3000
4.00k
            txn->remove(k);
3001
4.00k
        }
3002
4.00k
        for (auto& tablet_info : tablets_info) {
3003
4.00k
            std::string k;
3004
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3005
4.00k
            txn->remove(k);
3006
4.00k
        }
3007
2
        for (auto& k : init_rs_keys) {
3008
0
            txn->remove(k);
3009
0
        }
3010
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3011
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3012
0
                         << ", err=" << err;
3013
0
            return -1;
3014
0
        }
3015
2
        return ret;
3016
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
2933
48
    auto loop_done = [&, this]() -> int {
2934
48
        int ret = 0;
2935
48
        bool finished = true;
2936
48
        bool has_empty_key = false;
2937
48
        DORIS_CLOUD_DEFER {
2938
48
            init_rs_keys.clear();
2939
48
            has_failure = false;
2940
48
        };
2941
48
        auto tablets_info = sync_executor.when_all(&finished);
2942
48
        if (!finished) {
2943
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
2944
1
            return -1;
2945
1
        }
2946
2947
47
        size_t size_before_erase = tablets_info.size();
2948
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
2949
47
        if (tablets_info.empty()) {
2950
0
            return size_before_erase == 0 ? 0 : -1;
2951
47
        } else if (size_before_erase != tablets_info.size()) {
2952
1
            has_empty_key = true;
2953
1
        }
2954
2955
47
        ret = has_empty_key ? -1 : 0;
2956
        // sort the vector using key's order
2957
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
2958
47
            return prev.tablet_meta_key < last.tablet_meta_key;
2959
47
        });
2960
47
        std::unique_ptr<Transaction> txn;
2961
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
2962
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
2963
0
            return -1;
2964
0
        }
2965
47
        std::string tablet_key_end;
2966
47
        if (!tablets_info.empty()) {
2967
47
            if (!has_empty_key && !has_failure) {
2968
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
2969
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
2970
45
            } else {
2971
8
                for (auto& tablet_info : tablets_info) {
2972
8
                    txn->remove(tablet_info.tablet_meta_key);
2973
8
                }
2974
2
            }
2975
47
        }
2976
47
        if (is_multi_version) {
2977
6
            for (auto& tablet_info : tablets_info) {
2978
                // Remove all versions of tablet compact stats for recycled tablet
2979
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
2980
6
                LOG_INFO("remove versioned tablet compact stats key")
2981
6
                        .tag("compact_stats_key", hex(k));
2982
6
                versioned_remove_all(txn.get(), k);
2983
6
            }
2984
6
            for (auto& tablet_info : tablets_info) {
2985
                // Remove all versions of tablet load stats for recycled tablet
2986
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
2987
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
2988
6
                versioned_remove_all(txn.get(), k);
2989
6
            }
2990
6
            for (auto& tablet_info : tablets_info) {
2991
                // Remove all versions of meta tablet for recycled tablet
2992
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
2993
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
2994
6
                versioned_remove_all(txn.get(), k);
2995
6
            }
2996
5
        }
2997
248
        for (auto& tablet_info : tablets_info) {
2998
248
            std::string k;
2999
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3000
248
            txn->remove(k);
3001
248
        }
3002
248
        for (auto& tablet_info : tablets_info) {
3003
248
            std::string k;
3004
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3005
248
            txn->remove(k);
3006
248
        }
3007
47
        for (auto& k : init_rs_keys) {
3008
0
            txn->remove(k);
3009
0
        }
3010
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3011
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3012
0
                         << ", err=" << err;
3013
0
            return -1;
3014
0
        }
3015
47
        return ret;
3016
47
    };
3017
3018
52
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3019
52
                               std::move(loop_done));
3020
52
    if (ret != 0) {
3021
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3022
5
        return ret;
3023
5
    }
3024
3025
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3026
47
    std::unique_ptr<Transaction> txn;
3027
47
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3028
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3029
0
        return -1;
3030
0
    }
3031
47
    txn->remove(stats_key_begin, stats_key_end);
3032
47
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3033
47
                 << " end=" << hex(stats_key_end);
3034
47
    txn->remove(job_key_begin, job_key_end);
3035
47
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3036
47
    std::string schema_key_begin, schema_key_end;
3037
47
    std::string schema_dict_key;
3038
47
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3039
47
    if (partition_id <= 0) {
3040
        // Delete schema kv of this index
3041
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3042
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3043
15
        txn->remove(schema_key_begin, schema_key_end);
3044
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3045
15
                     << " end=" << hex(schema_key_end);
3046
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3047
15
        txn->remove(schema_dict_key);
3048
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3049
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3050
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3051
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3052
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3053
15
                     << " end=" << hex(versioned_schema_key_end);
3054
15
    }
3055
3056
47
    TxnErrorCode err = txn->commit();
3057
47
    if (err != TxnErrorCode::TXN_OK) {
3058
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3059
0
                     << " err=" << err;
3060
0
        return -1;
3061
0
    }
3062
3063
47
    return ret;
3064
47
}
3065
3066
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3067
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3068
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3069
5.61k
    if (num_segments <= 0) return 0;
3070
3071
5.61k
    std::vector<std::string> file_paths;
3072
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3073
0
        return -1;
3074
0
    }
3075
3076
    // Process inverted indexes
3077
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3078
    // default format as v1.
3079
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3080
5.61k
    bool delete_rowset_data_by_prefix = false;
3081
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3082
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3083
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3084
0
        delete_rowset_data_by_prefix = true;
3085
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3086
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3087
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3088
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3089
10.0k
            }
3090
10.0k
        }
3091
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3092
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3093
2.00k
        }
3094
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3095
        // schema version and index id are not found, delete rowset data by prefix directly.
3096
0
        delete_rowset_data_by_prefix = true;
3097
809
    } else {
3098
        // otherwise, try to get schema kv
3099
809
        InvertedIndexInfo index_info;
3100
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3101
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3102
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3103
809
                                 &inverted_index_get_ret);
3104
809
        if (inverted_index_get_ret == 0) {
3105
809
            index_format = index_info.first;
3106
809
            index_ids = index_info.second;
3107
809
        } else if (inverted_index_get_ret == 1) {
3108
            // 1. Schema kv not found means tablet has been recycled
3109
            // Maybe some tablet recycle failed by some bugs
3110
            // We need to delete again to double check
3111
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3112
            // because we are uncertain about the inverted index information.
3113
            // If there are inverted indexes, some data might not be deleted,
3114
            // but this is acceptable as we have made our best effort to delete the data.
3115
0
            LOG_INFO(
3116
0
                    "delete rowset data schema kv not found, need to delete again to double "
3117
0
                    "check")
3118
0
                    .tag("instance_id", instance_id_)
3119
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3120
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3121
            // Currently index_ids is guaranteed to be empty,
3122
            // but we clear it again here as a safeguard against future code changes
3123
            // that might cause index_ids to no longer be empty
3124
0
            index_format = InvertedIndexStorageFormatPB::V2;
3125
0
            index_ids.clear();
3126
0
        } else {
3127
            // failed to get schema kv, delete rowset data by prefix directly.
3128
0
            delete_rowset_data_by_prefix = true;
3129
0
        }
3130
809
    }
3131
3132
5.61k
    if (delete_rowset_data_by_prefix) {
3133
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3134
0
                                  rs_meta_pb.rowset_id_v2());
3135
0
    }
3136
3137
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3138
5.61k
    if (it == accessor_map_.end()) {
3139
1.59k
        LOG_WARNING("instance has no such resource id")
3140
1.59k
                .tag("instance_id", instance_id_)
3141
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3142
1.59k
        return -1;
3143
1.59k
    }
3144
4.01k
    auto& accessor = it->second;
3145
3146
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3147
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3148
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3149
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3150
20.0k
                                         &file_paths);
3151
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3152
40.0k
            for (const auto& index_id : index_ids) {
3153
40.0k
                add_file_to_delete_if_not_packed(
3154
40.0k
                        rs_meta_pb,
3155
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3156
40.0k
                                               index_id.second),
3157
40.0k
                        &file_paths);
3158
40.0k
            }
3159
20.0k
        } else if (!index_ids.empty()) {
3160
0
            add_file_to_delete_if_not_packed(
3161
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3162
0
        }
3163
20.0k
    }
3164
3165
    // Process delete bitmap - check where it's stored.
3166
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3167
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3168
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3169
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3170
0
                .tag("instance_id", instance_id_)
3171
0
                .tag("tablet_id", tablet_id)
3172
0
                .tag("rowset_id", rowset_id);
3173
0
        return -1;
3174
0
    }
3175
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3176
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3177
2.00k
    }
3178
    // TODO(AlexYue): seems could do do batch
3179
4.01k
    return accessor->delete_files(file_paths);
3180
4.01k
}
3181
3182
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3183
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3184
62.3k
            .tag("instance_id", instance_id_)
3185
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3186
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3187
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3188
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3189
62.3k
    if (index_map.empty()) {
3190
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3191
62.3k
                .tag("instance_id", instance_id_)
3192
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3193
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3194
62.3k
        return 0;
3195
62.3k
    }
3196
3197
12
    struct PackedSmallFileInfo {
3198
12
        std::string small_file_path;
3199
12
    };
3200
12
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3201
12
    packed_file_updates.reserve(index_map.size());
3202
27
    for (const auto& [small_path, index_pb] : index_map) {
3203
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3204
0
            continue;
3205
0
        }
3206
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3207
27
                PackedSmallFileInfo {small_path});
3208
27
    }
3209
12
    if (packed_file_updates.empty()) {
3210
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3211
0
                .tag("instance_id", instance_id_)
3212
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3213
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3214
0
                .tag("index_map_size", index_map.size());
3215
0
        return 0;
3216
0
    }
3217
3218
12
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3219
12
    int ret = 0;
3220
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3221
24
        if (small_files.empty()) {
3222
0
            continue;
3223
0
        }
3224
3225
24
        bool success = false;
3226
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3227
24
            std::unique_ptr<Transaction> txn;
3228
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3229
24
            if (err != TxnErrorCode::TXN_OK) {
3230
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3231
0
                        .tag("instance_id", instance_id_)
3232
0
                        .tag("packed_file_path", packed_file_path)
3233
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3234
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3235
0
                        .tag("err", err);
3236
0
                ret = -1;
3237
0
                break;
3238
0
            }
3239
3240
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3241
24
            std::string packed_val;
3242
24
            err = txn->get(packed_key, &packed_val);
3243
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3244
0
                LOG_WARNING("packed file info not found when recycling rowset")
3245
0
                        .tag("instance_id", instance_id_)
3246
0
                        .tag("packed_file_path", packed_file_path)
3247
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3248
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3249
0
                        .tag("key", hex(packed_key))
3250
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3251
                // Skip this packed file entry and continue with others
3252
0
                success = true;
3253
0
                break;
3254
0
            }
3255
24
            if (err != TxnErrorCode::TXN_OK) {
3256
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3257
0
                        .tag("instance_id", instance_id_)
3258
0
                        .tag("packed_file_path", packed_file_path)
3259
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3260
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3261
0
                        .tag("err", err);
3262
0
                ret = -1;
3263
0
                break;
3264
0
            }
3265
3266
24
            cloud::PackedFileInfoPB packed_info;
3267
24
            if (!packed_info.ParseFromString(packed_val)) {
3268
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3269
0
                        .tag("instance_id", instance_id_)
3270
0
                        .tag("packed_file_path", packed_file_path)
3271
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3272
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3273
0
                ret = -1;
3274
0
                break;
3275
0
            }
3276
3277
24
            LOG_INFO("packed file update check")
3278
24
                    .tag("instance_id", instance_id_)
3279
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3280
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3281
24
                    .tag("merged_file_path", packed_file_path)
3282
24
                    .tag("requested_small_files", small_files.size())
3283
24
                    .tag("merge_entries", packed_info.slices_size());
3284
3285
24
            auto* small_file_entries = packed_info.mutable_slices();
3286
24
            int64_t changed_files = 0;
3287
24
            int64_t missing_entries = 0;
3288
24
            int64_t already_deleted = 0;
3289
27
            for (const auto& small_file_info : small_files) {
3290
27
                bool found = false;
3291
87
                for (auto& small_file_entry : *small_file_entries) {
3292
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3293
27
                        if (!small_file_entry.deleted()) {
3294
27
                            small_file_entry.set_deleted(true);
3295
27
                            if (!small_file_entry.corrected()) {
3296
27
                                small_file_entry.set_corrected(true);
3297
27
                            }
3298
27
                            ++changed_files;
3299
27
                        } else {
3300
0
                            ++already_deleted;
3301
0
                        }
3302
27
                        found = true;
3303
27
                        break;
3304
27
                    }
3305
87
                }
3306
27
                if (!found) {
3307
0
                    ++missing_entries;
3308
0
                    LOG_WARNING("packed file info missing small file entry")
3309
0
                            .tag("instance_id", instance_id_)
3310
0
                            .tag("packed_file_path", packed_file_path)
3311
0
                            .tag("small_file_path", small_file_info.small_file_path)
3312
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3313
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3314
0
                }
3315
27
            }
3316
3317
24
            if (changed_files == 0) {
3318
0
                LOG_INFO("skip merge file update: no merge entries changed")
3319
0
                        .tag("instance_id", instance_id_)
3320
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3321
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3322
0
                        .tag("merged_file_path", packed_file_path)
3323
0
                        .tag("missing_entries", missing_entries)
3324
0
                        .tag("already_deleted", already_deleted)
3325
0
                        .tag("requested_small_files", small_files.size())
3326
0
                        .tag("merge_entries", packed_info.slices_size());
3327
0
                success = true;
3328
0
                break;
3329
0
            }
3330
3331
            // Calculate remaining files
3332
24
            int64_t left_file_count = 0;
3333
24
            int64_t left_file_bytes = 0;
3334
141
            for (const auto& small_file_entry : packed_info.slices()) {
3335
141
                if (!small_file_entry.deleted()) {
3336
57
                    ++left_file_count;
3337
57
                    left_file_bytes += small_file_entry.size();
3338
57
                }
3339
141
            }
3340
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3341
24
            packed_info.set_ref_cnt(left_file_count);
3342
24
            LOG_INFO("updated packed file reference info")
3343
24
                    .tag("instance_id", instance_id_)
3344
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3345
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3346
24
                    .tag("packed_file_path", packed_file_path)
3347
24
                    .tag("ref_cnt", left_file_count)
3348
24
                    .tag("left_file_bytes", left_file_bytes);
3349
3350
24
            if (left_file_count == 0) {
3351
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3352
7
            }
3353
3354
24
            std::string updated_val;
3355
24
            if (!packed_info.SerializeToString(&updated_val)) {
3356
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3357
0
                        .tag("instance_id", instance_id_)
3358
0
                        .tag("packed_file_path", packed_file_path)
3359
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3360
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3361
0
                ret = -1;
3362
0
                break;
3363
0
            }
3364
3365
24
            txn->put(packed_key, updated_val);
3366
24
            err = txn->commit();
3367
24
            if (err == TxnErrorCode::TXN_OK) {
3368
24
                success = true;
3369
24
                if (left_file_count == 0) {
3370
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3371
7
                            .tag("instance_id", instance_id_)
3372
7
                            .tag("packed_file_path", packed_file_path);
3373
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3374
0
                        ret = -1;
3375
0
                    }
3376
7
                }
3377
24
                break;
3378
24
            }
3379
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3380
0
                if (attempt >= max_retry_times) {
3381
0
                    LOG_WARNING("packed file info update conflict after max retry")
3382
0
                            .tag("instance_id", instance_id_)
3383
0
                            .tag("packed_file_path", packed_file_path)
3384
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3385
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3386
0
                            .tag("changed_files", changed_files)
3387
0
                            .tag("attempt", attempt);
3388
0
                    ret = -1;
3389
0
                    break;
3390
0
                }
3391
0
                LOG_WARNING("packed file info update conflict, retrying")
3392
0
                        .tag("instance_id", instance_id_)
3393
0
                        .tag("packed_file_path", packed_file_path)
3394
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3395
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3396
0
                        .tag("changed_files", changed_files)
3397
0
                        .tag("attempt", attempt);
3398
0
                sleep_for_packed_file_retry();
3399
0
                continue;
3400
0
            }
3401
3402
0
            LOG_WARNING("failed to commit packed file info update")
3403
0
                    .tag("instance_id", instance_id_)
3404
0
                    .tag("packed_file_path", packed_file_path)
3405
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3406
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3407
0
                    .tag("err", err)
3408
0
                    .tag("changed_files", changed_files);
3409
0
            ret = -1;
3410
0
            break;
3411
0
        }
3412
3413
24
        if (!success) {
3414
0
            ret = -1;
3415
0
        }
3416
24
    }
3417
3418
12
    return ret;
3419
12
}
3420
3421
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3422
        int64_t tablet_id, const std::string& rowset_id,
3423
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3424
58.2k
    if (out_storage_type) {
3425
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3426
58.2k
    }
3427
3428
    // Get delete bitmap storage info from FDB
3429
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3430
58.2k
    std::unique_ptr<Transaction> txn;
3431
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3432
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3433
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3434
0
                .tag("instance_id", instance_id_)
3435
0
                .tag("tablet_id", tablet_id)
3436
0
                .tag("rowset_id", rowset_id)
3437
0
                .tag("err", err);
3438
0
        return -1;
3439
0
    }
3440
3441
58.2k
    std::string dbm_val;
3442
58.2k
    err = txn->get(dbm_key, &dbm_val);
3443
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3444
        // No delete bitmap for this rowset, nothing to do
3445
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3446
4.63k
                .tag("instance_id", instance_id_)
3447
4.63k
                .tag("tablet_id", tablet_id)
3448
4.63k
                .tag("rowset_id", rowset_id);
3449
4.63k
        return 0;
3450
4.63k
    }
3451
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3452
0
        LOG_WARNING("failed to get delete bitmap storage")
3453
0
                .tag("instance_id", instance_id_)
3454
0
                .tag("tablet_id", tablet_id)
3455
0
                .tag("rowset_id", rowset_id)
3456
0
                .tag("err", err);
3457
0
        return -1;
3458
0
    }
3459
3460
53.5k
    DeleteBitmapStoragePB storage;
3461
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3462
0
        LOG_WARNING("failed to parse delete bitmap storage")
3463
0
                .tag("instance_id", instance_id_)
3464
0
                .tag("tablet_id", tablet_id)
3465
0
                .tag("rowset_id", rowset_id);
3466
0
        return -1;
3467
0
    }
3468
3469
53.5k
    if (storage.store_in_fdb()) {
3470
0
        if (out_storage_type) {
3471
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3472
0
        }
3473
0
        return 0;
3474
0
    }
3475
3476
    // Check if delete bitmap is stored in standalone file.
3477
53.5k
    if (!storage.has_packed_slice_location() ||
3478
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3479
53.5k
        if (out_storage_type) {
3480
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3481
53.5k
        }
3482
53.5k
        return 0;
3483
53.5k
    }
3484
3485
18.4E
    if (out_storage_type) {
3486
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3487
0
    }
3488
3489
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3490
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3491
3492
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3493
18.4E
            .tag("instance_id", instance_id_)
3494
18.4E
            .tag("tablet_id", tablet_id)
3495
18.4E
            .tag("rowset_id", rowset_id)
3496
18.4E
            .tag("packed_file_path", packed_file_path);
3497
3498
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3499
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3500
0
        std::unique_ptr<Transaction> update_txn;
3501
0
        err = txn_kv_->create_txn(&update_txn);
3502
0
        if (err != TxnErrorCode::TXN_OK) {
3503
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3504
0
                    .tag("instance_id", instance_id_)
3505
0
                    .tag("tablet_id", tablet_id)
3506
0
                    .tag("rowset_id", rowset_id)
3507
0
                    .tag("err", err);
3508
0
            return -1;
3509
0
        }
3510
3511
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3512
0
        std::string packed_val;
3513
0
        err = update_txn->get(packed_key, &packed_val);
3514
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3515
0
            LOG_WARNING("packed file info not found for delete bitmap")
3516
0
                    .tag("instance_id", instance_id_)
3517
0
                    .tag("tablet_id", tablet_id)
3518
0
                    .tag("rowset_id", rowset_id)
3519
0
                    .tag("packed_file_path", packed_file_path);
3520
0
            return 0;
3521
0
        }
3522
0
        if (err != TxnErrorCode::TXN_OK) {
3523
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3524
0
                    .tag("instance_id", instance_id_)
3525
0
                    .tag("tablet_id", tablet_id)
3526
0
                    .tag("rowset_id", rowset_id)
3527
0
                    .tag("packed_file_path", packed_file_path)
3528
0
                    .tag("err", err);
3529
0
            return -1;
3530
0
        }
3531
3532
0
        cloud::PackedFileInfoPB packed_info;
3533
0
        if (!packed_info.ParseFromString(packed_val)) {
3534
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3535
0
                    .tag("instance_id", instance_id_)
3536
0
                    .tag("tablet_id", tablet_id)
3537
0
                    .tag("rowset_id", rowset_id)
3538
0
                    .tag("packed_file_path", packed_file_path);
3539
0
            return -1;
3540
0
        }
3541
3542
        // Find and mark the small file entry as deleted
3543
        // Use tablet_id and rowset_id to match entry instead of path,
3544
        // because path format may vary with path_version (with or without shard prefix)
3545
0
        auto* entries = packed_info.mutable_slices();
3546
0
        bool found = false;
3547
0
        bool already_deleted = false;
3548
0
        for (auto& entry : *entries) {
3549
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3550
0
                if (!entry.deleted()) {
3551
0
                    entry.set_deleted(true);
3552
0
                    if (!entry.corrected()) {
3553
0
                        entry.set_corrected(true);
3554
0
                    }
3555
0
                } else {
3556
0
                    already_deleted = true;
3557
0
                }
3558
0
                found = true;
3559
0
                break;
3560
0
            }
3561
0
        }
3562
3563
0
        if (!found) {
3564
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3565
0
                    .tag("instance_id", instance_id_)
3566
0
                    .tag("tablet_id", tablet_id)
3567
0
                    .tag("rowset_id", rowset_id)
3568
0
                    .tag("packed_file_path", packed_file_path);
3569
0
            return 0;
3570
0
        }
3571
3572
0
        if (already_deleted) {
3573
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3574
0
                    .tag("instance_id", instance_id_)
3575
0
                    .tag("tablet_id", tablet_id)
3576
0
                    .tag("rowset_id", rowset_id)
3577
0
                    .tag("packed_file_path", packed_file_path);
3578
0
            return 0;
3579
0
        }
3580
3581
        // Calculate remaining files
3582
0
        int64_t left_file_count = 0;
3583
0
        int64_t left_file_bytes = 0;
3584
0
        for (const auto& entry : packed_info.slices()) {
3585
0
            if (!entry.deleted()) {
3586
0
                ++left_file_count;
3587
0
                left_file_bytes += entry.size();
3588
0
            }
3589
0
        }
3590
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3591
0
        packed_info.set_ref_cnt(left_file_count);
3592
3593
0
        if (left_file_count == 0) {
3594
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3595
0
        }
3596
3597
0
        std::string updated_val;
3598
0
        if (!packed_info.SerializeToString(&updated_val)) {
3599
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3600
0
                    .tag("instance_id", instance_id_)
3601
0
                    .tag("tablet_id", tablet_id)
3602
0
                    .tag("rowset_id", rowset_id)
3603
0
                    .tag("packed_file_path", packed_file_path);
3604
0
            return -1;
3605
0
        }
3606
3607
0
        update_txn->put(packed_key, updated_val);
3608
0
        err = update_txn->commit();
3609
0
        if (err == TxnErrorCode::TXN_OK) {
3610
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3611
0
                    .tag("instance_id", instance_id_)
3612
0
                    .tag("tablet_id", tablet_id)
3613
0
                    .tag("rowset_id", rowset_id)
3614
0
                    .tag("packed_file_path", packed_file_path)
3615
0
                    .tag("left_file_count", left_file_count);
3616
0
            if (left_file_count == 0) {
3617
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3618
0
                    return -1;
3619
0
                }
3620
0
            }
3621
0
            return 0;
3622
0
        }
3623
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3624
0
            if (attempt >= max_retry_times) {
3625
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3626
0
                        .tag("instance_id", instance_id_)
3627
0
                        .tag("tablet_id", tablet_id)
3628
0
                        .tag("rowset_id", rowset_id)
3629
0
                        .tag("packed_file_path", packed_file_path)
3630
0
                        .tag("attempt", attempt);
3631
0
                return -1;
3632
0
            }
3633
0
            sleep_for_packed_file_retry();
3634
0
            continue;
3635
0
        }
3636
3637
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3638
0
                .tag("instance_id", instance_id_)
3639
0
                .tag("tablet_id", tablet_id)
3640
0
                .tag("rowset_id", rowset_id)
3641
0
                .tag("packed_file_path", packed_file_path)
3642
0
                .tag("err", err);
3643
0
        return -1;
3644
0
    }
3645
3646
18.4E
    return -1;
3647
18.4E
}
3648
3649
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3650
                                                const std::string& packed_key,
3651
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3652
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3653
0
        LOG_WARNING("packed file missing resource id when recycling")
3654
0
                .tag("instance_id", instance_id_)
3655
0
                .tag("packed_file_path", packed_file_path);
3656
0
        return -1;
3657
0
    }
3658
3659
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3660
7
    if (!accessor) {
3661
0
        LOG_WARNING("no accessor available to delete packed file")
3662
0
                .tag("instance_id", instance_id_)
3663
0
                .tag("packed_file_path", packed_file_path)
3664
0
                .tag("resource_id", packed_info.resource_id());
3665
0
        return -1;
3666
0
    }
3667
3668
7
    int del_ret = accessor->delete_file(packed_file_path);
3669
7
    if (del_ret != 0 && del_ret != 1) {
3670
0
        LOG_WARNING("failed to delete packed file")
3671
0
                .tag("instance_id", instance_id_)
3672
0
                .tag("packed_file_path", packed_file_path)
3673
0
                .tag("resource_id", resource_id)
3674
0
                .tag("ret", del_ret);
3675
0
        return -1;
3676
0
    }
3677
7
    if (del_ret == 1) {
3678
0
        LOG_INFO("packed file already removed")
3679
0
                .tag("instance_id", instance_id_)
3680
0
                .tag("packed_file_path", packed_file_path)
3681
0
                .tag("resource_id", resource_id);
3682
7
    } else {
3683
7
        LOG_INFO("deleted packed file")
3684
7
                .tag("instance_id", instance_id_)
3685
7
                .tag("packed_file_path", packed_file_path)
3686
7
                .tag("resource_id", resource_id);
3687
7
    }
3688
3689
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3690
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3691
7
        std::unique_ptr<Transaction> del_txn;
3692
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3693
7
        if (err != TxnErrorCode::TXN_OK) {
3694
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3695
0
                    .tag("instance_id", instance_id_)
3696
0
                    .tag("packed_file_path", packed_file_path)
3697
0
                    .tag("attempt", attempt)
3698
0
                    .tag("err", err);
3699
0
            return -1;
3700
0
        }
3701
3702
7
        std::string latest_val;
3703
7
        err = del_txn->get(packed_key, &latest_val);
3704
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3705
0
            return 0;
3706
0
        }
3707
7
        if (err != TxnErrorCode::TXN_OK) {
3708
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3709
0
                    .tag("instance_id", instance_id_)
3710
0
                    .tag("packed_file_path", packed_file_path)
3711
0
                    .tag("attempt", attempt)
3712
0
                    .tag("err", err);
3713
0
            return -1;
3714
0
        }
3715
3716
7
        cloud::PackedFileInfoPB latest_info;
3717
7
        if (!latest_info.ParseFromString(latest_val)) {
3718
0
            LOG_WARNING("failed to parse packed file info before removal")
3719
0
                    .tag("instance_id", instance_id_)
3720
0
                    .tag("packed_file_path", packed_file_path)
3721
0
                    .tag("attempt", attempt);
3722
0
            return -1;
3723
0
        }
3724
3725
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3726
7
              latest_info.ref_cnt() == 0)) {
3727
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3728
0
                    .tag("instance_id", instance_id_)
3729
0
                    .tag("packed_file_path", packed_file_path)
3730
0
                    .tag("attempt", attempt);
3731
0
            return 0;
3732
0
        }
3733
3734
7
        del_txn->remove(packed_key);
3735
7
        err = del_txn->commit();
3736
7
        if (err == TxnErrorCode::TXN_OK) {
3737
7
            LOG_INFO("removed packed file metadata")
3738
7
                    .tag("instance_id", instance_id_)
3739
7
                    .tag("packed_file_path", packed_file_path);
3740
7
            return 0;
3741
7
        }
3742
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3743
0
            if (attempt >= max_retry_times) {
3744
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3745
0
                        .tag("instance_id", instance_id_)
3746
0
                        .tag("packed_file_path", packed_file_path)
3747
0
                        .tag("attempt", attempt);
3748
0
                return -1;
3749
0
            }
3750
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3751
0
                    .tag("instance_id", instance_id_)
3752
0
                    .tag("packed_file_path", packed_file_path)
3753
0
                    .tag("attempt", attempt);
3754
0
            sleep_for_packed_file_retry();
3755
0
            continue;
3756
0
        }
3757
0
        LOG_WARNING("failed to remove packed file kv")
3758
0
                .tag("instance_id", instance_id_)
3759
0
                .tag("packed_file_path", packed_file_path)
3760
0
                .tag("attempt", attempt)
3761
0
                .tag("err", err);
3762
0
        return -1;
3763
0
    }
3764
0
    return -1;
3765
7
}
3766
3767
int InstanceRecycler::delete_rowset_data(
3768
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3769
64
        RecyclerMetricsContext& metrics_context) {
3770
64
    int ret = 0;
3771
    // resource_id -> file_paths
3772
64
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3773
    // (resource_id, tablet_id, rowset_id)
3774
64
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3775
64
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3776
3777
54.1k
    for (const auto& [_, rs] : rowsets) {
3778
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3779
        // due to aborted schema change.
3780
54.1k
        if (is_formal_rowset) {
3781
3.15k
            std::lock_guard lock(recycled_tablets_mtx_);
3782
3.15k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
3783
                // Tablet has been recycled and this rowset has no packed slices, so file data
3784
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
3785
                // slice info must still run to decrement packed file ref counts.
3786
0
                continue;
3787
0
            }
3788
3.15k
        }
3789
3790
54.1k
        int64_t num_segments = rs.num_segments();
3791
        // Check num_segments before accessor lookup, because empty rowsets
3792
        // (e.g. base compaction output of empty rowsets) may have no resource_id
3793
        // set. Skipping them early avoids a spurious "no such resource id" error
3794
        // that marks the entire batch as failed and prevents txn_remove from
3795
        // cleaning up recycle KV keys.
3796
54.1k
        if (num_segments <= 0) {
3797
0
            metrics_context.total_recycled_num++;
3798
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
3799
0
            continue;
3800
0
        }
3801
3802
54.1k
        auto it = accessor_map_.find(rs.resource_id());
3803
        // possible if the accessor is not initilized correctly
3804
54.1k
        if (it == accessor_map_.end()) [[unlikely]] {
3805
1
            LOG_WARNING("instance has no such resource id")
3806
1
                    .tag("instance_id", instance_id_)
3807
1
                    .tag("resource_id", rs.resource_id());
3808
1
            ret = -1;
3809
1
            continue;
3810
1
        }
3811
3812
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
3813
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
3814
54.1k
        int64_t tablet_id = rs.tablet_id();
3815
54.1k
        LOG_INFO("recycle rowset merge index size")
3816
54.1k
                .tag("instance_id", instance_id_)
3817
54.1k
                .tag("tablet_id", tablet_id)
3818
54.1k
                .tag("rowset_id", rowset_id)
3819
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
3820
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
3821
0
            ret = -1;
3822
0
            continue;
3823
0
        }
3824
3825
        // Process delete bitmap - check where it's stored.
3826
54.1k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3827
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3828
54.1k
                                                           &delete_bitmap_storage_type) != 0) {
3829
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3830
0
                    .tag("instance_id", instance_id_)
3831
0
                    .tag("tablet_id", tablet_id)
3832
0
                    .tag("rowset_id", rowset_id);
3833
0
            ret = -1;
3834
0
            continue;
3835
0
        }
3836
54.1k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3837
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3838
51.5k
        }
3839
3840
        // Process inverted indexes
3841
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
3842
        // default format as v1.
3843
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3844
54.1k
        int inverted_index_get_ret = 0;
3845
54.1k
        if (rs.has_tablet_schema()) {
3846
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
3847
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3848
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3849
53.5k
                }
3850
53.5k
            }
3851
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
3852
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
3853
26.5k
            }
3854
27.5k
        } else {
3855
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
3856
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
3857
0
                                "instance_id="
3858
0
                             << instance_id_ << " tablet_id=" << tablet_id
3859
0
                             << " rowset_id=" << rowset_id;
3860
0
                ret = -1;
3861
0
                continue;
3862
0
            }
3863
27.5k
            InvertedIndexInfo index_info;
3864
27.5k
            inverted_index_get_ret =
3865
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
3866
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3867
27.5k
                                     &inverted_index_get_ret);
3868
27.5k
            if (inverted_index_get_ret == 0) {
3869
27.0k
                index_format = index_info.first;
3870
27.0k
                index_ids = index_info.second;
3871
27.0k
            } else if (inverted_index_get_ret == 1) {
3872
                // 1. Schema kv not found means tablet has been recycled
3873
                // Maybe some tablet recycle failed by some bugs
3874
                // We need to delete again to double check
3875
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3876
                // because we are uncertain about the inverted index information.
3877
                // If there are inverted indexes, some data might not be deleted,
3878
                // but this is acceptable as we have made our best effort to delete the data.
3879
503
                LOG_INFO(
3880
503
                        "delete rowset data schema kv not found, need to delete again to "
3881
503
                        "double "
3882
503
                        "check")
3883
503
                        .tag("instance_id", instance_id_)
3884
503
                        .tag("tablet_id", tablet_id)
3885
503
                        .tag("rowset", rs.ShortDebugString());
3886
                // Currently index_ids is guaranteed to be empty,
3887
                // but we clear it again here as a safeguard against future code changes
3888
                // that might cause index_ids to no longer be empty
3889
503
                index_format = InvertedIndexStorageFormatPB::V2;
3890
503
                index_ids.clear();
3891
18.4E
            } else {
3892
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
3893
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
3894
18.4E
                ret = -1;
3895
18.4E
                continue;
3896
18.4E
            }
3897
27.5k
        }
3898
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3899
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3900
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3901
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
3902
5
            continue;
3903
5
        }
3904
323k
        for (int64_t i = 0; i < num_segments; ++i) {
3905
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
3906
269k
                                             &file_paths);
3907
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
3908
535k
                for (const auto& index_id : index_ids) {
3909
535k
                    add_file_to_delete_if_not_packed(
3910
535k
                            rs,
3911
535k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3912
535k
                                                   index_id.second),
3913
535k
                            &file_paths);
3914
535k
                }
3915
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
3916
                // try to recycle inverted index v2 when get_ret == 1
3917
                // we treat schema not found as if it has a v2 format inverted index
3918
                // to reduce chance of data leakage
3919
2.50k
                if (inverted_index_get_ret == 1) {
3920
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
3921
2.50k
                            .tag("instance_id", instance_id_)
3922
2.50k
                            .tag("inverted index v2 path",
3923
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
3924
2.50k
                }
3925
2.50k
                add_file_to_delete_if_not_packed(
3926
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3927
2.50k
            }
3928
269k
        }
3929
54.1k
    }
3930
3931
64
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
3932
64
                                                 "delete_rowset_data",
3933
64
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
3933
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
3933
50
                                                 [](const int& ret) { return ret != 0; });
3934
64
    for (auto& [resource_id, file_paths] : resource_file_paths) {
3935
50
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3936
50
            DCHECK(accessor_map_.count(*rid))
3937
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3938
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3939
50
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3940
50
                                     &accessor_map_);
3941
50
            if (!accessor_map_.contains(*rid)) {
3942
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3943
0
                        .tag("resource_id", resource_id)
3944
0
                        .tag("instance_id", instance_id_);
3945
0
                return -1;
3946
0
            }
3947
50
            auto& accessor = accessor_map_[*rid];
3948
50
            int ret = accessor->delete_files(*paths);
3949
50
            if (!ret) {
3950
                // deduplication of different files with the same rowset id
3951
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3952
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3953
50
                std::set<std::string> deleted_rowset_id;
3954
3955
50
                std::for_each(paths->begin(), paths->end(),
3956
50
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3957
857k
                               this](const std::string& path) {
3958
857k
                                  std::vector<std::string> str;
3959
857k
                                  butil::SplitString(path, '/', &str);
3960
857k
                                  std::string rowset_id;
3961
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3962
853k
                                      rowset_id = str.back().substr(0, pos);
3963
853k
                                  } else {
3964
4.06k
                                      if (path.find("packed_file/") != std::string::npos) {
3965
0
                                          return; // packed files do not have rowset_id encoded
3966
0
                                      }
3967
4.06k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3968
4.06k
                                      return;
3969
4.06k
                                  }
3970
853k
                                  auto rs_meta = rowsets.find(rowset_id);
3971
853k
                                  if (rs_meta != rowsets.end() &&
3972
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
3973
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3974
54.1k
                                      metrics_context.total_recycled_data_size +=
3975
54.1k
                                              rs_meta->second.total_disk_size();
3976
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3977
54.1k
                                              rs_meta->second.num_segments();
3978
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3979
54.1k
                                              rs_meta->second.total_disk_size();
3980
54.1k
                                      metrics_context.total_recycled_num++;
3981
54.1k
                                  }
3982
853k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3957
7
                               this](const std::string& path) {
3958
7
                                  std::vector<std::string> str;
3959
7
                                  butil::SplitString(path, '/', &str);
3960
7
                                  std::string rowset_id;
3961
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3962
7
                                      rowset_id = str.back().substr(0, pos);
3963
7
                                  } else {
3964
0
                                      if (path.find("packed_file/") != std::string::npos) {
3965
0
                                          return; // packed files do not have rowset_id encoded
3966
0
                                      }
3967
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3968
0
                                      return;
3969
0
                                  }
3970
7
                                  auto rs_meta = rowsets.find(rowset_id);
3971
7
                                  if (rs_meta != rowsets.end() &&
3972
7
                                      !deleted_rowset_id.contains(rowset_id)) {
3973
7
                                      deleted_rowset_id.emplace(rowset_id);
3974
7
                                      metrics_context.total_recycled_data_size +=
3975
7
                                              rs_meta->second.total_disk_size();
3976
7
                                      segment_metrics_context_.total_recycled_num +=
3977
7
                                              rs_meta->second.num_segments();
3978
7
                                      segment_metrics_context_.total_recycled_data_size +=
3979
7
                                              rs_meta->second.total_disk_size();
3980
7
                                      metrics_context.total_recycled_num++;
3981
7
                                  }
3982
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
3957
857k
                               this](const std::string& path) {
3958
857k
                                  std::vector<std::string> str;
3959
857k
                                  butil::SplitString(path, '/', &str);
3960
857k
                                  std::string rowset_id;
3961
857k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3962
853k
                                      rowset_id = str.back().substr(0, pos);
3963
853k
                                  } else {
3964
4.06k
                                      if (path.find("packed_file/") != std::string::npos) {
3965
0
                                          return; // packed files do not have rowset_id encoded
3966
0
                                      }
3967
4.06k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3968
4.06k
                                      return;
3969
4.06k
                                  }
3970
853k
                                  auto rs_meta = rowsets.find(rowset_id);
3971
853k
                                  if (rs_meta != rowsets.end() &&
3972
857k
                                      !deleted_rowset_id.contains(rowset_id)) {
3973
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
3974
54.1k
                                      metrics_context.total_recycled_data_size +=
3975
54.1k
                                              rs_meta->second.total_disk_size();
3976
54.1k
                                      segment_metrics_context_.total_recycled_num +=
3977
54.1k
                                              rs_meta->second.num_segments();
3978
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
3979
54.1k
                                              rs_meta->second.total_disk_size();
3980
54.1k
                                      metrics_context.total_recycled_num++;
3981
54.1k
                                  }
3982
853k
                              });
3983
50
            }
3984
50
            return ret;
3985
50
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3935
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3936
5
            DCHECK(accessor_map_.count(*rid))
3937
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3938
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3939
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3940
5
                                     &accessor_map_);
3941
5
            if (!accessor_map_.contains(*rid)) {
3942
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3943
0
                        .tag("resource_id", resource_id)
3944
0
                        .tag("instance_id", instance_id_);
3945
0
                return -1;
3946
0
            }
3947
5
            auto& accessor = accessor_map_[*rid];
3948
5
            int ret = accessor->delete_files(*paths);
3949
5
            if (!ret) {
3950
                // deduplication of different files with the same rowset id
3951
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3952
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3953
5
                std::set<std::string> deleted_rowset_id;
3954
3955
5
                std::for_each(paths->begin(), paths->end(),
3956
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3957
5
                               this](const std::string& path) {
3958
5
                                  std::vector<std::string> str;
3959
5
                                  butil::SplitString(path, '/', &str);
3960
5
                                  std::string rowset_id;
3961
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3962
5
                                      rowset_id = str.back().substr(0, pos);
3963
5
                                  } else {
3964
5
                                      if (path.find("packed_file/") != std::string::npos) {
3965
5
                                          return; // packed files do not have rowset_id encoded
3966
5
                                      }
3967
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3968
5
                                      return;
3969
5
                                  }
3970
5
                                  auto rs_meta = rowsets.find(rowset_id);
3971
5
                                  if (rs_meta != rowsets.end() &&
3972
5
                                      !deleted_rowset_id.contains(rowset_id)) {
3973
5
                                      deleted_rowset_id.emplace(rowset_id);
3974
5
                                      metrics_context.total_recycled_data_size +=
3975
5
                                              rs_meta->second.total_disk_size();
3976
5
                                      segment_metrics_context_.total_recycled_num +=
3977
5
                                              rs_meta->second.num_segments();
3978
5
                                      segment_metrics_context_.total_recycled_data_size +=
3979
5
                                              rs_meta->second.total_disk_size();
3980
5
                                      metrics_context.total_recycled_num++;
3981
5
                                  }
3982
5
                              });
3983
5
            }
3984
5
            return ret;
3985
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
3935
45
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
3936
45
            DCHECK(accessor_map_.count(*rid))
3937
0
                    << "uninitilized accessor, instance_id=" << instance_id_
3938
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
3939
45
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
3940
45
                                     &accessor_map_);
3941
45
            if (!accessor_map_.contains(*rid)) {
3942
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
3943
0
                        .tag("resource_id", resource_id)
3944
0
                        .tag("instance_id", instance_id_);
3945
0
                return -1;
3946
0
            }
3947
45
            auto& accessor = accessor_map_[*rid];
3948
45
            int ret = accessor->delete_files(*paths);
3949
45
            if (!ret) {
3950
                // deduplication of different files with the same rowset id
3951
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
3952
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
3953
45
                std::set<std::string> deleted_rowset_id;
3954
3955
45
                std::for_each(paths->begin(), paths->end(),
3956
45
                              [&metrics_context, &rowsets, &deleted_rowset_id,
3957
45
                               this](const std::string& path) {
3958
45
                                  std::vector<std::string> str;
3959
45
                                  butil::SplitString(path, '/', &str);
3960
45
                                  std::string rowset_id;
3961
45
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
3962
45
                                      rowset_id = str.back().substr(0, pos);
3963
45
                                  } else {
3964
45
                                      if (path.find("packed_file/") != std::string::npos) {
3965
45
                                          return; // packed files do not have rowset_id encoded
3966
45
                                      }
3967
45
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
3968
45
                                      return;
3969
45
                                  }
3970
45
                                  auto rs_meta = rowsets.find(rowset_id);
3971
45
                                  if (rs_meta != rowsets.end() &&
3972
45
                                      !deleted_rowset_id.contains(rowset_id)) {
3973
45
                                      deleted_rowset_id.emplace(rowset_id);
3974
45
                                      metrics_context.total_recycled_data_size +=
3975
45
                                              rs_meta->second.total_disk_size();
3976
45
                                      segment_metrics_context_.total_recycled_num +=
3977
45
                                              rs_meta->second.num_segments();
3978
45
                                      segment_metrics_context_.total_recycled_data_size +=
3979
45
                                              rs_meta->second.total_disk_size();
3980
45
                                      metrics_context.total_recycled_num++;
3981
45
                                  }
3982
45
                              });
3983
45
            }
3984
45
            return ret;
3985
45
        });
3986
50
    }
3987
64
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
3988
5
        LOG_INFO(
3989
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
3990
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
3991
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
3992
5
        concurrent_delete_executor.add([&]() -> int {
3993
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3994
5
            if (!ret) {
3995
5
                auto rs = rowsets.at(rowset_id);
3996
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3997
5
                metrics_context.total_recycled_num++;
3998
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3999
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4000
5
            }
4001
5
            return ret;
4002
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
3992
5
        concurrent_delete_executor.add([&]() -> int {
3993
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
3994
5
            if (!ret) {
3995
5
                auto rs = rowsets.at(rowset_id);
3996
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
3997
5
                metrics_context.total_recycled_num++;
3998
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
3999
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4000
5
            }
4001
5
            return ret;
4002
5
        });
4003
5
    }
4004
4005
64
    bool finished = true;
4006
64
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4007
64
    for (int r : rets) {
4008
55
        if (r != 0) {
4009
0
            ret = -1;
4010
0
            break;
4011
0
        }
4012
55
    }
4013
64
    ret = finished ? ret : -1;
4014
64
    return ret;
4015
64
}
4016
4017
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4018
3.30k
                                         const std::string& rowset_id) {
4019
3.30k
    auto it = accessor_map_.find(resource_id);
4020
3.30k
    if (it == accessor_map_.end()) {
4021
400
        LOG_WARNING("instance has no such resource id")
4022
400
                .tag("instance_id", instance_id_)
4023
400
                .tag("resource_id", resource_id)
4024
400
                .tag("tablet_id", tablet_id)
4025
400
                .tag("rowset_id", rowset_id);
4026
400
        return -1;
4027
400
    }
4028
2.90k
    auto& accessor = it->second;
4029
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4030
3.30k
}
4031
4032
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4033
4
    if (key.empty()) {
4034
0
        return false;
4035
0
    }
4036
4
    std::string_view key_view = key;
4037
4
    key_view.remove_prefix(1); // remove keyspace prefix
4038
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4039
4
    if (decode_key(&key_view, &decoded) != 0) {
4040
0
        return false;
4041
0
    }
4042
4
    if (decoded.size() < 4) {
4043
0
        return false;
4044
0
    }
4045
4
    try {
4046
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4047
4
    } catch (const std::bad_variant_access&) {
4048
0
        return false;
4049
0
    }
4050
4
    return true;
4051
4
}
4052
4053
14
int InstanceRecycler::recycle_packed_files() {
4054
14
    const std::string task_name = "recycle_packed_files";
4055
14
    auto start_tp = steady_clock::now();
4056
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4057
14
    int ret = 0;
4058
14
    PackedFileRecycleStats stats;
4059
4060
14
    register_recycle_task(task_name, start_time);
4061
14
    DORIS_CLOUD_DEFER {
4062
14
        unregister_recycle_task(task_name);
4063
14
        int64_t cost =
4064
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4065
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4066
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4067
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4068
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4069
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4070
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4071
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4072
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4073
14
                                                             stats.bytes_object_deleted);
4074
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4075
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4076
14
                .tag("instance_id", instance_id_)
4077
14
                .tag("num_scanned", stats.num_scanned)
4078
14
                .tag("num_corrected", stats.num_corrected)
4079
14
                .tag("num_deleted", stats.num_deleted)
4080
14
                .tag("num_failed", stats.num_failed)
4081
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4082
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4083
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4084
14
                .tag("bytes_deleted", stats.bytes_deleted)
4085
14
                .tag("ret", ret);
4086
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4061
14
    DORIS_CLOUD_DEFER {
4062
14
        unregister_recycle_task(task_name);
4063
14
        int64_t cost =
4064
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4065
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4066
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4067
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4068
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4069
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4070
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4071
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4072
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4073
14
                                                             stats.bytes_object_deleted);
4074
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4075
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4076
14
                .tag("instance_id", instance_id_)
4077
14
                .tag("num_scanned", stats.num_scanned)
4078
14
                .tag("num_corrected", stats.num_corrected)
4079
14
                .tag("num_deleted", stats.num_deleted)
4080
14
                .tag("num_failed", stats.num_failed)
4081
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4082
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4083
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4084
14
                .tag("bytes_deleted", stats.bytes_deleted)
4085
14
                .tag("ret", ret);
4086
14
    };
4087
4088
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4089
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4090
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4091
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
4088
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4089
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4090
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4091
4
    };
4092
4093
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4094
4095
14
    std::string begin = packed_file_key({instance_id_, ""});
4096
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4097
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4098
0
        ret = -1;
4099
0
    }
4100
4101
14
    return ret;
4102
14
}
4103
4104
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4105
                                                  RecyclerMetricsContext& metrics_context,
4106
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4107
0
    std::string tablet_key_begin, tablet_key_end;
4108
4109
0
    if (partition_id > 0) {
4110
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4111
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4112
0
    } else {
4113
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4114
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4115
0
    }
4116
    // for calculate the total num or bytes of recyled objects
4117
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4118
0
                                                          std::string_view v) -> int {
4119
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4120
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4121
0
            return 0;
4122
0
        }
4123
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4124
4125
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4126
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4127
0
            return 0;
4128
0
        }
4129
4130
0
        if (!is_empty_tablet) {
4131
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4132
0
                return 0;
4133
0
            }
4134
0
            tablet_metrics_context_.total_need_recycle_num++;
4135
0
        }
4136
0
        return 0;
4137
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_
4138
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4139
0
    metrics_context.report(true);
4140
0
    tablet_metrics_context_.report(true);
4141
0
    segment_metrics_context_.report(true);
4142
0
    return ret;
4143
0
}
4144
4145
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4146
0
                                                 RecyclerMetricsContext& metrics_context) {
4147
0
    int ret = 0;
4148
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4149
0
    std::unique_ptr<Transaction> txn;
4150
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4151
0
        LOG_WARNING("failed to recycle tablet ")
4152
0
                .tag("tablet id", tablet_id)
4153
0
                .tag("instance_id", instance_id_)
4154
0
                .tag("reason", "failed to create txn");
4155
0
        ret = -1;
4156
0
    }
4157
0
    GetRowsetResponse resp;
4158
0
    std::string msg;
4159
0
    MetaServiceCode code = MetaServiceCode::OK;
4160
    // get rowsets in tablet
4161
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4162
0
                        tablet_id, code, msg, &resp);
4163
0
    if (code != MetaServiceCode::OK) {
4164
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4165
0
                .tag("tablet id", tablet_id)
4166
0
                .tag("msg", msg)
4167
0
                .tag("code", code)
4168
0
                .tag("instance id", instance_id_);
4169
0
        ret = -1;
4170
0
    }
4171
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4172
        /*
4173
        * For compatibility, we skip the loop for [0-1] here.
4174
        * The purpose of this loop is to delete object files,
4175
        * and since [0-1] only has meta and doesn't have object files,
4176
        * skipping it doesn't affect system correctness.
4177
        *
4178
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4179
        * would return error -1 directly, causing the recycle operation to fail.
4180
        *
4181
        * [0-1] doesn't have resource id is a bug.
4182
        * In the future, we will fix this problem, after that,
4183
        * we can remove this if statement.
4184
        *
4185
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4186
        */
4187
4188
0
        if (rs_meta.end_version() == 1) {
4189
            // Assert that [0-1] has no resource_id to make sure
4190
            // this if statement will not be forgetted to remove
4191
            // when the resource id bug is fixed
4192
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4193
0
            continue;
4194
0
        }
4195
0
        if (!rs_meta.has_resource_id()) {
4196
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4197
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4198
0
                    .tag("instance_id", instance_id_)
4199
0
                    .tag("tablet_id", tablet_id);
4200
0
            continue;
4201
0
        }
4202
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4203
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4204
        // possible if the accessor is not initilized correctly
4205
0
        if (it == accessor_map_.end()) [[unlikely]] {
4206
0
            LOG_WARNING(
4207
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4208
0
                    "recycle process")
4209
0
                    .tag("tablet id", tablet_id)
4210
0
                    .tag("instance_id", instance_id_)
4211
0
                    .tag("resource_id", rs_meta.resource_id())
4212
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4213
0
            continue;
4214
0
        }
4215
4216
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4217
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4218
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4219
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4220
0
    }
4221
0
    return ret;
4222
0
}
4223
4224
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4225
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4226
4.26k
            .tag("instance_id", instance_id_)
4227
4.26k
            .tag("tablet_id", tablet_id);
4228
4229
4.26k
    if (should_recycle_versioned_keys()) {
4230
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4231
14
        if (ret != 0) {
4232
0
            return ret;
4233
0
        }
4234
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4235
        // during the recycle_versioned_tablet process.
4236
        //
4237
        // .. And remove restore job rowsets of this tablet too
4238
14
    }
4239
4240
4.26k
    int ret = 0;
4241
4.26k
    auto start_time = steady_clock::now();
4242
4243
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4244
4245
    // collect resource ids
4246
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4247
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4248
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4249
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4250
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4251
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4252
4253
260
    std::set<std::string> resource_ids;
4254
260
    int64_t recycle_rowsets_number = 0;
4255
260
    int64_t recycle_segments_number = 0;
4256
260
    int64_t recycle_rowsets_data_size = 0;
4257
260
    int64_t recycle_rowsets_index_size = 0;
4258
260
    int64_t recycle_restore_job_rowsets_number = 0;
4259
260
    int64_t recycle_restore_job_segments_number = 0;
4260
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4261
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4262
260
    int64_t max_rowset_version = 0;
4263
260
    int64_t min_rowset_creation_time = INT64_MAX;
4264
260
    int64_t max_rowset_creation_time = 0;
4265
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4266
260
    int64_t max_rowset_expiration_time = 0;
4267
4268
260
    DORIS_CLOUD_DEFER {
4269
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4270
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4271
260
                .tag("instance_id", instance_id_)
4272
260
                .tag("tablet_id", tablet_id)
4273
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4274
260
                .tag("recycle segments number", recycle_segments_number)
4275
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4276
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4277
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4278
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4279
260
                .tag("all restore job rowsets recycle data size",
4280
260
                     recycle_restore_job_rowsets_data_size)
4281
260
                .tag("all restore job rowsets recycle index size",
4282
260
                     recycle_restore_job_rowsets_index_size)
4283
260
                .tag("max rowset version", max_rowset_version)
4284
260
                .tag("min rowset creation time", min_rowset_creation_time)
4285
260
                .tag("max rowset creation time", max_rowset_creation_time)
4286
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4287
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4288
260
                .tag("task type", metrics_context.operation_type)
4289
260
                .tag("ret", ret);
4290
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4268
260
    DORIS_CLOUD_DEFER {
4269
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4270
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4271
260
                .tag("instance_id", instance_id_)
4272
260
                .tag("tablet_id", tablet_id)
4273
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4274
260
                .tag("recycle segments number", recycle_segments_number)
4275
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4276
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4277
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4278
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4279
260
                .tag("all restore job rowsets recycle data size",
4280
260
                     recycle_restore_job_rowsets_data_size)
4281
260
                .tag("all restore job rowsets recycle index size",
4282
260
                     recycle_restore_job_rowsets_index_size)
4283
260
                .tag("max rowset version", max_rowset_version)
4284
260
                .tag("min rowset creation time", min_rowset_creation_time)
4285
260
                .tag("max rowset creation time", max_rowset_creation_time)
4286
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4287
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4288
260
                .tag("task type", metrics_context.operation_type)
4289
260
                .tag("ret", ret);
4290
260
    };
4291
4292
260
    std::unique_ptr<Transaction> txn;
4293
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4294
0
        LOG_WARNING("failed to recycle tablet ")
4295
0
                .tag("tablet id", tablet_id)
4296
0
                .tag("instance_id", instance_id_)
4297
0
                .tag("reason", "failed to create txn");
4298
0
        ret = -1;
4299
0
    }
4300
260
    GetRowsetResponse resp;
4301
260
    std::string msg;
4302
260
    MetaServiceCode code = MetaServiceCode::OK;
4303
    // get rowsets in tablet
4304
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4305
260
                        tablet_id, code, msg, &resp);
4306
260
    if (code != MetaServiceCode::OK) {
4307
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4308
0
                .tag("tablet id", tablet_id)
4309
0
                .tag("msg", msg)
4310
0
                .tag("code", code)
4311
0
                .tag("instance id", instance_id_);
4312
0
        ret = -1;
4313
0
    }
4314
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4315
4316
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4317
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4318
3
            if (rs_meta.num_segments() <= 0) {
4319
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4320
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4321
2
                        .tag("instance_id", instance_id_)
4322
2
                        .tag("tablet_id", tablet_id);
4323
2
                recycle_rowsets_number += 1;
4324
2
                continue;
4325
2
            }
4326
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4327
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4328
1
                    .tag("instance_id", instance_id_)
4329
1
                    .tag("tablet_id", tablet_id);
4330
1
            return -1;
4331
3
        }
4332
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4333
1
                << "rs_meta" << rs_meta.ShortDebugString();
4334
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4335
        // possible if the accessor is not initilized correctly
4336
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4337
1
            LOG_WARNING(
4338
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4339
1
                    "recycle process")
4340
1
                    .tag("tablet id", tablet_id)
4341
1
                    .tag("instance_id", instance_id_)
4342
1
                    .tag("resource_id", rs_meta.resource_id())
4343
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4344
1
            return -1;
4345
1
        }
4346
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4347
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4348
0
                    .tag("instance_id", instance_id_)
4349
0
                    .tag("tablet_id", tablet_id)
4350
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4351
0
            return -1;
4352
0
        }
4353
2.54k
        recycle_rowsets_number += 1;
4354
2.54k
        recycle_segments_number += rs_meta.num_segments();
4355
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4356
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4357
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4358
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4359
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4360
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4361
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4362
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4363
2.54k
    }
4364
4365
    // get restore job rowset in tablet
4366
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4367
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4368
258
    if (code != MetaServiceCode::OK) {
4369
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4370
0
                .tag("tablet id", tablet_id)
4371
0
                .tag("msg", msg)
4372
0
                .tag("code", code)
4373
0
                .tag("instance id", instance_id_);
4374
0
        return -1;
4375
0
    }
4376
4377
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4378
0
        if (!rs_meta.has_resource_id()) {
4379
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4380
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4381
0
                    .tag("instance_id", instance_id_)
4382
0
                    .tag("tablet_id", tablet_id);
4383
0
            return -1;
4384
0
        }
4385
4386
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4387
        // possible if the accessor is not initilized correctly
4388
0
        if (it == accessor_map_.end()) [[unlikely]] {
4389
0
            LOG_WARNING(
4390
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4391
0
                    "recycle process")
4392
0
                    .tag("tablet id", tablet_id)
4393
0
                    .tag("instance_id", instance_id_)
4394
0
                    .tag("resource_id", rs_meta.resource_id())
4395
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4396
0
            return -1;
4397
0
        }
4398
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4399
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4400
0
                    .tag("instance_id", instance_id_)
4401
0
                    .tag("tablet_id", tablet_id)
4402
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4403
0
            return -1;
4404
0
        }
4405
0
        recycle_restore_job_rowsets_number += 1;
4406
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4407
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4408
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4409
0
        resource_ids.emplace(rs_meta.resource_id());
4410
0
    }
4411
4412
258
    LOG_INFO("recycle tablet start to delete object")
4413
258
            .tag("instance id", instance_id_)
4414
258
            .tag("tablet id", tablet_id)
4415
258
            .tag("recycle tablet resource ids are",
4416
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4417
258
                                 [](std::string rs_id, const auto& it) {
4418
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4419
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
4417
217
                                 [](std::string rs_id, const auto& it) {
4418
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4419
217
                                 }));
4420
4421
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4422
258
            _thread_pool_group.s3_producer_pool,
4423
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4424
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
4424
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4425
4426
    // delete all rowset data in this tablet
4427
    // ATTN: there may be data leak if not all accessor initilized successfully
4428
    //       partial data deleted if the tablet is stored cross-storage vault
4429
    //       vault id is not attached to TabletMeta...
4430
258
    for (const auto& resource_id : resource_ids) {
4431
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4432
217
        concurrent_delete_executor.add(
4433
217
                [&, rs_id = resource_id,
4434
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4435
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4436
217
                    if (res != 0) {
4437
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4438
3
                                     << " path=" << accessor_ptr->uri()
4439
3
                                     << " task type=" << metrics_context.operation_type;
4440
3
                        return std::make_pair(-1, rs_id);
4441
3
                    }
4442
214
                    return std::make_pair(0, rs_id);
4443
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4434
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4435
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4436
217
                    if (res != 0) {
4437
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4438
3
                                     << " path=" << accessor_ptr->uri()
4439
3
                                     << " task type=" << metrics_context.operation_type;
4440
3
                        return std::make_pair(-1, rs_id);
4441
3
                    }
4442
214
                    return std::make_pair(0, rs_id);
4443
217
                });
4444
217
    }
4445
4446
258
    bool finished = true;
4447
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4448
258
    for (auto& r : rets) {
4449
217
        if (r.first != 0) {
4450
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4451
3
            ret = -1;
4452
3
        }
4453
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4454
217
    }
4455
258
    ret = finished ? ret : -1;
4456
4457
258
    if (ret != 0) { // failed recycle tablet data
4458
3
        LOG_WARNING("ret!=0")
4459
3
                .tag("finished", finished)
4460
3
                .tag("ret", ret)
4461
3
                .tag("instance_id", instance_id_)
4462
3
                .tag("tablet_id", tablet_id);
4463
3
        return ret;
4464
3
    }
4465
4466
255
    tablet_metrics_context_.total_recycled_data_size +=
4467
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4468
255
    tablet_metrics_context_.total_recycled_num += 1;
4469
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4470
255
    segment_metrics_context_.total_recycled_data_size +=
4471
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4472
255
    metrics_context.total_recycled_data_size +=
4473
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4474
255
    tablet_metrics_context_.report();
4475
255
    segment_metrics_context_.report();
4476
255
    metrics_context.report();
4477
4478
255
    txn.reset();
4479
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4480
0
        LOG_WARNING("failed to recycle tablet ")
4481
0
                .tag("tablet id", tablet_id)
4482
0
                .tag("instance_id", instance_id_)
4483
0
                .tag("reason", "failed to create txn");
4484
0
        ret = -1;
4485
0
    }
4486
    // delete all rowset kv in this tablet
4487
255
    txn->remove(rs_key0, rs_key1);
4488
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4489
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4490
4491
    // remove delete bitmap for MoW table
4492
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4493
255
    txn->remove(pending_key);
4494
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4495
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4496
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4497
4498
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4499
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4500
255
    txn->remove(dbm_start_key, dbm_end_key);
4501
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4502
255
              << " end=" << hex(dbm_end_key);
4503
4504
255
    TxnErrorCode err = txn->commit();
4505
255
    if (err != TxnErrorCode::TXN_OK) {
4506
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4507
0
        ret = -1;
4508
0
    }
4509
4510
255
    if (ret == 0) {
4511
        // All object files under tablet have been deleted
4512
255
        std::lock_guard lock(recycled_tablets_mtx_);
4513
255
        recycled_tablets_.insert(tablet_id);
4514
255
    }
4515
4516
255
    return ret;
4517
258
}
4518
4519
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4520
14
                                               RecyclerMetricsContext& metrics_context) {
4521
14
    int ret = 0;
4522
14
    auto start_time = steady_clock::now();
4523
4524
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4525
4526
    // collect resource ids
4527
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4528
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4529
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4530
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4531
4532
11
    int64_t recycle_rowsets_number = 0;
4533
11
    int64_t recycle_segments_number = 0;
4534
11
    int64_t recycle_rowsets_data_size = 0;
4535
11
    int64_t recycle_rowsets_index_size = 0;
4536
11
    int64_t max_rowset_version = 0;
4537
11
    int64_t min_rowset_creation_time = INT64_MAX;
4538
11
    int64_t max_rowset_creation_time = 0;
4539
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4540
11
    int64_t max_rowset_expiration_time = 0;
4541
4542
11
    DORIS_CLOUD_DEFER {
4543
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4544
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4545
11
                .tag("instance_id", instance_id_)
4546
11
                .tag("tablet_id", tablet_id)
4547
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4548
11
                .tag("recycle segments number", recycle_segments_number)
4549
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4550
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4551
11
                .tag("max rowset version", max_rowset_version)
4552
11
                .tag("min rowset creation time", min_rowset_creation_time)
4553
11
                .tag("max rowset creation time", max_rowset_creation_time)
4554
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4555
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4556
11
                .tag("ret", ret);
4557
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4542
11
    DORIS_CLOUD_DEFER {
4543
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4544
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4545
11
                .tag("instance_id", instance_id_)
4546
11
                .tag("tablet_id", tablet_id)
4547
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4548
11
                .tag("recycle segments number", recycle_segments_number)
4549
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4550
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4551
11
                .tag("max rowset version", max_rowset_version)
4552
11
                .tag("min rowset creation time", min_rowset_creation_time)
4553
11
                .tag("max rowset creation time", max_rowset_creation_time)
4554
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4555
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4556
11
                .tag("ret", ret);
4557
11
    };
4558
4559
11
    std::unique_ptr<Transaction> txn;
4560
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4561
0
        LOG_WARNING("failed to recycle tablet ")
4562
0
                .tag("tablet id", tablet_id)
4563
0
                .tag("instance_id", instance_id_)
4564
0
                .tag("reason", "failed to create txn");
4565
0
        ret = -1;
4566
0
    }
4567
4568
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4569
    // by the related operation logs.
4570
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4571
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4572
11
    MetaReader meta_reader(instance_id_);
4573
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4574
11
    if (err == TxnErrorCode::TXN_OK) {
4575
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4576
11
    }
4577
11
    if (err != TxnErrorCode::TXN_OK) {
4578
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4579
0
                .tag("tablet id", tablet_id)
4580
0
                .tag("err", err)
4581
0
                .tag("instance id", instance_id_);
4582
0
        ret = -1;
4583
0
    }
4584
4585
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4586
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4587
11
            .tag("instance_id", instance_id_)
4588
11
            .tag("tablet_id", tablet_id);
4589
4590
11
    SyncExecutor<int> concurrent_delete_executor(
4591
11
            _thread_pool_group.s3_producer_pool,
4592
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4593
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
4594
4595
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4596
60
        recycle_rowsets_number += 1;
4597
60
        recycle_segments_number += rs_meta.num_segments();
4598
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4599
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4600
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4601
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4602
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4603
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4604
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4605
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4595
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4596
60
        recycle_rowsets_number += 1;
4597
60
        recycle_segments_number += rs_meta.num_segments();
4598
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4599
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4600
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4601
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4602
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4603
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4604
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4605
60
    };
4606
4607
11
    std::vector<RowsetDeleteTask> all_tasks;
4608
4609
11
    auto create_delete_task = [this](const RowsetMetaCloudPB& rs_meta, std::string_view recycle_key,
4610
11
                                     std::string_view non_versioned_rowset_key =
4611
60
                                             "") -> RowsetDeleteTask {
4612
60
        RowsetDeleteTask task;
4613
60
        task.rowset_meta = rs_meta;
4614
60
        task.recycle_rowset_key = std::string(recycle_key);
4615
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4616
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4617
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4618
60
        return task;
4619
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clERKNS_17RowsetMetaCloudPBESt17basic_string_viewIcSt11char_traitsIcEESB_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clERKNS_17RowsetMetaCloudPBESt17basic_string_viewIcSt11char_traitsIcEESB_
Line
Count
Source
4611
60
                                             "") -> RowsetDeleteTask {
4612
60
        RowsetDeleteTask task;
4613
60
        task.rowset_meta = rs_meta;
4614
60
        task.recycle_rowset_key = std::string(recycle_key);
4615
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4616
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4617
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4618
60
        return task;
4619
60
    };
4620
4621
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4622
60
        update_rowset_stats(rs_meta);
4623
        // Version 0-1 rowset has no resource_id and no actual data files,
4624
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4625
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4626
60
        std::string rowset_load_key =
4627
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4628
60
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4629
60
        RowsetDeleteTask task = create_delete_task(
4630
60
                rs_meta, encode_versioned_key(rowset_load_key, versionstamp), rowset_key);
4631
60
        all_tasks.push_back(std::move(task));
4632
60
    }
4633
4634
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4635
0
        update_rowset_stats(rs_meta);
4636
        // Version 0-1 rowset has no resource_id and no actual data files,
4637
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4638
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4639
0
        std::string rowset_compact_key = versioned::meta_rowset_compact_key(
4640
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4641
0
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4642
0
        RowsetDeleteTask task = create_delete_task(
4643
0
                rs_meta, encode_versioned_key(rowset_compact_key, versionstamp), rowset_key);
4644
0
        all_tasks.push_back(std::move(task));
4645
0
    }
4646
4647
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4648
0
        RecycleRowsetPB recycle_rowset;
4649
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4650
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4651
0
            return -1;
4652
0
        }
4653
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4654
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4655
                // in old version, keep this key-value pair and it needs to be checked manually
4656
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4657
0
                return -1;
4658
0
            }
4659
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4660
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4661
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4662
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4663
0
                return -1;
4664
0
            }
4665
            // decode rowset_id
4666
0
            auto k1 = k;
4667
0
            k1.remove_prefix(1);
4668
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4669
0
            decode_key(&k1, &out);
4670
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4671
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4672
0
            LOG_INFO("delete old-version rowset data")
4673
0
                    .tag("instance_id", instance_id_)
4674
0
                    .tag("tablet_id", tablet_id)
4675
0
                    .tag("rowset_id", rowset_id);
4676
4677
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4678
            // so we must use prefix deletion directly instead of batch delete.
4679
0
            concurrent_delete_executor.add(
4680
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4681
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4682
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4683
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
4684
0
        } else {
4685
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4686
            // Version 0-1 rowset has no resource_id and no actual data files,
4687
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4688
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4689
0
            RowsetDeleteTask task = create_delete_task(rowset_meta, k);
4690
0
            all_tasks.push_back(std::move(task));
4691
0
        }
4692
0
        return 0;
4693
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
4694
4695
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4696
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4697
0
                .tag("tablet id", tablet_id)
4698
0
                .tag("instance_id", instance_id_)
4699
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4700
0
        ret = -1;
4701
0
    }
4702
4703
    // Phase 1: Classify tasks by ref_count
4704
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4705
60
    for (auto& task : all_tasks) {
4706
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4707
60
        if (classify_ret < 0) {
4708
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4709
0
                    .tag("instance_id", instance_id_)
4710
0
                    .tag("tablet_id", tablet_id)
4711
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4712
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4713
0
                return recycle_rowset_meta_and_data(t.recycle_rowset_key, t.rowset_meta,
4714
0
                                                    t.non_versioned_rowset_key);
4715
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
4716
0
        }
4717
60
    }
4718
4719
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4720
4721
11
    LOG_INFO("batch delete plan created")
4722
11
            .tag("instance_id", instance_id_)
4723
11
            .tag("tablet_id", tablet_id)
4724
11
            .tag("plan_count", batch_delete_tasks.size());
4725
4726
    // Phase 2: Execute batch delete using existing delete_rowset_data
4727
11
    if (!batch_delete_tasks.empty()) {
4728
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4729
49
        for (const auto& task : batch_delete_tasks) {
4730
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4731
49
            if (task.rowset_meta.resource_id().empty()) {
4732
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4733
10
                        .tag("instance_id", instance_id_)
4734
10
                        .tag("tablet_id", tablet_id)
4735
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4736
10
                continue;
4737
10
            }
4738
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4739
39
        }
4740
4741
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4742
10
        bool delete_success = true;
4743
10
        if (!rowsets_to_delete.empty()) {
4744
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4745
9
                                                         "batch_delete_versioned_tablet");
4746
9
            int delete_ret = delete_rowset_data(
4747
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4748
9
            if (delete_ret != 0) {
4749
0
                LOG_WARNING("batch delete execution failed")
4750
0
                        .tag("instance_id", instance_id_)
4751
0
                        .tag("tablet_id", tablet_id);
4752
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4753
0
                ret = -1;
4754
0
                delete_success = false;
4755
0
            }
4756
9
        }
4757
4758
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4759
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4760
10
        if (delete_success) {
4761
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4762
10
            if (cleanup_ret != 0) {
4763
0
                LOG_WARNING("batch delete cleanup failed")
4764
0
                        .tag("instance_id", instance_id_)
4765
0
                        .tag("tablet_id", tablet_id);
4766
0
                ret = -1;
4767
0
            }
4768
10
        }
4769
10
    }
4770
4771
    // Always wait for fallback tasks to complete before returning
4772
11
    bool finished = true;
4773
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4774
11
    for (int r : rets) {
4775
0
        if (r != 0) {
4776
0
            ret = -1;
4777
0
        }
4778
0
    }
4779
4780
11
    ret = finished ? ret : -1;
4781
4782
11
    if (ret != 0) { // failed recycle tablet data
4783
0
        LOG_WARNING("recycle versioned tablet failed")
4784
0
                .tag("finished", finished)
4785
0
                .tag("ret", ret)
4786
0
                .tag("instance_id", instance_id_)
4787
0
                .tag("tablet_id", tablet_id);
4788
0
        return ret;
4789
0
    }
4790
4791
11
    tablet_metrics_context_.total_recycled_data_size +=
4792
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4793
11
    tablet_metrics_context_.total_recycled_num += 1;
4794
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4795
11
    segment_metrics_context_.total_recycled_data_size +=
4796
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4797
11
    metrics_context.total_recycled_data_size +=
4798
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4799
11
    tablet_metrics_context_.report();
4800
11
    segment_metrics_context_.report();
4801
11
    metrics_context.report();
4802
4803
11
    txn.reset();
4804
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4805
0
        LOG_WARNING("failed to recycle tablet ")
4806
0
                .tag("tablet id", tablet_id)
4807
0
                .tag("instance_id", instance_id_)
4808
0
                .tag("reason", "failed to create txn");
4809
0
        ret = -1;
4810
0
    }
4811
    // delete all rowset kv in this tablet
4812
11
    txn->remove(rs_key0, rs_key1);
4813
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4814
4815
    // remove delete bitmap for MoW table
4816
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4817
11
    txn->remove(pending_key);
4818
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4819
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4820
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4821
4822
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4823
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4824
11
    txn->remove(dbm_start_key, dbm_end_key);
4825
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4826
11
              << " end=" << hex(dbm_end_key);
4827
4828
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
4829
11
    std::string tablet_index_val;
4830
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
4831
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
4832
0
        LOG_WARNING("failed to get tablet index kv")
4833
0
                .tag("instance_id", instance_id_)
4834
0
                .tag("tablet_id", tablet_id)
4835
0
                .tag("err", err);
4836
0
        ret = -1;
4837
11
    } else if (err == TxnErrorCode::TXN_OK) {
4838
        // If the tablet index kv exists, we need to delete it
4839
10
        TabletIndexPB tablet_index_pb;
4840
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
4841
0
            LOG_WARNING("failed to parse tablet index pb")
4842
0
                    .tag("instance_id", instance_id_)
4843
0
                    .tag("tablet_id", tablet_id);
4844
0
            ret = -1;
4845
10
        } else {
4846
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
4847
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
4848
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
4849
10
            txn->remove(versioned_inverted_idx_key);
4850
10
            txn->remove(versioned_idx_key);
4851
10
        }
4852
10
    }
4853
4854
11
    err = txn->commit();
4855
11
    if (err != TxnErrorCode::TXN_OK) {
4856
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4857
0
        ret = -1;
4858
0
    }
4859
4860
11
    if (ret == 0) {
4861
        // All object files under tablet have been deleted
4862
11
        std::lock_guard lock(recycled_tablets_mtx_);
4863
11
        recycled_tablets_.insert(tablet_id);
4864
11
    }
4865
4866
11
    return ret;
4867
11
}
4868
4869
27
int InstanceRecycler::recycle_rowsets() {
4870
27
    if (should_recycle_versioned_keys()) {
4871
5
        return recycle_versioned_rowsets();
4872
5
    }
4873
4874
22
    const std::string task_name = "recycle_rowsets";
4875
22
    int64_t num_scanned = 0;
4876
22
    int64_t num_expired = 0;
4877
22
    int64_t num_prepare = 0;
4878
22
    int64_t num_compacted = 0;
4879
22
    int64_t num_empty_rowset = 0;
4880
22
    size_t total_rowset_key_size = 0;
4881
22
    size_t total_rowset_value_size = 0;
4882
22
    size_t expired_rowset_size = 0;
4883
22
    std::atomic_long num_recycled = 0;
4884
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
4885
4886
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
4887
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
4888
22
    std::string recyc_rs_key0;
4889
22
    std::string recyc_rs_key1;
4890
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
4891
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
4892
4893
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
4894
4895
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
4896
22
    register_recycle_task(task_name, start_time);
4897
4898
22
    DORIS_CLOUD_DEFER {
4899
22
        unregister_recycle_task(task_name);
4900
22
        int64_t cost =
4901
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4902
22
        metrics_context.finish_report();
4903
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4904
22
                .tag("instance_id", instance_id_)
4905
22
                .tag("num_scanned", num_scanned)
4906
22
                .tag("num_expired", num_expired)
4907
22
                .tag("num_recycled", num_recycled)
4908
22
                .tag("num_recycled.prepare", num_prepare)
4909
22
                .tag("num_recycled.compacted", num_compacted)
4910
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4911
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4912
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4913
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
4914
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4898
7
    DORIS_CLOUD_DEFER {
4899
7
        unregister_recycle_task(task_name);
4900
7
        int64_t cost =
4901
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4902
7
        metrics_context.finish_report();
4903
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4904
7
                .tag("instance_id", instance_id_)
4905
7
                .tag("num_scanned", num_scanned)
4906
7
                .tag("num_expired", num_expired)
4907
7
                .tag("num_recycled", num_recycled)
4908
7
                .tag("num_recycled.prepare", num_prepare)
4909
7
                .tag("num_recycled.compacted", num_compacted)
4910
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4911
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4912
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4913
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
4914
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
4898
15
    DORIS_CLOUD_DEFER {
4899
15
        unregister_recycle_task(task_name);
4900
15
        int64_t cost =
4901
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4902
15
        metrics_context.finish_report();
4903
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
4904
15
                .tag("instance_id", instance_id_)
4905
15
                .tag("num_scanned", num_scanned)
4906
15
                .tag("num_expired", num_expired)
4907
15
                .tag("num_recycled", num_recycled)
4908
15
                .tag("num_recycled.prepare", num_prepare)
4909
15
                .tag("num_recycled.compacted", num_compacted)
4910
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
4911
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
4912
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
4913
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
4914
15
    };
4915
4916
22
    std::vector<std::string> rowset_keys;
4917
22
    std::vector<std::string> rowset_keys_to_mark_recycled;
4918
22
    std::vector<std::string> rowset_keys_to_abort;
4919
22
    std::vector<std::string> prepare_rowset_keys_to_delete;
4920
    // rowset_id -> rowset_meta
4921
    // store rowset id and meta for statistics rs size when delete
4922
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
4923
4924
    // Store keys of rowset recycled by background workers
4925
22
    std::mutex async_recycled_rowset_keys_mutex;
4926
22
    std::vector<std::string> async_recycled_rowset_keys;
4927
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
4928
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
4929
22
    worker_pool->start();
4930
    // TODO bacth delete
4931
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4932
4.00k
        std::string dbm_start_key =
4933
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4934
4.00k
        std::string dbm_end_key = dbm_start_key;
4935
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4936
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4937
4.00k
        if (ret != 0) {
4938
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4939
0
                         << instance_id_;
4940
0
        }
4941
4.00k
        return ret;
4942
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4931
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4932
3
        std::string dbm_start_key =
4933
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4934
3
        std::string dbm_end_key = dbm_start_key;
4935
3
        encode_int64(INT64_MAX, &dbm_end_key);
4936
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4937
3
        if (ret != 0) {
4938
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4939
0
                         << instance_id_;
4940
0
        }
4941
3
        return ret;
4942
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
4931
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
4932
4.00k
        std::string dbm_start_key =
4933
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4934
4.00k
        std::string dbm_end_key = dbm_start_key;
4935
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
4936
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4937
4.00k
        if (ret != 0) {
4938
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
4939
0
                         << instance_id_;
4940
0
        }
4941
4.00k
        return ret;
4942
4.00k
    };
4943
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
4944
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4945
        // Try to delete rowset data in background thread
4946
250
        int ret = worker_pool->submit_with_timeout(
4947
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4948
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4949
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4950
0
                        return;
4951
0
                    }
4952
246
                    std::vector<std::string> keys;
4953
246
                    {
4954
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4955
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4956
246
                        if (async_recycled_rowset_keys.size() > 100) {
4957
2
                            keys.swap(async_recycled_rowset_keys);
4958
2
                        }
4959
246
                    }
4960
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4961
246
                    if (keys.empty()) return;
4962
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4963
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4964
0
                                     << instance_id_;
4965
2
                    } else {
4966
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4967
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4968
2
                                           num_recycled, start_time);
4969
2
                    }
4970
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
4947
246
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4948
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4949
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4950
0
                        return;
4951
0
                    }
4952
246
                    std::vector<std::string> keys;
4953
246
                    {
4954
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4955
246
                        async_recycled_rowset_keys.push_back(std::move(key));
4956
246
                        if (async_recycled_rowset_keys.size() > 100) {
4957
2
                            keys.swap(async_recycled_rowset_keys);
4958
2
                        }
4959
246
                    }
4960
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4961
246
                    if (keys.empty()) return;
4962
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4963
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4964
0
                                     << instance_id_;
4965
2
                    } else {
4966
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4967
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4968
2
                                           num_recycled, start_time);
4969
2
                    }
4970
2
                },
4971
250
                0);
4972
250
        if (ret == 0) return 0;
4973
        // Submit task failed, delete rowset data in current thread
4974
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4975
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4976
0
            return -1;
4977
0
        }
4978
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4979
0
            return -1;
4980
0
        }
4981
4
        rowset_keys.push_back(std::move(key));
4982
4
        return 0;
4983
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
4944
250
                                            int64_t tablet_id, const std::string& rowset_id) {
4945
        // Try to delete rowset data in background thread
4946
250
        int ret = worker_pool->submit_with_timeout(
4947
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
4948
250
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4949
250
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4950
250
                        return;
4951
250
                    }
4952
250
                    std::vector<std::string> keys;
4953
250
                    {
4954
250
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
4955
250
                        async_recycled_rowset_keys.push_back(std::move(key));
4956
250
                        if (async_recycled_rowset_keys.size() > 100) {
4957
250
                            keys.swap(async_recycled_rowset_keys);
4958
250
                        }
4959
250
                    }
4960
250
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
4961
250
                    if (keys.empty()) return;
4962
250
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
4963
250
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
4964
250
                                     << instance_id_;
4965
250
                    } else {
4966
250
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
4967
250
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
4968
250
                                           num_recycled, start_time);
4969
250
                    }
4970
250
                },
4971
250
                0);
4972
250
        if (ret == 0) return 0;
4973
        // Submit task failed, delete rowset data in current thread
4974
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
4975
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
4976
0
            return -1;
4977
0
        }
4978
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
4979
0
            return -1;
4980
0
        }
4981
4
        rowset_keys.push_back(std::move(key));
4982
4
        return 0;
4983
4
    };
4984
4985
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
4986
4987
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4988
4.00k
        ++num_scanned;
4989
4.00k
        total_rowset_key_size += k.size();
4990
4.00k
        total_rowset_value_size += v.size();
4991
4.00k
        RecycleRowsetPB rowset;
4992
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4993
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4994
0
            return -1;
4995
0
        }
4996
4997
4.00k
        int64_t current_time = ::time(nullptr);
4998
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4999
5000
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5001
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5002
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5003
4.00k
        if (current_time < expiration) { // not expired
5004
0
            return 0;
5005
0
        }
5006
4.00k
        ++num_expired;
5007
4.00k
        expired_rowset_size += v.size();
5008
5009
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5010
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5011
                // in old version, keep this key-value pair and it needs to be checked manually
5012
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5013
0
                return -1;
5014
0
            }
5015
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5016
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5017
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5018
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5019
0
                rowset_keys.emplace_back(k);
5020
0
                return -1;
5021
0
            }
5022
            // decode rowset_id
5023
250
            auto k1 = k;
5024
250
            k1.remove_prefix(1);
5025
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5026
250
            decode_key(&k1, &out);
5027
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5028
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5029
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5030
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5031
250
                      << " task_type=" << metrics_context.operation_type;
5032
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5033
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5034
0
                return -1;
5035
0
            }
5036
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5037
250
            metrics_context.total_recycled_num++;
5038
250
            segment_metrics_context_.total_recycled_data_size +=
5039
250
                    rowset.rowset_meta().total_disk_size();
5040
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5041
250
            return 0;
5042
250
        }
5043
5044
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5045
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5046
6
            if (need_mark_rowset_as_recycled(rowset)) {
5047
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5048
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5049
4
                             "at next turn, instance_id="
5050
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
4
                          << " version=[" << rowset_meta->start_version() << '-'
5052
4
                          << rowset_meta->end_version() << "]";
5053
4
                return 0;
5054
4
            }
5055
6
        }
5056
5057
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5058
3.75k
            rowset_meta->end_version() != 1) {
5059
2
            if (make_deferred_abort_task(rowset).has_value()) {
5060
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5061
2
                             "instance_id="
5062
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
2
                          << " version=[" << rowset_meta->start_version() << '-'
5064
2
                          << rowset_meta->end_version() << "]";
5065
2
                rowset_keys_to_abort.emplace_back(k);
5066
2
            }
5067
2
        }
5068
5069
        // TODO(plat1ko): check rowset not referenced
5070
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5071
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5072
0
                LOG_INFO("recycle rowset that has empty resource id");
5073
0
            } else {
5074
                // other situations, keep this key-value pair and it needs to be checked manually
5075
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5076
0
                return -1;
5077
0
            }
5078
0
        }
5079
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5080
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5081
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5082
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5083
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5084
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5085
3.75k
                  << " rowset_meta_size=" << v.size()
5086
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5087
3.75k
                  << " task_type=" << metrics_context.operation_type;
5088
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5089
            // unable to calculate file path, can only be deleted by rowset id prefix
5090
653
            num_prepare += 1;
5091
653
            prepare_rowset_keys_to_delete.emplace_back(k);
5092
3.10k
        } else {
5093
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5094
3.10k
            rowset_keys.emplace_back(k);
5095
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5096
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5097
3.10k
                ++num_empty_rowset;
5098
3.10k
            }
5099
3.10k
        }
5100
3.75k
        return 0;
5101
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4987
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4988
7
        ++num_scanned;
4989
7
        total_rowset_key_size += k.size();
4990
7
        total_rowset_value_size += v.size();
4991
7
        RecycleRowsetPB rowset;
4992
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4993
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4994
0
            return -1;
4995
0
        }
4996
4997
7
        int64_t current_time = ::time(nullptr);
4998
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4999
5000
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5001
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5002
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5003
7
        if (current_time < expiration) { // not expired
5004
0
            return 0;
5005
0
        }
5006
7
        ++num_expired;
5007
7
        expired_rowset_size += v.size();
5008
5009
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5010
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5011
                // in old version, keep this key-value pair and it needs to be checked manually
5012
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5013
0
                return -1;
5014
0
            }
5015
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5016
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5017
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5018
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5019
0
                rowset_keys.emplace_back(k);
5020
0
                return -1;
5021
0
            }
5022
            // decode rowset_id
5023
0
            auto k1 = k;
5024
0
            k1.remove_prefix(1);
5025
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5026
0
            decode_key(&k1, &out);
5027
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5028
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5029
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5030
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5031
0
                      << " task_type=" << metrics_context.operation_type;
5032
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5033
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5034
0
                return -1;
5035
0
            }
5036
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5037
0
            metrics_context.total_recycled_num++;
5038
0
            segment_metrics_context_.total_recycled_data_size +=
5039
0
                    rowset.rowset_meta().total_disk_size();
5040
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5041
0
            return 0;
5042
0
        }
5043
5044
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5045
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5046
6
            if (need_mark_rowset_as_recycled(rowset)) {
5047
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5048
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5049
4
                             "at next turn, instance_id="
5050
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
4
                          << " version=[" << rowset_meta->start_version() << '-'
5052
4
                          << rowset_meta->end_version() << "]";
5053
4
                return 0;
5054
4
            }
5055
6
        }
5056
5057
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5058
3
            rowset_meta->end_version() != 1) {
5059
2
            if (make_deferred_abort_task(rowset).has_value()) {
5060
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5061
2
                             "instance_id="
5062
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
2
                          << " version=[" << rowset_meta->start_version() << '-'
5064
2
                          << rowset_meta->end_version() << "]";
5065
2
                rowset_keys_to_abort.emplace_back(k);
5066
2
            }
5067
2
        }
5068
5069
        // TODO(plat1ko): check rowset not referenced
5070
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5071
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5072
0
                LOG_INFO("recycle rowset that has empty resource id");
5073
0
            } else {
5074
                // other situations, keep this key-value pair and it needs to be checked manually
5075
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5076
0
                return -1;
5077
0
            }
5078
0
        }
5079
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5080
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5081
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5082
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5083
3
                  << "] txn_id=" << rowset_meta->txn_id()
5084
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5085
3
                  << " rowset_meta_size=" << v.size()
5086
3
                  << " creation_time=" << rowset_meta->creation_time()
5087
3
                  << " task_type=" << metrics_context.operation_type;
5088
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5089
            // unable to calculate file path, can only be deleted by rowset id prefix
5090
3
            num_prepare += 1;
5091
3
            prepare_rowset_keys_to_delete.emplace_back(k);
5092
3
        } else {
5093
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5094
0
            rowset_keys.emplace_back(k);
5095
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5096
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5097
0
                ++num_empty_rowset;
5098
0
            }
5099
0
        }
5100
3
        return 0;
5101
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
4987
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
4988
4.00k
        ++num_scanned;
4989
4.00k
        total_rowset_key_size += k.size();
4990
4.00k
        total_rowset_value_size += v.size();
4991
4.00k
        RecycleRowsetPB rowset;
4992
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
4993
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4994
0
            return -1;
4995
0
        }
4996
4997
4.00k
        int64_t current_time = ::time(nullptr);
4998
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
4999
5000
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5001
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5002
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5003
4.00k
        if (current_time < expiration) { // not expired
5004
0
            return 0;
5005
0
        }
5006
4.00k
        ++num_expired;
5007
4.00k
        expired_rowset_size += v.size();
5008
5009
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5010
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5011
                // in old version, keep this key-value pair and it needs to be checked manually
5012
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5013
0
                return -1;
5014
0
            }
5015
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5016
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5017
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5018
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5019
0
                rowset_keys.emplace_back(k);
5020
0
                return -1;
5021
0
            }
5022
            // decode rowset_id
5023
250
            auto k1 = k;
5024
250
            k1.remove_prefix(1);
5025
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5026
250
            decode_key(&k1, &out);
5027
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5028
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5029
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5030
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5031
250
                      << " task_type=" << metrics_context.operation_type;
5032
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5033
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5034
0
                return -1;
5035
0
            }
5036
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5037
250
            metrics_context.total_recycled_num++;
5038
250
            segment_metrics_context_.total_recycled_data_size +=
5039
250
                    rowset.rowset_meta().total_disk_size();
5040
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5041
250
            return 0;
5042
250
        }
5043
5044
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5045
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5046
0
            if (need_mark_rowset_as_recycled(rowset)) {
5047
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5048
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5049
0
                             "at next turn, instance_id="
5050
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5051
0
                          << " version=[" << rowset_meta->start_version() << '-'
5052
0
                          << rowset_meta->end_version() << "]";
5053
0
                return 0;
5054
0
            }
5055
0
        }
5056
5057
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5058
3.75k
            rowset_meta->end_version() != 1) {
5059
0
            if (make_deferred_abort_task(rowset).has_value()) {
5060
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5061
0
                             "instance_id="
5062
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5063
0
                          << " version=[" << rowset_meta->start_version() << '-'
5064
0
                          << rowset_meta->end_version() << "]";
5065
0
                rowset_keys_to_abort.emplace_back(k);
5066
0
            }
5067
0
        }
5068
5069
        // TODO(plat1ko): check rowset not referenced
5070
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5071
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5072
0
                LOG_INFO("recycle rowset that has empty resource id");
5073
0
            } else {
5074
                // other situations, keep this key-value pair and it needs to be checked manually
5075
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5076
0
                return -1;
5077
0
            }
5078
0
        }
5079
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5080
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5081
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5082
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5083
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5084
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5085
3.75k
                  << " rowset_meta_size=" << v.size()
5086
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5087
3.75k
                  << " task_type=" << metrics_context.operation_type;
5088
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5089
            // unable to calculate file path, can only be deleted by rowset id prefix
5090
650
            num_prepare += 1;
5091
650
            prepare_rowset_keys_to_delete.emplace_back(k);
5092
3.10k
        } else {
5093
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5094
3.10k
            rowset_keys.emplace_back(k);
5095
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5096
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5097
3.10k
                ++num_empty_rowset;
5098
3.10k
            }
5099
3.10k
        }
5100
3.75k
        return 0;
5101
3.75k
    };
5102
5103
28
    auto loop_done = [&]() -> int {
5104
28
        std::vector<std::string> rowset_keys_to_delete;
5105
28
        std::vector<std::string> mark_keys_to_process;
5106
28
        std::vector<std::string> abort_keys_to_process;
5107
28
        std::vector<std::string> prepare_keys_to_process;
5108
        // rowset_id -> rowset_meta
5109
        // store rowset id and meta for statistics rs size when delete
5110
28
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5111
28
        rowset_keys_to_delete.swap(rowset_keys);
5112
28
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5113
28
        abort_keys_to_process.swap(rowset_keys_to_abort);
5114
28
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5115
28
        rowsets_to_delete.swap(rowsets);
5116
28
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5117
28
                             rowsets_to_delete = std::move(rowsets_to_delete),
5118
28
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5119
28
                             mark_keys_to_process = std::move(mark_keys_to_process),
5120
28
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5121
28
            if (!mark_keys_to_process.empty() &&
5122
28
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5123
4
                                                                mark_keys_to_process) != 0) {
5124
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5125
0
                             << instance_id_;
5126
0
                return;
5127
0
            }
5128
28
            if (!abort_keys_to_process.empty() &&
5129
28
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5130
2
                        0) {
5131
0
                return;
5132
0
            }
5133
28
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5134
28
            if (!prepare_keys_to_process.empty() &&
5135
28
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5136
24
                                             &prepare_delete_tasks) != 0) {
5137
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5138
0
                             << instance_id_;
5139
0
                return;
5140
0
            }
5141
28
            if (!prepare_delete_tasks.empty()) {
5142
24
                std::vector<std::string> prepare_rowset_keys_to_delete;
5143
24
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5144
653
                for (const auto& task : prepare_delete_tasks) {
5145
653
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5146
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5147
0
                        return;
5148
0
                    }
5149
653
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5150
0
                        return;
5151
0
                    }
5152
653
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5153
653
                }
5154
24
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5155
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5156
0
                                 << instance_id_;
5157
0
                    return;
5158
0
                }
5159
24
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5160
24
                                       std::memory_order_relaxed);
5161
24
            }
5162
28
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5163
28
                                   metrics_context) != 0) {
5164
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5165
0
                return;
5166
0
            }
5167
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5168
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5169
0
                    return;
5170
0
                }
5171
3.10k
            }
5172
28
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5173
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5174
0
                return;
5175
0
            }
5176
28
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5177
28
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5120
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5121
7
            if (!mark_keys_to_process.empty() &&
5122
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5123
4
                                                                mark_keys_to_process) != 0) {
5124
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5125
0
                             << instance_id_;
5126
0
                return;
5127
0
            }
5128
7
            if (!abort_keys_to_process.empty() &&
5129
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5130
2
                        0) {
5131
0
                return;
5132
0
            }
5133
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5134
7
            if (!prepare_keys_to_process.empty() &&
5135
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5136
3
                                             &prepare_delete_tasks) != 0) {
5137
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5138
0
                             << instance_id_;
5139
0
                return;
5140
0
            }
5141
7
            if (!prepare_delete_tasks.empty()) {
5142
3
                std::vector<std::string> prepare_rowset_keys_to_delete;
5143
3
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5144
3
                for (const auto& task : prepare_delete_tasks) {
5145
3
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5146
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5147
0
                        return;
5148
0
                    }
5149
3
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5150
0
                        return;
5151
0
                    }
5152
3
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5153
3
                }
5154
3
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5155
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5156
0
                                 << instance_id_;
5157
0
                    return;
5158
0
                }
5159
3
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5160
3
                                       std::memory_order_relaxed);
5161
3
            }
5162
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5163
7
                                   metrics_context) != 0) {
5164
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5165
0
                return;
5166
0
            }
5167
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5168
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5169
0
                    return;
5170
0
                }
5171
0
            }
5172
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5173
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5174
0
                return;
5175
0
            }
5176
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5177
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5120
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5121
21
            if (!mark_keys_to_process.empty() &&
5122
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5123
0
                                                                mark_keys_to_process) != 0) {
5124
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5125
0
                             << instance_id_;
5126
0
                return;
5127
0
            }
5128
21
            if (!abort_keys_to_process.empty() &&
5129
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5130
0
                        0) {
5131
0
                return;
5132
0
            }
5133
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5134
21
            if (!prepare_keys_to_process.empty() &&
5135
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5136
21
                                             &prepare_delete_tasks) != 0) {
5137
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5138
0
                             << instance_id_;
5139
0
                return;
5140
0
            }
5141
21
            if (!prepare_delete_tasks.empty()) {
5142
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5143
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5144
650
                for (const auto& task : prepare_delete_tasks) {
5145
650
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5146
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5147
0
                        return;
5148
0
                    }
5149
650
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5150
0
                        return;
5151
0
                    }
5152
650
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5153
650
                }
5154
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5155
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5156
0
                                 << instance_id_;
5157
0
                    return;
5158
0
                }
5159
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5160
21
                                       std::memory_order_relaxed);
5161
21
            }
5162
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5163
21
                                   metrics_context) != 0) {
5164
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5165
0
                return;
5166
0
            }
5167
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5168
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5169
0
                    return;
5170
0
                }
5171
3.10k
            }
5172
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5173
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5174
0
                return;
5175
0
            }
5176
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5177
21
        });
5178
28
        return 0;
5179
28
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5103
7
    auto loop_done = [&]() -> int {
5104
7
        std::vector<std::string> rowset_keys_to_delete;
5105
7
        std::vector<std::string> mark_keys_to_process;
5106
7
        std::vector<std::string> abort_keys_to_process;
5107
7
        std::vector<std::string> prepare_keys_to_process;
5108
        // rowset_id -> rowset_meta
5109
        // store rowset id and meta for statistics rs size when delete
5110
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5111
7
        rowset_keys_to_delete.swap(rowset_keys);
5112
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5113
7
        abort_keys_to_process.swap(rowset_keys_to_abort);
5114
7
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5115
7
        rowsets_to_delete.swap(rowsets);
5116
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5117
7
                             rowsets_to_delete = std::move(rowsets_to_delete),
5118
7
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5119
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5120
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5121
7
            if (!mark_keys_to_process.empty() &&
5122
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5123
7
                                                                mark_keys_to_process) != 0) {
5124
7
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5125
7
                             << instance_id_;
5126
7
                return;
5127
7
            }
5128
7
            if (!abort_keys_to_process.empty() &&
5129
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5130
7
                        0) {
5131
7
                return;
5132
7
            }
5133
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5134
7
            if (!prepare_keys_to_process.empty() &&
5135
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5136
7
                                             &prepare_delete_tasks) != 0) {
5137
7
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5138
7
                             << instance_id_;
5139
7
                return;
5140
7
            }
5141
7
            if (!prepare_delete_tasks.empty()) {
5142
7
                std::vector<std::string> prepare_rowset_keys_to_delete;
5143
7
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5144
7
                for (const auto& task : prepare_delete_tasks) {
5145
7
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5146
7
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5147
7
                        return;
5148
7
                    }
5149
7
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5150
7
                        return;
5151
7
                    }
5152
7
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5153
7
                }
5154
7
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5155
7
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5156
7
                                 << instance_id_;
5157
7
                    return;
5158
7
                }
5159
7
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5160
7
                                       std::memory_order_relaxed);
5161
7
            }
5162
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5163
7
                                   metrics_context) != 0) {
5164
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5165
7
                return;
5166
7
            }
5167
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5168
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5169
7
                    return;
5170
7
                }
5171
7
            }
5172
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5173
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5174
7
                return;
5175
7
            }
5176
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5177
7
        });
5178
7
        return 0;
5179
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5103
21
    auto loop_done = [&]() -> int {
5104
21
        std::vector<std::string> rowset_keys_to_delete;
5105
21
        std::vector<std::string> mark_keys_to_process;
5106
21
        std::vector<std::string> abort_keys_to_process;
5107
21
        std::vector<std::string> prepare_keys_to_process;
5108
        // rowset_id -> rowset_meta
5109
        // store rowset id and meta for statistics rs size when delete
5110
21
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5111
21
        rowset_keys_to_delete.swap(rowset_keys);
5112
21
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5113
21
        abort_keys_to_process.swap(rowset_keys_to_abort);
5114
21
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5115
21
        rowsets_to_delete.swap(rowsets);
5116
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5117
21
                             rowsets_to_delete = std::move(rowsets_to_delete),
5118
21
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5119
21
                             mark_keys_to_process = std::move(mark_keys_to_process),
5120
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5121
21
            if (!mark_keys_to_process.empty() &&
5122
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5123
21
                                                                mark_keys_to_process) != 0) {
5124
21
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5125
21
                             << instance_id_;
5126
21
                return;
5127
21
            }
5128
21
            if (!abort_keys_to_process.empty() &&
5129
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5130
21
                        0) {
5131
21
                return;
5132
21
            }
5133
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5134
21
            if (!prepare_keys_to_process.empty() &&
5135
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5136
21
                                             &prepare_delete_tasks) != 0) {
5137
21
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5138
21
                             << instance_id_;
5139
21
                return;
5140
21
            }
5141
21
            if (!prepare_delete_tasks.empty()) {
5142
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5143
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5144
21
                for (const auto& task : prepare_delete_tasks) {
5145
21
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5146
21
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5147
21
                        return;
5148
21
                    }
5149
21
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5150
21
                        return;
5151
21
                    }
5152
21
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5153
21
                }
5154
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5155
21
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5156
21
                                 << instance_id_;
5157
21
                    return;
5158
21
                }
5159
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5160
21
                                       std::memory_order_relaxed);
5161
21
            }
5162
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5163
21
                                   metrics_context) != 0) {
5164
21
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5165
21
                return;
5166
21
            }
5167
21
            for (const auto& [_, rs] : rowsets_to_delete) {
5168
21
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5169
21
                    return;
5170
21
                }
5171
21
            }
5172
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5173
21
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5174
21
                return;
5175
21
            }
5176
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5177
21
        });
5178
21
        return 0;
5179
21
    };
5180
5181
22
    if (config::enable_recycler_stats_metrics) {
5182
0
        scan_and_statistics_rowsets();
5183
0
    }
5184
    // recycle_func and loop_done for scan and recycle
5185
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5186
22
                               std::move(loop_done));
5187
5188
22
    worker_pool->stop();
5189
5190
22
    if (!async_recycled_rowset_keys.empty()) {
5191
1
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5192
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5193
0
            return -1;
5194
1
        } else {
5195
1
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5196
1
        }
5197
1
    }
5198
5199
    // Report final metrics after all concurrent tasks completed
5200
22
    segment_metrics_context_.report();
5201
22
    metrics_context.report();
5202
5203
22
    return ret;
5204
22
}
5205
5206
13
int InstanceRecycler::recycle_restore_jobs() {
5207
13
    const std::string task_name = "recycle_restore_jobs";
5208
13
    int64_t num_scanned = 0;
5209
13
    int64_t num_expired = 0;
5210
13
    int64_t num_recycled = 0;
5211
13
    int64_t num_aborted = 0;
5212
5213
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5214
5215
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5216
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5217
13
    std::string restore_job_key0;
5218
13
    std::string restore_job_key1;
5219
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5220
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5221
5222
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5223
5224
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5225
13
    register_recycle_task(task_name, start_time);
5226
5227
13
    DORIS_CLOUD_DEFER {
5228
13
        unregister_recycle_task(task_name);
5229
13
        int64_t cost =
5230
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5231
13
        metrics_context.finish_report();
5232
5233
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5234
13
                .tag("instance_id", instance_id_)
5235
13
                .tag("num_scanned", num_scanned)
5236
13
                .tag("num_expired", num_expired)
5237
13
                .tag("num_recycled", num_recycled)
5238
13
                .tag("num_aborted", num_aborted);
5239
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5227
13
    DORIS_CLOUD_DEFER {
5228
13
        unregister_recycle_task(task_name);
5229
13
        int64_t cost =
5230
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5231
13
        metrics_context.finish_report();
5232
5233
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5234
13
                .tag("instance_id", instance_id_)
5235
13
                .tag("num_scanned", num_scanned)
5236
13
                .tag("num_expired", num_expired)
5237
13
                .tag("num_recycled", num_recycled)
5238
13
                .tag("num_aborted", num_aborted);
5239
13
    };
5240
5241
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5242
5243
13
    std::vector<std::string_view> restore_job_keys;
5244
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5245
41
        ++num_scanned;
5246
41
        RestoreJobCloudPB restore_job_pb;
5247
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5248
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5249
0
            return -1;
5250
0
        }
5251
41
        int64_t expiration =
5252
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5253
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5254
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5255
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5256
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5257
0
                   << " state=" << restore_job_pb.state();
5258
41
        int64_t current_time = ::time(nullptr);
5259
41
        if (current_time < expiration) { // not expired
5260
0
            return 0;
5261
0
        }
5262
41
        ++num_expired;
5263
5264
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5265
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5266
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5267
5268
41
        std::unique_ptr<Transaction> txn;
5269
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5270
41
        if (err != TxnErrorCode::TXN_OK) {
5271
0
            LOG_WARNING("failed to recycle restore job")
5272
0
                    .tag("err", err)
5273
0
                    .tag("tablet id", tablet_id)
5274
0
                    .tag("instance_id", instance_id_)
5275
0
                    .tag("reason", "failed to create txn");
5276
0
            return -1;
5277
0
        }
5278
5279
41
        std::string val;
5280
41
        err = txn->get(k, &val);
5281
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5282
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5283
0
            return 0;
5284
0
        }
5285
41
        if (err != TxnErrorCode::TXN_OK) {
5286
0
            LOG_WARNING("failed to get kv");
5287
0
            return -1;
5288
0
        }
5289
41
        restore_job_pb.Clear();
5290
41
        if (!restore_job_pb.ParseFromString(val)) {
5291
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5292
0
            return -1;
5293
0
        }
5294
5295
        // PREPARED or COMMITTED, change state to DROPPED and return
5296
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5297
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5298
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5299
0
            restore_job_pb.set_need_recycle_data(true);
5300
0
            txn->put(k, restore_job_pb.SerializeAsString());
5301
0
            err = txn->commit();
5302
0
            if (err != TxnErrorCode::TXN_OK) {
5303
0
                LOG_WARNING("failed to commit txn: {}", err);
5304
0
                return -1;
5305
0
            }
5306
0
            num_aborted++;
5307
0
            return 0;
5308
0
        }
5309
5310
        // Change state to RECYCLING
5311
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5312
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5313
21
            txn->put(k, restore_job_pb.SerializeAsString());
5314
21
            err = txn->commit();
5315
21
            if (err != TxnErrorCode::TXN_OK) {
5316
0
                LOG_WARNING("failed to commit txn: {}", err);
5317
0
                return -1;
5318
0
            }
5319
21
            return 0;
5320
21
        }
5321
5322
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5323
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5324
5325
        // Recycle all data associated with the restore job.
5326
        // This includes rowsets, segments, and related resources.
5327
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5328
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5329
0
            LOG_WARNING("failed to recycle tablet")
5330
0
                    .tag("tablet_id", tablet_id)
5331
0
                    .tag("instance_id", instance_id_);
5332
0
            return -1;
5333
0
        }
5334
5335
        // delete all restore job rowset kv
5336
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5337
5338
20
        err = txn->commit();
5339
20
        if (err != TxnErrorCode::TXN_OK) {
5340
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5341
0
                    .tag("err", err)
5342
0
                    .tag("tablet id", tablet_id)
5343
0
                    .tag("instance_id", instance_id_)
5344
0
                    .tag("reason", "failed to commit txn");
5345
0
            return -1;
5346
0
        }
5347
5348
20
        metrics_context.total_recycled_num = ++num_recycled;
5349
20
        metrics_context.report();
5350
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5351
20
        restore_job_keys.push_back(k);
5352
5353
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5354
20
                  << " tablet_id=" << tablet_id;
5355
20
        return 0;
5356
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
5244
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5245
41
        ++num_scanned;
5246
41
        RestoreJobCloudPB restore_job_pb;
5247
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5248
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5249
0
            return -1;
5250
0
        }
5251
41
        int64_t expiration =
5252
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5253
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5254
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5255
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5256
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5257
0
                   << " state=" << restore_job_pb.state();
5258
41
        int64_t current_time = ::time(nullptr);
5259
41
        if (current_time < expiration) { // not expired
5260
0
            return 0;
5261
0
        }
5262
41
        ++num_expired;
5263
5264
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5265
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5266
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5267
5268
41
        std::unique_ptr<Transaction> txn;
5269
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5270
41
        if (err != TxnErrorCode::TXN_OK) {
5271
0
            LOG_WARNING("failed to recycle restore job")
5272
0
                    .tag("err", err)
5273
0
                    .tag("tablet id", tablet_id)
5274
0
                    .tag("instance_id", instance_id_)
5275
0
                    .tag("reason", "failed to create txn");
5276
0
            return -1;
5277
0
        }
5278
5279
41
        std::string val;
5280
41
        err = txn->get(k, &val);
5281
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5282
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5283
0
            return 0;
5284
0
        }
5285
41
        if (err != TxnErrorCode::TXN_OK) {
5286
0
            LOG_WARNING("failed to get kv");
5287
0
            return -1;
5288
0
        }
5289
41
        restore_job_pb.Clear();
5290
41
        if (!restore_job_pb.ParseFromString(val)) {
5291
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5292
0
            return -1;
5293
0
        }
5294
5295
        // PREPARED or COMMITTED, change state to DROPPED and return
5296
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5297
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5298
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5299
0
            restore_job_pb.set_need_recycle_data(true);
5300
0
            txn->put(k, restore_job_pb.SerializeAsString());
5301
0
            err = txn->commit();
5302
0
            if (err != TxnErrorCode::TXN_OK) {
5303
0
                LOG_WARNING("failed to commit txn: {}", err);
5304
0
                return -1;
5305
0
            }
5306
0
            num_aborted++;
5307
0
            return 0;
5308
0
        }
5309
5310
        // Change state to RECYCLING
5311
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5312
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5313
21
            txn->put(k, restore_job_pb.SerializeAsString());
5314
21
            err = txn->commit();
5315
21
            if (err != TxnErrorCode::TXN_OK) {
5316
0
                LOG_WARNING("failed to commit txn: {}", err);
5317
0
                return -1;
5318
0
            }
5319
21
            return 0;
5320
21
        }
5321
5322
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5323
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5324
5325
        // Recycle all data associated with the restore job.
5326
        // This includes rowsets, segments, and related resources.
5327
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5328
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5329
0
            LOG_WARNING("failed to recycle tablet")
5330
0
                    .tag("tablet_id", tablet_id)
5331
0
                    .tag("instance_id", instance_id_);
5332
0
            return -1;
5333
0
        }
5334
5335
        // delete all restore job rowset kv
5336
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5337
5338
20
        err = txn->commit();
5339
20
        if (err != TxnErrorCode::TXN_OK) {
5340
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5341
0
                    .tag("err", err)
5342
0
                    .tag("tablet id", tablet_id)
5343
0
                    .tag("instance_id", instance_id_)
5344
0
                    .tag("reason", "failed to commit txn");
5345
0
            return -1;
5346
0
        }
5347
5348
20
        metrics_context.total_recycled_num = ++num_recycled;
5349
20
        metrics_context.report();
5350
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5351
20
        restore_job_keys.push_back(k);
5352
5353
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5354
20
                  << " tablet_id=" << tablet_id;
5355
20
        return 0;
5356
20
    };
5357
5358
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5359
3
        if (restore_job_keys.empty()) return 0;
5360
1
        DORIS_CLOUD_DEFER {
5361
1
            restore_job_keys.clear();
5362
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5360
1
        DORIS_CLOUD_DEFER {
5361
1
            restore_job_keys.clear();
5362
1
        };
5363
5364
1
        std::unique_ptr<Transaction> txn;
5365
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5366
1
        if (err != TxnErrorCode::TXN_OK) {
5367
0
            LOG_WARNING("failed to recycle restore job")
5368
0
                    .tag("err", err)
5369
0
                    .tag("instance_id", instance_id_)
5370
0
                    .tag("reason", "failed to create txn");
5371
0
            return -1;
5372
0
        }
5373
20
        for (auto& k : restore_job_keys) {
5374
20
            txn->remove(k);
5375
20
        }
5376
1
        err = txn->commit();
5377
1
        if (err != TxnErrorCode::TXN_OK) {
5378
0
            LOG_WARNING("failed to recycle restore job")
5379
0
                    .tag("err", err)
5380
0
                    .tag("instance_id", instance_id_)
5381
0
                    .tag("reason", "failed to commit txn");
5382
0
            return -1;
5383
0
        }
5384
1
        return 0;
5385
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5358
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5359
3
        if (restore_job_keys.empty()) return 0;
5360
1
        DORIS_CLOUD_DEFER {
5361
1
            restore_job_keys.clear();
5362
1
        };
5363
5364
1
        std::unique_ptr<Transaction> txn;
5365
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5366
1
        if (err != TxnErrorCode::TXN_OK) {
5367
0
            LOG_WARNING("failed to recycle restore job")
5368
0
                    .tag("err", err)
5369
0
                    .tag("instance_id", instance_id_)
5370
0
                    .tag("reason", "failed to create txn");
5371
0
            return -1;
5372
0
        }
5373
20
        for (auto& k : restore_job_keys) {
5374
20
            txn->remove(k);
5375
20
        }
5376
1
        err = txn->commit();
5377
1
        if (err != TxnErrorCode::TXN_OK) {
5378
0
            LOG_WARNING("failed to recycle restore job")
5379
0
                    .tag("err", err)
5380
0
                    .tag("instance_id", instance_id_)
5381
0
                    .tag("reason", "failed to commit txn");
5382
0
            return -1;
5383
0
        }
5384
1
        return 0;
5385
1
    };
5386
5387
13
    if (config::enable_recycler_stats_metrics) {
5388
0
        scan_and_statistics_restore_jobs();
5389
0
    }
5390
5391
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5392
13
                            std::move(loop_done));
5393
13
}
5394
5395
9
int InstanceRecycler::recycle_versioned_rowsets() {
5396
9
    const std::string task_name = "recycle_rowsets";
5397
9
    int64_t num_scanned = 0;
5398
9
    int64_t num_expired = 0;
5399
9
    int64_t num_prepare = 0;
5400
9
    int64_t num_compacted = 0;
5401
9
    int64_t num_empty_rowset = 0;
5402
9
    size_t total_rowset_key_size = 0;
5403
9
    size_t total_rowset_value_size = 0;
5404
9
    size_t expired_rowset_size = 0;
5405
9
    std::atomic_long num_recycled = 0;
5406
9
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5407
5408
9
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5409
9
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5410
9
    std::string recyc_rs_key0;
5411
9
    std::string recyc_rs_key1;
5412
9
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5413
9
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5414
5415
9
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5416
5417
9
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5418
9
    register_recycle_task(task_name, start_time);
5419
5420
9
    DORIS_CLOUD_DEFER {
5421
9
        unregister_recycle_task(task_name);
5422
9
        int64_t cost =
5423
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5424
9
        metrics_context.finish_report();
5425
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5426
9
                .tag("instance_id", instance_id_)
5427
9
                .tag("num_scanned", num_scanned)
5428
9
                .tag("num_expired", num_expired)
5429
9
                .tag("num_recycled", num_recycled)
5430
9
                .tag("num_recycled.prepare", num_prepare)
5431
9
                .tag("num_recycled.compacted", num_compacted)
5432
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5433
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5434
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5435
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5436
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5420
9
    DORIS_CLOUD_DEFER {
5421
9
        unregister_recycle_task(task_name);
5422
9
        int64_t cost =
5423
9
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5424
9
        metrics_context.finish_report();
5425
9
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5426
9
                .tag("instance_id", instance_id_)
5427
9
                .tag("num_scanned", num_scanned)
5428
9
                .tag("num_expired", num_expired)
5429
9
                .tag("num_recycled", num_recycled)
5430
9
                .tag("num_recycled.prepare", num_prepare)
5431
9
                .tag("num_recycled.compacted", num_compacted)
5432
9
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5433
9
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5434
9
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5435
9
                .tag("expired_rowset_meta_size", expired_rowset_size);
5436
9
    };
5437
5438
9
    std::vector<std::string> orphan_rowset_keys;
5439
5440
    // Store keys of rowset recycled by background workers
5441
9
    std::mutex async_recycled_rowset_keys_mutex;
5442
9
    std::vector<std::string> async_recycled_rowset_keys;
5443
9
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5444
9
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5445
9
    worker_pool->start();
5446
9
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5447
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5448
        // Try to delete rowset data in background thread
5449
400
        int ret = worker_pool->submit_with_timeout(
5450
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5451
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5452
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5453
400
                        return;
5454
400
                    }
5455
                    // The async recycled rowsets are staled format or has not been used,
5456
                    // so we don't need to check the rowset ref count key.
5457
0
                    std::vector<std::string> keys;
5458
0
                    {
5459
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5460
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5461
0
                        if (async_recycled_rowset_keys.size() > 100) {
5462
0
                            keys.swap(async_recycled_rowset_keys);
5463
0
                        }
5464
0
                    }
5465
0
                    if (keys.empty()) return;
5466
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5467
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5468
0
                                     << instance_id_;
5469
0
                    } else {
5470
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5471
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5472
0
                                           num_recycled, start_time);
5473
0
                    }
5474
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
5450
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5451
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5452
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5453
400
                        return;
5454
400
                    }
5455
                    // The async recycled rowsets are staled format or has not been used,
5456
                    // so we don't need to check the rowset ref count key.
5457
0
                    std::vector<std::string> keys;
5458
0
                    {
5459
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5460
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5461
0
                        if (async_recycled_rowset_keys.size() > 100) {
5462
0
                            keys.swap(async_recycled_rowset_keys);
5463
0
                        }
5464
0
                    }
5465
0
                    if (keys.empty()) return;
5466
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5467
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5468
0
                                     << instance_id_;
5469
0
                    } else {
5470
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5471
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5472
0
                                           num_recycled, start_time);
5473
0
                    }
5474
0
                },
5475
400
                0);
5476
400
        if (ret == 0) return 0;
5477
        // Submit task failed, delete rowset data in current thread
5478
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5479
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5480
0
            return -1;
5481
0
        }
5482
0
        orphan_rowset_keys.push_back(std::move(key));
5483
0
        return 0;
5484
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
5447
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5448
        // Try to delete rowset data in background thread
5449
400
        int ret = worker_pool->submit_with_timeout(
5450
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5451
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5452
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5453
400
                        return;
5454
400
                    }
5455
                    // The async recycled rowsets are staled format or has not been used,
5456
                    // so we don't need to check the rowset ref count key.
5457
400
                    std::vector<std::string> keys;
5458
400
                    {
5459
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5460
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5461
400
                        if (async_recycled_rowset_keys.size() > 100) {
5462
400
                            keys.swap(async_recycled_rowset_keys);
5463
400
                        }
5464
400
                    }
5465
400
                    if (keys.empty()) return;
5466
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5467
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5468
400
                                     << instance_id_;
5469
400
                    } else {
5470
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5471
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5472
400
                                           num_recycled, start_time);
5473
400
                    }
5474
400
                },
5475
400
                0);
5476
400
        if (ret == 0) return 0;
5477
        // Submit task failed, delete rowset data in current thread
5478
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5479
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5480
0
            return -1;
5481
0
        }
5482
0
        orphan_rowset_keys.push_back(std::move(key));
5483
0
        return 0;
5484
0
    };
5485
5486
9
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5487
5488
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5489
2.01k
        ++num_scanned;
5490
2.01k
        total_rowset_key_size += k.size();
5491
2.01k
        total_rowset_value_size += v.size();
5492
2.01k
        RecycleRowsetPB rowset;
5493
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5494
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5495
0
            return -1;
5496
0
        }
5497
5498
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5499
5500
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5501
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5502
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5503
2.01k
        int64_t current_time = ::time(nullptr);
5504
2.01k
        if (current_time < final_expiration) { // not expired
5505
0
            return 0;
5506
0
        }
5507
2.01k
        ++num_expired;
5508
2.01k
        expired_rowset_size += v.size();
5509
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5510
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5511
                // in old version, keep this key-value pair and it needs to be checked manually
5512
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5513
0
                return -1;
5514
0
            }
5515
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5516
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5517
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5518
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5519
0
                orphan_rowset_keys.emplace_back(k);
5520
0
                return -1;
5521
0
            }
5522
            // decode rowset_id
5523
0
            auto k1 = k;
5524
0
            k1.remove_prefix(1);
5525
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5526
0
            decode_key(&k1, &out);
5527
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5528
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5529
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5530
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5531
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5532
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5533
0
                return -1;
5534
0
            }
5535
0
            return 0;
5536
0
        }
5537
        // TODO(plat1ko): check rowset not referenced
5538
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5539
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5540
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5541
0
                LOG_INFO("recycle rowset that has empty resource id");
5542
0
            } else {
5543
                // other situations, keep this key-value pair and it needs to be checked manually
5544
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5545
0
                return -1;
5546
0
            }
5547
0
        }
5548
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5549
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5550
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5551
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5552
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5553
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5554
2.01k
                  << " rowset_meta_size=" << v.size()
5555
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5556
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5557
            // unable to calculate file path, can only be deleted by rowset id prefix
5558
400
            num_prepare += 1;
5559
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5560
400
                                             rowset_meta->tablet_id(),
5561
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5562
0
                return -1;
5563
0
            }
5564
1.61k
        } else {
5565
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5566
1.61k
            worker_pool->submit(
5567
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5568
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5569
1.60k
                            return;
5570
1.60k
                        }
5571
13
                        num_compacted += is_compacted;
5572
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5573
13
                        if (rowset_meta.num_segments() == 0) {
5574
0
                            ++num_empty_rowset;
5575
0
                        }
5576
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
5567
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5568
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5569
1.60k
                            return;
5570
1.60k
                        }
5571
13
                        num_compacted += is_compacted;
5572
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5573
13
                        if (rowset_meta.num_segments() == 0) {
5574
0
                            ++num_empty_rowset;
5575
0
                        }
5576
13
                    });
5577
1.61k
        }
5578
2.01k
        return 0;
5579
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
5488
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5489
2.01k
        ++num_scanned;
5490
2.01k
        total_rowset_key_size += k.size();
5491
2.01k
        total_rowset_value_size += v.size();
5492
2.01k
        RecycleRowsetPB rowset;
5493
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5494
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5495
0
            return -1;
5496
0
        }
5497
5498
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5499
5500
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5501
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5502
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5503
2.01k
        int64_t current_time = ::time(nullptr);
5504
2.01k
        if (current_time < final_expiration) { // not expired
5505
0
            return 0;
5506
0
        }
5507
2.01k
        ++num_expired;
5508
2.01k
        expired_rowset_size += v.size();
5509
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5510
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5511
                // in old version, keep this key-value pair and it needs to be checked manually
5512
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5513
0
                return -1;
5514
0
            }
5515
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5516
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5517
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5518
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5519
0
                orphan_rowset_keys.emplace_back(k);
5520
0
                return -1;
5521
0
            }
5522
            // decode rowset_id
5523
0
            auto k1 = k;
5524
0
            k1.remove_prefix(1);
5525
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5526
0
            decode_key(&k1, &out);
5527
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5528
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5529
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5530
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5531
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5532
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5533
0
                return -1;
5534
0
            }
5535
0
            return 0;
5536
0
        }
5537
        // TODO(plat1ko): check rowset not referenced
5538
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5539
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5540
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5541
0
                LOG_INFO("recycle rowset that has empty resource id");
5542
0
            } else {
5543
                // other situations, keep this key-value pair and it needs to be checked manually
5544
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5545
0
                return -1;
5546
0
            }
5547
0
        }
5548
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5549
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5550
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5551
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5552
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5553
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5554
2.01k
                  << " rowset_meta_size=" << v.size()
5555
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5556
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5557
            // unable to calculate file path, can only be deleted by rowset id prefix
5558
400
            num_prepare += 1;
5559
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5560
400
                                             rowset_meta->tablet_id(),
5561
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5562
0
                return -1;
5563
0
            }
5564
1.61k
        } else {
5565
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5566
1.61k
            worker_pool->submit(
5567
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5568
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5569
1.61k
                            return;
5570
1.61k
                        }
5571
1.61k
                        num_compacted += is_compacted;
5572
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5573
1.61k
                        if (rowset_meta.num_segments() == 0) {
5574
1.61k
                            ++num_empty_rowset;
5575
1.61k
                        }
5576
1.61k
                    });
5577
1.61k
        }
5578
2.01k
        return 0;
5579
2.01k
    };
5580
5581
9
    if (config::enable_recycler_stats_metrics) {
5582
0
        scan_and_statistics_rowsets();
5583
0
    }
5584
5585
9
    auto loop_done = [&]() -> int {
5586
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5587
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5588
0
        }
5589
6
        orphan_rowset_keys.clear();
5590
6
        return 0;
5591
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5585
6
    auto loop_done = [&]() -> int {
5586
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5587
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5588
0
        }
5589
6
        orphan_rowset_keys.clear();
5590
6
        return 0;
5591
6
    };
5592
5593
    // recycle_func and loop_done for scan and recycle
5594
9
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5595
9
                               std::move(loop_done));
5596
5597
9
    worker_pool->stop();
5598
5599
9
    if (!async_recycled_rowset_keys.empty()) {
5600
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5601
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5602
0
            return -1;
5603
0
        } else {
5604
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5605
0
        }
5606
0
    }
5607
5608
    // Report final metrics after all concurrent tasks completed
5609
9
    segment_metrics_context_.report();
5610
9
    metrics_context.report();
5611
5612
9
    return ret;
5613
9
}
5614
5615
int InstanceRecycler::recycle_rowset_meta_and_data(std::string_view recycle_rowset_key,
5616
                                                   const RowsetMetaCloudPB& rowset_meta,
5617
1.61k
                                                   std::string_view non_versioned_rowset_key) {
5618
1.61k
    constexpr int MAX_RETRY = 10;
5619
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5620
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5621
1.61k
    std::string_view reference_instance_id = instance_id_;
5622
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5623
8
        reference_instance_id = rowset_meta.reference_instance_id();
5624
8
    }
5625
5626
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5627
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5628
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(recycle_rowset_key));
5629
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5630
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5631
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5632
1.61k
        std::unique_ptr<Transaction> txn;
5633
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5634
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5635
0
            LOG_WARNING("failed to create txn").tag("err", err);
5636
0
            return -1;
5637
0
        }
5638
5639
1.61k
        std::string rowset_ref_count_key =
5640
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5641
1.61k
        int64_t ref_count = 0;
5642
1.61k
        {
5643
1.61k
            std::string value;
5644
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5645
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5646
                // This is the old version rowset, we could recycle it directly.
5647
1.60k
                ref_count = 1;
5648
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5649
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5650
0
                return -1;
5651
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5652
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5653
0
                return -1;
5654
0
            }
5655
1.61k
        }
5656
5657
1.61k
        if (ref_count == 1) {
5658
            // It would not be added since it is recycling.
5659
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5660
1.60k
                LOG_WARNING("failed to delete rowset data");
5661
1.60k
                return -1;
5662
1.60k
            }
5663
5664
            // Reset the transaction to avoid timeout.
5665
10
            err = txn_kv_->create_txn(&txn);
5666
10
            if (err != TxnErrorCode::TXN_OK) {
5667
0
                LOG_WARNING("failed to create txn").tag("err", err);
5668
0
                return -1;
5669
0
            }
5670
10
            txn->remove(rowset_ref_count_key);
5671
10
            LOG_INFO("delete rowset data ref count key")
5672
10
                    .tag("txn_id", rowset_meta.txn_id())
5673
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5674
5675
10
            std::string dbm_start_key =
5676
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5677
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5678
10
                    {reference_instance_id, tablet_id, rowset_id,
5679
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5680
10
            txn->remove(dbm_start_key, dbm_end_key);
5681
10
            LOG_INFO("remove delete bitmap kv")
5682
10
                    .tag("begin", hex(dbm_start_key))
5683
10
                    .tag("end", hex(dbm_end_key));
5684
5685
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5686
10
                    {reference_instance_id, tablet_id, rowset_id});
5687
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5688
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5689
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5690
10
            LOG_INFO("remove versioned delete bitmap kv")
5691
10
                    .tag("begin", hex(versioned_dbm_start_key))
5692
10
                    .tag("end", hex(versioned_dbm_end_key));
5693
5694
10
            std::string meta_rowset_key_begin =
5695
10
                    versioned::meta_rowset_key({reference_instance_id, tablet_id, rowset_id});
5696
10
            std::string meta_rowset_key_end = meta_rowset_key_begin;
5697
10
            encode_int64(INT64_MAX, &meta_rowset_key_end);
5698
10
            txn->remove(meta_rowset_key_begin, meta_rowset_key_end);
5699
10
            LOG_INFO("remove meta rowset key").tag("key", hex(meta_rowset_key_begin));
5700
10
        } else {
5701
            // Decrease the rowset ref count.
5702
            //
5703
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5704
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5705
3
            txn->atomic_add(rowset_ref_count_key, -1);
5706
3
            LOG_INFO("decrease rowset data ref count")
5707
3
                    .tag("txn_id", rowset_meta.txn_id())
5708
3
                    .tag("ref_count", ref_count - 1)
5709
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5710
3
        }
5711
5712
13
        if (!recycle_rowset_key.empty()) { // empty when recycle ref rowsets for deleted instance
5713
13
            txn->remove(recycle_rowset_key);
5714
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(recycle_rowset_key));
5715
13
        }
5716
13
        if (!non_versioned_rowset_key.empty()) {
5717
0
            txn->remove(non_versioned_rowset_key);
5718
0
            LOG_INFO("remove non versioned rowset key").tag("key", hex(non_versioned_rowset_key));
5719
0
        }
5720
5721
13
        err = txn->commit();
5722
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5723
            // The rowset ref count key has been changed, we need to retry.
5724
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5725
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5726
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5727
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5728
0
            continue;
5729
13
        } else if (err != TxnErrorCode::TXN_OK) {
5730
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5731
0
            return -1;
5732
0
        }
5733
13
        LOG_INFO("recycle rowset meta and data success");
5734
13
        return 0;
5735
13
    }
5736
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5737
0
            .tag("tablet_id", tablet_id)
5738
0
            .tag("rowset_id", rowset_id)
5739
0
            .tag("retry", MAX_RETRY);
5740
0
    return -1;
5741
1.61k
}
5742
5743
29
int InstanceRecycler::recycle_tmp_rowsets() {
5744
29
    const std::string task_name = "recycle_tmp_rowsets";
5745
29
    int64_t num_scanned = 0;
5746
29
    int64_t num_expired = 0;
5747
29
    std::atomic_long num_recycled = 0;
5748
29
    size_t expired_rowset_size = 0;
5749
29
    size_t total_rowset_key_size = 0;
5750
29
    size_t total_rowset_value_size = 0;
5751
29
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5752
5753
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5754
29
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5755
29
    std::string tmp_rs_key0;
5756
29
    std::string tmp_rs_key1;
5757
29
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5758
29
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5759
5760
29
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5761
5762
29
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5763
29
    register_recycle_task(task_name, start_time);
5764
5765
29
    DORIS_CLOUD_DEFER {
5766
29
        unregister_recycle_task(task_name);
5767
29
        int64_t cost =
5768
29
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5769
29
        metrics_context.finish_report();
5770
29
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5771
29
                .tag("instance_id", instance_id_)
5772
29
                .tag("num_scanned", num_scanned)
5773
29
                .tag("num_expired", num_expired)
5774
29
                .tag("num_recycled", num_recycled)
5775
29
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5776
29
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5777
29
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5778
29
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5765
12
    DORIS_CLOUD_DEFER {
5766
12
        unregister_recycle_task(task_name);
5767
12
        int64_t cost =
5768
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5769
12
        metrics_context.finish_report();
5770
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5771
12
                .tag("instance_id", instance_id_)
5772
12
                .tag("num_scanned", num_scanned)
5773
12
                .tag("num_expired", num_expired)
5774
12
                .tag("num_recycled", num_recycled)
5775
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5776
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5777
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5778
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5765
17
    DORIS_CLOUD_DEFER {
5766
17
        unregister_recycle_task(task_name);
5767
17
        int64_t cost =
5768
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5769
17
        metrics_context.finish_report();
5770
17
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5771
17
                .tag("instance_id", instance_id_)
5772
17
                .tag("num_scanned", num_scanned)
5773
17
                .tag("num_expired", num_expired)
5774
17
                .tag("num_recycled", num_recycled)
5775
17
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5776
17
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5777
17
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5778
17
    };
5779
5780
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
5781
5782
29
    std::vector<std::string> tmp_rowset_keys;
5783
29
    std::vector<std::string> tmp_rowset_ref_count_keys;
5784
29
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
5785
29
    std::vector<std::string> tmp_rowset_keys_to_abort;
5786
5787
    // rowset_id -> rowset_meta
5788
    // store tmp_rowset id and meta for statistics rs size when delete
5789
29
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
5790
29
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5791
29
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
5792
29
    worker_pool->start();
5793
5794
29
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5795
5796
29
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
5797
29
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
5798
29
                             &earlest_ts, &tmp_rowset_ref_count_keys,
5799
29
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
5800
51.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5801
51.0k
        ++num_scanned;
5802
51.0k
        total_rowset_key_size += k.size();
5803
51.0k
        total_rowset_value_size += v.size();
5804
51.0k
        doris::RowsetMetaCloudPB rowset;
5805
51.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5806
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5807
0
            return -1;
5808
0
        }
5809
51.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5810
51.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5811
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5812
0
                   << " txn_expiration=" << rowset.txn_expiration()
5813
0
                   << " rowset_creation_time=" << rowset.creation_time();
5814
51.0k
        int64_t current_time = ::time(nullptr);
5815
51.0k
        if (current_time < expiration) { // not expired
5816
0
            return 0;
5817
0
        }
5818
5819
51.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
5820
16
            if (need_mark_rowset_as_recycled(rowset)) {
5821
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5822
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5823
9
                             "at next turn, instance_id="
5824
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5825
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5826
9
                return 0;
5827
9
            }
5828
16
        }
5829
5830
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5831
7
            if (make_deferred_abort_task(rowset).has_value()) {
5832
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5833
3
                             "instance_id="
5834
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5835
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5836
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5837
3
            }
5838
7
        }
5839
5840
51.0k
        ++num_expired;
5841
51.0k
        expired_rowset_size += v.size();
5842
51.0k
        if (!rowset.has_resource_id()) {
5843
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5844
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5845
0
                return -1;
5846
0
            }
5847
            // might be a delete pred rowset
5848
0
            tmp_rowset_keys.emplace_back(k);
5849
0
            return 0;
5850
0
        }
5851
        // TODO(plat1ko): check rowset not referenced
5852
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5853
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5854
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5855
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5856
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5857
51.0k
                  << " num_expired=" << num_expired
5858
51.0k
                  << " task_type=" << metrics_context.operation_type;
5859
5860
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5861
        // Remove the rowset ref count key directly since it has not been used.
5862
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5863
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5864
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5865
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5866
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5867
5868
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5869
51.0k
        return 0;
5870
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5800
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5801
16
        ++num_scanned;
5802
16
        total_rowset_key_size += k.size();
5803
16
        total_rowset_value_size += v.size();
5804
16
        doris::RowsetMetaCloudPB rowset;
5805
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5806
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5807
0
            return -1;
5808
0
        }
5809
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5810
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5811
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5812
0
                   << " txn_expiration=" << rowset.txn_expiration()
5813
0
                   << " rowset_creation_time=" << rowset.creation_time();
5814
16
        int64_t current_time = ::time(nullptr);
5815
16
        if (current_time < expiration) { // not expired
5816
0
            return 0;
5817
0
        }
5818
5819
16
        if (config::enable_mark_delete_rowset_before_recycle) {
5820
16
            if (need_mark_rowset_as_recycled(rowset)) {
5821
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5822
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5823
9
                             "at next turn, instance_id="
5824
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5825
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5826
9
                return 0;
5827
9
            }
5828
16
        }
5829
5830
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5831
7
            if (make_deferred_abort_task(rowset).has_value()) {
5832
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5833
3
                             "instance_id="
5834
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5835
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5836
3
                tmp_rowset_keys_to_abort.emplace_back(k);
5837
3
            }
5838
7
        }
5839
5840
7
        ++num_expired;
5841
7
        expired_rowset_size += v.size();
5842
7
        if (!rowset.has_resource_id()) {
5843
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5844
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5845
0
                return -1;
5846
0
            }
5847
            // might be a delete pred rowset
5848
0
            tmp_rowset_keys.emplace_back(k);
5849
0
            return 0;
5850
0
        }
5851
        // TODO(plat1ko): check rowset not referenced
5852
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5853
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5854
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5855
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5856
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5857
7
                  << " num_expired=" << num_expired
5858
7
                  << " task_type=" << metrics_context.operation_type;
5859
5860
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5861
        // Remove the rowset ref count key directly since it has not been used.
5862
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5863
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5864
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5865
7
                  << "key=" << hex(rowset_ref_count_key);
5866
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5867
5868
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5869
7
        return 0;
5870
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5800
51.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
5801
51.0k
        ++num_scanned;
5802
51.0k
        total_rowset_key_size += k.size();
5803
51.0k
        total_rowset_value_size += v.size();
5804
51.0k
        doris::RowsetMetaCloudPB rowset;
5805
51.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5806
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
5807
0
            return -1;
5808
0
        }
5809
51.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5810
51.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5811
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5812
0
                   << " txn_expiration=" << rowset.txn_expiration()
5813
0
                   << " rowset_creation_time=" << rowset.creation_time();
5814
51.0k
        int64_t current_time = ::time(nullptr);
5815
51.0k
        if (current_time < expiration) { // not expired
5816
0
            return 0;
5817
0
        }
5818
5819
51.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
5820
0
            if (need_mark_rowset_as_recycled(rowset)) {
5821
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
5822
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5823
0
                             "at next turn, instance_id="
5824
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5825
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5826
0
                return 0;
5827
0
            }
5828
0
        }
5829
5830
51.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
5831
0
            if (make_deferred_abort_task(rowset).has_value()) {
5832
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5833
0
                             "instance_id="
5834
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
5835
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
5836
0
                tmp_rowset_keys_to_abort.emplace_back(k);
5837
0
            }
5838
0
        }
5839
5840
51.0k
        ++num_expired;
5841
51.0k
        expired_rowset_size += v.size();
5842
51.0k
        if (!rowset.has_resource_id()) {
5843
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
5844
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
5845
0
                return -1;
5846
0
            }
5847
            // might be a delete pred rowset
5848
0
            tmp_rowset_keys.emplace_back(k);
5849
0
            return 0;
5850
0
        }
5851
        // TODO(plat1ko): check rowset not referenced
5852
51.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5853
51.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
5854
51.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
5855
51.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
5856
51.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
5857
51.0k
                  << " num_expired=" << num_expired
5858
51.0k
                  << " task_type=" << metrics_context.operation_type;
5859
5860
51.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
5861
        // Remove the rowset ref count key directly since it has not been used.
5862
51.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
5863
51.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
5864
51.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
5865
51.0k
                  << "key=" << hex(rowset_ref_count_key);
5866
51.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
5867
5868
51.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
5869
51.0k
        return 0;
5870
51.0k
    };
5871
5872
    // TODO bacth delete
5873
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5874
51.0k
        std::string dbm_start_key =
5875
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5876
51.0k
        std::string dbm_end_key = dbm_start_key;
5877
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5878
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5879
51.0k
        if (ret != 0) {
5880
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5881
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5882
0
                         << ", rowset_id=" << rowset_id;
5883
0
        }
5884
51.0k
        return ret;
5885
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5873
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5874
7
        std::string dbm_start_key =
5875
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5876
7
        std::string dbm_end_key = dbm_start_key;
5877
7
        encode_int64(INT64_MAX, &dbm_end_key);
5878
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5879
7
        if (ret != 0) {
5880
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5881
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5882
0
                         << ", rowset_id=" << rowset_id;
5883
0
        }
5884
7
        return ret;
5885
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5873
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5874
51.0k
        std::string dbm_start_key =
5875
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5876
51.0k
        std::string dbm_end_key = dbm_start_key;
5877
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
5878
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5879
51.0k
        if (ret != 0) {
5880
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5881
0
                         << instance_id_ << ", tablet_id=" << tablet_id
5882
0
                         << ", rowset_id=" << rowset_id;
5883
0
        }
5884
51.0k
        return ret;
5885
51.0k
    };
5886
5887
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5888
51.0k
        auto delete_bitmap_start =
5889
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5890
51.0k
        auto delete_bitmap_end =
5891
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5892
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5893
51.0k
        if (ret != 0) {
5894
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5895
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5896
0
        }
5897
51.0k
        return ret;
5898
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5887
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5888
7
        auto delete_bitmap_start =
5889
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5890
7
        auto delete_bitmap_end =
5891
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5892
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5893
7
        if (ret != 0) {
5894
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5895
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5896
0
        }
5897
7
        return ret;
5898
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5887
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5888
51.0k
        auto delete_bitmap_start =
5889
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
5890
51.0k
        auto delete_bitmap_end =
5891
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
5892
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
5893
51.0k
        if (ret != 0) {
5894
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
5895
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
5896
0
        }
5897
51.0k
        return ret;
5898
51.0k
    };
5899
5900
29
    auto loop_done = [&]() -> int {
5901
19
        std::vector<std::string> tmp_rowset_keys_to_delete;
5902
19
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5903
19
        std::vector<std::string> mark_keys_to_process;
5904
19
        std::vector<std::string> abort_keys_to_process;
5905
19
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5906
19
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5907
19
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5908
19
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5909
19
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5910
19
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5911
19
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5912
19
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5913
19
                             tmp_rowset_ref_count_keys_to_delete =
5914
19
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5915
19
                             mark_keys_to_process = std::move(mark_keys_to_process),
5916
19
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5917
19
            if (!mark_keys_to_process.empty() &&
5918
19
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5919
7
                                                                  mark_keys_to_process) != 0) {
5920
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
19
            if (!abort_keys_to_process.empty() &&
5925
19
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5926
3
                                                                      false) != 0) {
5927
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5928
0
                             << instance_id_;
5929
0
                return;
5930
0
            }
5931
19
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5932
19
                                   metrics_context) != 0) {
5933
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5934
0
                return;
5935
0
            }
5936
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5937
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5938
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5939
0
                                 << rs.ShortDebugString();
5940
0
                    return;
5941
0
                }
5942
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5943
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5944
0
                                 << rs.ShortDebugString();
5945
0
                    return;
5946
0
                }
5947
51.0k
            }
5948
19
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5949
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5950
0
                return;
5951
0
            }
5952
19
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5953
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5954
0
                return;
5955
0
            }
5956
19
            num_recycled += tmp_rowset_keys_to_delete.size();
5957
19
            return;
5958
19
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5916
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5917
12
            if (!mark_keys_to_process.empty() &&
5918
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5919
7
                                                                  mark_keys_to_process) != 0) {
5920
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
12
            if (!abort_keys_to_process.empty() &&
5925
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5926
3
                                                                      false) != 0) {
5927
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5928
0
                             << instance_id_;
5929
0
                return;
5930
0
            }
5931
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5932
12
                                   metrics_context) != 0) {
5933
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5934
0
                return;
5935
0
            }
5936
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5937
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5938
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5939
0
                                 << rs.ShortDebugString();
5940
0
                    return;
5941
0
                }
5942
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5943
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5944
0
                                 << rs.ShortDebugString();
5945
0
                    return;
5946
0
                }
5947
7
            }
5948
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5949
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5950
0
                return;
5951
0
            }
5952
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5953
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5954
0
                return;
5955
0
            }
5956
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5957
12
            return;
5958
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5916
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5917
7
            if (!mark_keys_to_process.empty() &&
5918
7
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5919
0
                                                                  mark_keys_to_process) != 0) {
5920
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5921
0
                             << instance_id_;
5922
0
                return;
5923
0
            }
5924
7
            if (!abort_keys_to_process.empty() &&
5925
7
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5926
0
                                                                      false) != 0) {
5927
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5928
0
                             << instance_id_;
5929
0
                return;
5930
0
            }
5931
7
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5932
7
                                   metrics_context) != 0) {
5933
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5934
0
                return;
5935
0
            }
5936
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5937
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5938
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5939
0
                                 << rs.ShortDebugString();
5940
0
                    return;
5941
0
                }
5942
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5943
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5944
0
                                 << rs.ShortDebugString();
5945
0
                    return;
5946
0
                }
5947
51.0k
            }
5948
7
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5949
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5950
0
                return;
5951
0
            }
5952
7
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5953
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5954
0
                return;
5955
0
            }
5956
7
            num_recycled += tmp_rowset_keys_to_delete.size();
5957
7
            return;
5958
7
        });
5959
19
        return 0;
5960
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5900
12
    auto loop_done = [&]() -> int {
5901
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
5902
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5903
12
        std::vector<std::string> mark_keys_to_process;
5904
12
        std::vector<std::string> abort_keys_to_process;
5905
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5906
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5907
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5908
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5909
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5910
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5911
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5912
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5913
12
                             tmp_rowset_ref_count_keys_to_delete =
5914
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5915
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
5916
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5917
12
            if (!mark_keys_to_process.empty() &&
5918
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5919
12
                                                                  mark_keys_to_process) != 0) {
5920
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5921
12
                             << instance_id_;
5922
12
                return;
5923
12
            }
5924
12
            if (!abort_keys_to_process.empty() &&
5925
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5926
12
                                                                      false) != 0) {
5927
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5928
12
                             << instance_id_;
5929
12
                return;
5930
12
            }
5931
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5932
12
                                   metrics_context) != 0) {
5933
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5934
12
                return;
5935
12
            }
5936
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5937
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5938
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5939
12
                                 << rs.ShortDebugString();
5940
12
                    return;
5941
12
                }
5942
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5943
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5944
12
                                 << rs.ShortDebugString();
5945
12
                    return;
5946
12
                }
5947
12
            }
5948
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5949
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5950
12
                return;
5951
12
            }
5952
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5953
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5954
12
                return;
5955
12
            }
5956
12
            num_recycled += tmp_rowset_keys_to_delete.size();
5957
12
            return;
5958
12
        });
5959
12
        return 0;
5960
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
5900
7
    auto loop_done = [&]() -> int {
5901
7
        std::vector<std::string> tmp_rowset_keys_to_delete;
5902
7
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
5903
7
        std::vector<std::string> mark_keys_to_process;
5904
7
        std::vector<std::string> abort_keys_to_process;
5905
7
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
5906
7
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
5907
7
        tmp_rowsets_to_delete.swap(tmp_rowsets);
5908
7
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
5909
7
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
5910
7
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
5911
7
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
5912
7
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
5913
7
                             tmp_rowset_ref_count_keys_to_delete =
5914
7
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
5915
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5916
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5917
7
            if (!mark_keys_to_process.empty() &&
5918
7
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
5919
7
                                                                  mark_keys_to_process) != 0) {
5920
7
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
5921
7
                             << instance_id_;
5922
7
                return;
5923
7
            }
5924
7
            if (!abort_keys_to_process.empty() &&
5925
7
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
5926
7
                                                                      false) != 0) {
5927
7
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
5928
7
                             << instance_id_;
5929
7
                return;
5930
7
            }
5931
7
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
5932
7
                                   metrics_context) != 0) {
5933
7
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
5934
7
                return;
5935
7
            }
5936
7
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
5937
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5938
7
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
5939
7
                                 << rs.ShortDebugString();
5940
7
                    return;
5941
7
                }
5942
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5943
7
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
5944
7
                                 << rs.ShortDebugString();
5945
7
                    return;
5946
7
                }
5947
7
            }
5948
7
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
5949
7
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
5950
7
                return;
5951
7
            }
5952
7
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
5953
7
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
5954
7
                return;
5955
7
            }
5956
7
            num_recycled += tmp_rowset_keys_to_delete.size();
5957
7
            return;
5958
7
        });
5959
7
        return 0;
5960
7
    };
5961
5962
29
    if (config::enable_recycler_stats_metrics) {
5963
0
        scan_and_statistics_tmp_rowsets();
5964
0
    }
5965
    // recycle_func and loop_done for scan and recycle
5966
29
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
5967
29
                               std::move(loop_done));
5968
5969
29
    worker_pool->stop();
5970
5971
    // Report final metrics after all concurrent tasks completed
5972
29
    segment_metrics_context_.report();
5973
29
    metrics_context.report();
5974
5975
29
    return ret;
5976
29
}
5977
5978
int InstanceRecycler::scan_and_recycle(
5979
        std::string begin, std::string_view end,
5980
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
5981
259
        std::function<int()> loop_done) {
5982
259
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
5983
259
    int ret = 0;
5984
259
    int64_t cnt = 0;
5985
259
    int get_range_retried = 0;
5986
259
    std::string err;
5987
259
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5988
259
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5989
259
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5990
259
                  << " ret=" << ret << " err=" << err;
5991
259
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5987
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5988
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5989
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5990
31
                  << " ret=" << ret << " err=" << err;
5991
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
5987
228
    DORIS_CLOUD_DEFER_COPY(begin, end) {
5988
228
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
5989
228
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
5990
228
                  << " ret=" << ret << " err=" << err;
5991
228
    };
5992
5993
259
    std::unique_ptr<RangeGetIterator> it;
5994
287
    do {
5995
287
        if (get_range_retried > 1000) {
5996
0
            err = "txn_get exceeds max retry, may not scan all keys";
5997
0
            ret = -1;
5998
0
            return -1;
5999
0
        }
6000
287
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6001
287
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6002
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6003
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6004
0
                         << " get_range_retried=" << get_range_retried;
6005
0
            ++get_range_retried;
6006
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6007
0
            continue; // try again
6008
0
        }
6009
287
        if (!it->has_next()) {
6010
137
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6011
137
            break; // scan finished
6012
137
        }
6013
95.5k
        while (it->has_next()) {
6014
95.4k
            ++cnt;
6015
            // recycle corresponding resources
6016
95.4k
            auto [k, v] = it->next();
6017
95.4k
            if (!it->has_next()) {
6018
150
                begin = k;
6019
150
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6020
150
            }
6021
            // if we want to continue scanning, the recycle_func should not return non-zero
6022
95.4k
            if (recycle_func(k, v) != 0) {
6023
4.00k
                err = "recycle_func error";
6024
4.00k
                ret = -1;
6025
4.00k
            }
6026
95.4k
        }
6027
150
        begin.push_back('\x00'); // Update to next smallest key for iteration
6028
        // if we want to continue scanning, the recycle_func should not return non-zero
6029
150
        if (loop_done && loop_done() != 0) {
6030
5
            err = "loop_done error";
6031
5
            ret = -1;
6032
5
        }
6033
150
    } while (it->more() && !stopped());
6034
259
    return ret;
6035
259
}
6036
6037
19
int InstanceRecycler::abort_timeout_txn() {
6038
19
    const std::string task_name = "abort_timeout_txn";
6039
19
    int64_t num_scanned = 0;
6040
19
    int64_t num_timeout = 0;
6041
19
    int64_t num_abort = 0;
6042
19
    int64_t num_advance = 0;
6043
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6044
6045
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6046
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6047
19
    std::string begin_txn_running_key;
6048
19
    std::string end_txn_running_key;
6049
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6050
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6051
6052
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6053
6054
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6055
19
    register_recycle_task(task_name, start_time);
6056
6057
19
    DORIS_CLOUD_DEFER {
6058
19
        unregister_recycle_task(task_name);
6059
19
        int64_t cost =
6060
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6061
19
        metrics_context.finish_report();
6062
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6063
19
                .tag("instance_id", instance_id_)
6064
19
                .tag("num_scanned", num_scanned)
6065
19
                .tag("num_timeout", num_timeout)
6066
19
                .tag("num_abort", num_abort)
6067
19
                .tag("num_advance", num_advance);
6068
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6057
3
    DORIS_CLOUD_DEFER {
6058
3
        unregister_recycle_task(task_name);
6059
3
        int64_t cost =
6060
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6061
3
        metrics_context.finish_report();
6062
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6063
3
                .tag("instance_id", instance_id_)
6064
3
                .tag("num_scanned", num_scanned)
6065
3
                .tag("num_timeout", num_timeout)
6066
3
                .tag("num_abort", num_abort)
6067
3
                .tag("num_advance", num_advance);
6068
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6057
16
    DORIS_CLOUD_DEFER {
6058
16
        unregister_recycle_task(task_name);
6059
16
        int64_t cost =
6060
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6061
16
        metrics_context.finish_report();
6062
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6063
16
                .tag("instance_id", instance_id_)
6064
16
                .tag("num_scanned", num_scanned)
6065
16
                .tag("num_timeout", num_timeout)
6066
16
                .tag("num_abort", num_abort)
6067
16
                .tag("num_advance", num_advance);
6068
16
    };
6069
6070
19
    int64_t current_time =
6071
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6072
6073
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6074
19
                                  &current_time, &metrics_context,
6075
19
                                  this](std::string_view k, std::string_view v) -> int {
6076
9
        ++num_scanned;
6077
6078
9
        std::unique_ptr<Transaction> txn;
6079
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6080
9
        if (err != TxnErrorCode::TXN_OK) {
6081
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6082
0
            return -1;
6083
0
        }
6084
9
        std::string_view k1 = k;
6085
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6086
9
        k1.remove_prefix(1); // Remove key space
6087
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6088
9
        if (decode_key(&k1, &out) != 0) {
6089
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6090
0
            return -1;
6091
0
        }
6092
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6093
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6094
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6095
        // Update txn_info
6096
9
        std::string txn_inf_key, txn_inf_val;
6097
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6098
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6099
9
        if (err != TxnErrorCode::TXN_OK) {
6100
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6101
0
            return -1;
6102
0
        }
6103
9
        TxnInfoPB txn_info;
6104
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6105
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6106
0
            return -1;
6107
0
        }
6108
6109
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6110
3
            txn.reset();
6111
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6112
3
            std::shared_ptr<TxnLazyCommitTask> task =
6113
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6114
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6115
3
            if (ret.first != MetaServiceCode::OK) {
6116
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6117
0
                             << "msg=" << ret.second;
6118
0
                return -1;
6119
0
            }
6120
3
            ++num_advance;
6121
3
            return 0;
6122
6
        } else {
6123
6
            TxnRunningPB txn_running_pb;
6124
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6125
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6126
0
                return -1;
6127
0
            }
6128
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6129
4
                return 0;
6130
4
            }
6131
2
            ++num_timeout;
6132
6133
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6134
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6135
2
            txn_info.set_finish_time(current_time);
6136
2
            txn_info.set_reason("timeout");
6137
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6138
2
            txn_inf_val.clear();
6139
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6140
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6141
0
                return -1;
6142
0
            }
6143
2
            txn->put(txn_inf_key, txn_inf_val);
6144
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6145
            // Put recycle txn key
6146
2
            std::string recyc_txn_key, recyc_txn_val;
6147
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6148
2
            RecycleTxnPB recycle_txn_pb;
6149
2
            recycle_txn_pb.set_creation_time(current_time);
6150
2
            recycle_txn_pb.set_label(txn_info.label());
6151
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6152
0
                LOG_WARNING("failed to serialize txn recycle info")
6153
0
                        .tag("key", hex(k))
6154
0
                        .tag("db_id", db_id)
6155
0
                        .tag("txn_id", txn_id);
6156
0
                return -1;
6157
0
            }
6158
2
            txn->put(recyc_txn_key, recyc_txn_val);
6159
            // Remove txn running key
6160
2
            txn->remove(k);
6161
2
            err = txn->commit();
6162
2
            if (err != TxnErrorCode::TXN_OK) {
6163
0
                LOG_WARNING("failed to commit txn err={}", err)
6164
0
                        .tag("key", hex(k))
6165
0
                        .tag("db_id", db_id)
6166
0
                        .tag("txn_id", txn_id);
6167
0
                return -1;
6168
0
            }
6169
2
            metrics_context.total_recycled_num = ++num_abort;
6170
2
            metrics_context.report();
6171
2
        }
6172
6173
2
        return 0;
6174
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6075
3
                                  this](std::string_view k, std::string_view v) -> int {
6076
3
        ++num_scanned;
6077
6078
3
        std::unique_ptr<Transaction> txn;
6079
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6080
3
        if (err != TxnErrorCode::TXN_OK) {
6081
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6082
0
            return -1;
6083
0
        }
6084
3
        std::string_view k1 = k;
6085
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6086
3
        k1.remove_prefix(1); // Remove key space
6087
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6088
3
        if (decode_key(&k1, &out) != 0) {
6089
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6090
0
            return -1;
6091
0
        }
6092
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6093
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6094
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6095
        // Update txn_info
6096
3
        std::string txn_inf_key, txn_inf_val;
6097
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6098
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6099
3
        if (err != TxnErrorCode::TXN_OK) {
6100
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6101
0
            return -1;
6102
0
        }
6103
3
        TxnInfoPB txn_info;
6104
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6105
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6106
0
            return -1;
6107
0
        }
6108
6109
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6110
3
            txn.reset();
6111
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6112
3
            std::shared_ptr<TxnLazyCommitTask> task =
6113
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6114
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6115
3
            if (ret.first != MetaServiceCode::OK) {
6116
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6117
0
                             << "msg=" << ret.second;
6118
0
                return -1;
6119
0
            }
6120
3
            ++num_advance;
6121
3
            return 0;
6122
3
        } else {
6123
0
            TxnRunningPB txn_running_pb;
6124
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6125
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6126
0
                return -1;
6127
0
            }
6128
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6129
0
                return 0;
6130
0
            }
6131
0
            ++num_timeout;
6132
6133
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6134
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6135
0
            txn_info.set_finish_time(current_time);
6136
0
            txn_info.set_reason("timeout");
6137
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6138
0
            txn_inf_val.clear();
6139
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6140
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6141
0
                return -1;
6142
0
            }
6143
0
            txn->put(txn_inf_key, txn_inf_val);
6144
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6145
            // Put recycle txn key
6146
0
            std::string recyc_txn_key, recyc_txn_val;
6147
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6148
0
            RecycleTxnPB recycle_txn_pb;
6149
0
            recycle_txn_pb.set_creation_time(current_time);
6150
0
            recycle_txn_pb.set_label(txn_info.label());
6151
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6152
0
                LOG_WARNING("failed to serialize txn recycle info")
6153
0
                        .tag("key", hex(k))
6154
0
                        .tag("db_id", db_id)
6155
0
                        .tag("txn_id", txn_id);
6156
0
                return -1;
6157
0
            }
6158
0
            txn->put(recyc_txn_key, recyc_txn_val);
6159
            // Remove txn running key
6160
0
            txn->remove(k);
6161
0
            err = txn->commit();
6162
0
            if (err != TxnErrorCode::TXN_OK) {
6163
0
                LOG_WARNING("failed to commit txn err={}", err)
6164
0
                        .tag("key", hex(k))
6165
0
                        .tag("db_id", db_id)
6166
0
                        .tag("txn_id", txn_id);
6167
0
                return -1;
6168
0
            }
6169
0
            metrics_context.total_recycled_num = ++num_abort;
6170
0
            metrics_context.report();
6171
0
        }
6172
6173
0
        return 0;
6174
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6075
6
                                  this](std::string_view k, std::string_view v) -> int {
6076
6
        ++num_scanned;
6077
6078
6
        std::unique_ptr<Transaction> txn;
6079
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6080
6
        if (err != TxnErrorCode::TXN_OK) {
6081
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6082
0
            return -1;
6083
0
        }
6084
6
        std::string_view k1 = k;
6085
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6086
6
        k1.remove_prefix(1); // Remove key space
6087
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6088
6
        if (decode_key(&k1, &out) != 0) {
6089
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6090
0
            return -1;
6091
0
        }
6092
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6093
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6094
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6095
        // Update txn_info
6096
6
        std::string txn_inf_key, txn_inf_val;
6097
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6098
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6099
6
        if (err != TxnErrorCode::TXN_OK) {
6100
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6101
0
            return -1;
6102
0
        }
6103
6
        TxnInfoPB txn_info;
6104
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6105
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6106
0
            return -1;
6107
0
        }
6108
6109
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6110
0
            txn.reset();
6111
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6112
0
            std::shared_ptr<TxnLazyCommitTask> task =
6113
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6114
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6115
0
            if (ret.first != MetaServiceCode::OK) {
6116
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6117
0
                             << "msg=" << ret.second;
6118
0
                return -1;
6119
0
            }
6120
0
            ++num_advance;
6121
0
            return 0;
6122
6
        } else {
6123
6
            TxnRunningPB txn_running_pb;
6124
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6125
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6126
0
                return -1;
6127
0
            }
6128
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6129
4
                return 0;
6130
4
            }
6131
2
            ++num_timeout;
6132
6133
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6134
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6135
2
            txn_info.set_finish_time(current_time);
6136
2
            txn_info.set_reason("timeout");
6137
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6138
2
            txn_inf_val.clear();
6139
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6140
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6141
0
                return -1;
6142
0
            }
6143
2
            txn->put(txn_inf_key, txn_inf_val);
6144
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6145
            // Put recycle txn key
6146
2
            std::string recyc_txn_key, recyc_txn_val;
6147
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6148
2
            RecycleTxnPB recycle_txn_pb;
6149
2
            recycle_txn_pb.set_creation_time(current_time);
6150
2
            recycle_txn_pb.set_label(txn_info.label());
6151
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6152
0
                LOG_WARNING("failed to serialize txn recycle info")
6153
0
                        .tag("key", hex(k))
6154
0
                        .tag("db_id", db_id)
6155
0
                        .tag("txn_id", txn_id);
6156
0
                return -1;
6157
0
            }
6158
2
            txn->put(recyc_txn_key, recyc_txn_val);
6159
            // Remove txn running key
6160
2
            txn->remove(k);
6161
2
            err = txn->commit();
6162
2
            if (err != TxnErrorCode::TXN_OK) {
6163
0
                LOG_WARNING("failed to commit txn err={}", err)
6164
0
                        .tag("key", hex(k))
6165
0
                        .tag("db_id", db_id)
6166
0
                        .tag("txn_id", txn_id);
6167
0
                return -1;
6168
0
            }
6169
2
            metrics_context.total_recycled_num = ++num_abort;
6170
2
            metrics_context.report();
6171
2
        }
6172
6173
2
        return 0;
6174
6
    };
6175
6176
19
    if (config::enable_recycler_stats_metrics) {
6177
0
        scan_and_statistics_abort_timeout_txn();
6178
0
    }
6179
    // recycle_func and loop_done for scan and recycle
6180
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6181
19
                            std::move(handle_txn_running_kv));
6182
19
}
6183
6184
19
int InstanceRecycler::recycle_expired_txn_label() {
6185
19
    const std::string task_name = "recycle_expired_txn_label";
6186
19
    int64_t num_scanned = 0;
6187
19
    int64_t num_expired = 0;
6188
19
    std::atomic_long num_recycled = 0;
6189
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6190
19
    int ret = 0;
6191
6192
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6193
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6194
19
    std::string begin_recycle_txn_key;
6195
19
    std::string end_recycle_txn_key;
6196
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6197
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6198
19
    std::vector<std::string> recycle_txn_info_keys;
6199
6200
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6201
6202
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6203
19
    register_recycle_task(task_name, start_time);
6204
19
    DORIS_CLOUD_DEFER {
6205
19
        unregister_recycle_task(task_name);
6206
19
        int64_t cost =
6207
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6208
19
        metrics_context.finish_report();
6209
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6210
19
                .tag("instance_id", instance_id_)
6211
19
                .tag("num_scanned", num_scanned)
6212
19
                .tag("num_expired", num_expired)
6213
19
                .tag("num_recycled", num_recycled);
6214
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6204
1
    DORIS_CLOUD_DEFER {
6205
1
        unregister_recycle_task(task_name);
6206
1
        int64_t cost =
6207
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6208
1
        metrics_context.finish_report();
6209
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6210
1
                .tag("instance_id", instance_id_)
6211
1
                .tag("num_scanned", num_scanned)
6212
1
                .tag("num_expired", num_expired)
6213
1
                .tag("num_recycled", num_recycled);
6214
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6204
18
    DORIS_CLOUD_DEFER {
6205
18
        unregister_recycle_task(task_name);
6206
18
        int64_t cost =
6207
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6208
18
        metrics_context.finish_report();
6209
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6210
18
                .tag("instance_id", instance_id_)
6211
18
                .tag("num_scanned", num_scanned)
6212
18
                .tag("num_expired", num_expired)
6213
18
                .tag("num_recycled", num_recycled);
6214
18
    };
6215
6216
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6217
6218
19
    SyncExecutor<int> concurrent_delete_executor(
6219
19
            _thread_pool_group.s3_producer_pool,
6220
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6221
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6221
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6221
23.0k
            [](const int& ret) { return ret != 0; });
6222
6223
19
    int64_t current_time_ms =
6224
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6225
6226
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6227
30.0k
        ++num_scanned;
6228
30.0k
        RecycleTxnPB recycle_txn_pb;
6229
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6230
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6231
0
            return -1;
6232
0
        }
6233
30.0k
        if ((config::force_immediate_recycle) ||
6234
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6235
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6236
30.0k
             current_time_ms)) {
6237
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6238
23.0k
            num_expired++;
6239
23.0k
            recycle_txn_info_keys.emplace_back(k);
6240
23.0k
        }
6241
30.0k
        return 0;
6242
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6226
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6227
1
        ++num_scanned;
6228
1
        RecycleTxnPB recycle_txn_pb;
6229
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6230
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6231
0
            return -1;
6232
0
        }
6233
1
        if ((config::force_immediate_recycle) ||
6234
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6235
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6236
1
             current_time_ms)) {
6237
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6238
1
            num_expired++;
6239
1
            recycle_txn_info_keys.emplace_back(k);
6240
1
        }
6241
1
        return 0;
6242
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6226
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6227
30.0k
        ++num_scanned;
6228
30.0k
        RecycleTxnPB recycle_txn_pb;
6229
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6230
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6231
0
            return -1;
6232
0
        }
6233
30.0k
        if ((config::force_immediate_recycle) ||
6234
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6235
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6236
30.0k
             current_time_ms)) {
6237
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6238
23.0k
            num_expired++;
6239
23.0k
            recycle_txn_info_keys.emplace_back(k);
6240
23.0k
        }
6241
30.0k
        return 0;
6242
30.0k
    };
6243
6244
    // int 0 for success, 1 for conflict, -1 for error
6245
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6246
23.0k
        std::string_view k1 = k;
6247
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6248
23.0k
        k1.remove_prefix(1); // Remove key space
6249
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6250
23.0k
        int ret = decode_key(&k1, &out);
6251
23.0k
        if (ret != 0) {
6252
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6253
0
            return -1;
6254
0
        }
6255
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6256
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6257
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6258
23.0k
        std::unique_ptr<Transaction> txn;
6259
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6260
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6261
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6262
0
            return -1;
6263
0
        }
6264
        // Remove txn index kv
6265
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6266
23.0k
        txn->remove(index_key);
6267
        // Remove txn info kv
6268
23.0k
        std::string info_key, info_val;
6269
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6270
23.0k
        err = txn->get(info_key, &info_val);
6271
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6272
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6273
0
            return -1;
6274
0
        }
6275
23.0k
        TxnInfoPB txn_info;
6276
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6277
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6278
0
            return -1;
6279
0
        }
6280
23.0k
        txn->remove(info_key);
6281
        // Remove sub txn index kvs
6282
23.0k
        std::vector<std::string> sub_txn_index_keys;
6283
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6284
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6285
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6286
22.9k
        }
6287
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6288
22.9k
            txn->remove(sub_txn_index_key);
6289
22.9k
        }
6290
        // Update txn label
6291
23.0k
        std::string label_key, label_val;
6292
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6293
23.0k
        err = txn->get(label_key, &label_val);
6294
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6295
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6296
0
                         << " err=" << err;
6297
0
            return -1;
6298
0
        }
6299
23.0k
        TxnLabelPB txn_label;
6300
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6301
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6302
0
            return -1;
6303
0
        }
6304
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6305
23.0k
        if (it != txn_label.txn_ids().end()) {
6306
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6307
23.0k
        }
6308
23.0k
        if (txn_label.txn_ids().empty()) {
6309
23.0k
            txn->remove(label_key);
6310
23.0k
            TEST_SYNC_POINT_CALLBACK(
6311
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6312
23.0k
        } else {
6313
73
            if (!txn_label.SerializeToString(&label_val)) {
6314
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6315
0
                return -1;
6316
0
            }
6317
73
            TEST_SYNC_POINT_CALLBACK(
6318
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6319
73
            txn->atomic_set_ver_value(label_key, label_val);
6320
73
            TEST_SYNC_POINT_CALLBACK(
6321
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6322
73
        }
6323
        // Remove recycle txn kv
6324
23.0k
        txn->remove(k);
6325
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6326
23.0k
        err = txn->commit();
6327
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6328
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6329
62
                TEST_SYNC_POINT_CALLBACK(
6330
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6331
                // log the txn_id and label
6332
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6333
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6334
62
                             << " txn_label=" << txn_info.label();
6335
62
                return 1;
6336
62
            }
6337
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6338
0
            return -1;
6339
62
        }
6340
23.0k
        ++num_recycled;
6341
6342
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6343
23.0k
        return 0;
6344
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6245
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6246
1
        std::string_view k1 = k;
6247
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6248
1
        k1.remove_prefix(1); // Remove key space
6249
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6250
1
        int ret = decode_key(&k1, &out);
6251
1
        if (ret != 0) {
6252
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6253
0
            return -1;
6254
0
        }
6255
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6256
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6257
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6258
1
        std::unique_ptr<Transaction> txn;
6259
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6260
1
        if (err != TxnErrorCode::TXN_OK) {
6261
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6262
0
            return -1;
6263
0
        }
6264
        // Remove txn index kv
6265
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6266
1
        txn->remove(index_key);
6267
        // Remove txn info kv
6268
1
        std::string info_key, info_val;
6269
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6270
1
        err = txn->get(info_key, &info_val);
6271
1
        if (err != TxnErrorCode::TXN_OK) {
6272
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6273
0
            return -1;
6274
0
        }
6275
1
        TxnInfoPB txn_info;
6276
1
        if (!txn_info.ParseFromString(info_val)) {
6277
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6278
0
            return -1;
6279
0
        }
6280
1
        txn->remove(info_key);
6281
        // Remove sub txn index kvs
6282
1
        std::vector<std::string> sub_txn_index_keys;
6283
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6284
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6285
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6286
0
        }
6287
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6288
0
            txn->remove(sub_txn_index_key);
6289
0
        }
6290
        // Update txn label
6291
1
        std::string label_key, label_val;
6292
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6293
1
        err = txn->get(label_key, &label_val);
6294
1
        if (err != TxnErrorCode::TXN_OK) {
6295
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6296
0
                         << " err=" << err;
6297
0
            return -1;
6298
0
        }
6299
1
        TxnLabelPB txn_label;
6300
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6301
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6302
0
            return -1;
6303
0
        }
6304
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6305
1
        if (it != txn_label.txn_ids().end()) {
6306
1
            txn_label.mutable_txn_ids()->erase(it);
6307
1
        }
6308
1
        if (txn_label.txn_ids().empty()) {
6309
1
            txn->remove(label_key);
6310
1
            TEST_SYNC_POINT_CALLBACK(
6311
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6312
1
        } else {
6313
0
            if (!txn_label.SerializeToString(&label_val)) {
6314
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6315
0
                return -1;
6316
0
            }
6317
0
            TEST_SYNC_POINT_CALLBACK(
6318
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6319
0
            txn->atomic_set_ver_value(label_key, label_val);
6320
0
            TEST_SYNC_POINT_CALLBACK(
6321
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6322
0
        }
6323
        // Remove recycle txn kv
6324
1
        txn->remove(k);
6325
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6326
1
        err = txn->commit();
6327
1
        if (err != TxnErrorCode::TXN_OK) {
6328
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6329
0
                TEST_SYNC_POINT_CALLBACK(
6330
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6331
                // log the txn_id and label
6332
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6333
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6334
0
                             << " txn_label=" << txn_info.label();
6335
0
                return 1;
6336
0
            }
6337
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6338
0
            return -1;
6339
0
        }
6340
1
        ++num_recycled;
6341
6342
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6343
1
        return 0;
6344
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6245
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6246
23.0k
        std::string_view k1 = k;
6247
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6248
23.0k
        k1.remove_prefix(1); // Remove key space
6249
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6250
23.0k
        int ret = decode_key(&k1, &out);
6251
23.0k
        if (ret != 0) {
6252
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6253
0
            return -1;
6254
0
        }
6255
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6256
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6257
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6258
23.0k
        std::unique_ptr<Transaction> txn;
6259
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6260
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6261
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6262
0
            return -1;
6263
0
        }
6264
        // Remove txn index kv
6265
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6266
23.0k
        txn->remove(index_key);
6267
        // Remove txn info kv
6268
23.0k
        std::string info_key, info_val;
6269
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6270
23.0k
        err = txn->get(info_key, &info_val);
6271
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6272
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6273
0
            return -1;
6274
0
        }
6275
23.0k
        TxnInfoPB txn_info;
6276
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6277
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6278
0
            return -1;
6279
0
        }
6280
23.0k
        txn->remove(info_key);
6281
        // Remove sub txn index kvs
6282
23.0k
        std::vector<std::string> sub_txn_index_keys;
6283
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6284
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6285
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6286
22.9k
        }
6287
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6288
22.9k
            txn->remove(sub_txn_index_key);
6289
22.9k
        }
6290
        // Update txn label
6291
23.0k
        std::string label_key, label_val;
6292
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6293
23.0k
        err = txn->get(label_key, &label_val);
6294
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6295
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6296
0
                         << " err=" << err;
6297
0
            return -1;
6298
0
        }
6299
23.0k
        TxnLabelPB txn_label;
6300
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6301
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6302
0
            return -1;
6303
0
        }
6304
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6305
23.0k
        if (it != txn_label.txn_ids().end()) {
6306
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6307
23.0k
        }
6308
23.0k
        if (txn_label.txn_ids().empty()) {
6309
23.0k
            txn->remove(label_key);
6310
23.0k
            TEST_SYNC_POINT_CALLBACK(
6311
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6312
23.0k
        } else {
6313
73
            if (!txn_label.SerializeToString(&label_val)) {
6314
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6315
0
                return -1;
6316
0
            }
6317
73
            TEST_SYNC_POINT_CALLBACK(
6318
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6319
73
            txn->atomic_set_ver_value(label_key, label_val);
6320
73
            TEST_SYNC_POINT_CALLBACK(
6321
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6322
73
        }
6323
        // Remove recycle txn kv
6324
23.0k
        txn->remove(k);
6325
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6326
23.0k
        err = txn->commit();
6327
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6328
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6329
62
                TEST_SYNC_POINT_CALLBACK(
6330
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6331
                // log the txn_id and label
6332
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6333
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6334
62
                             << " txn_label=" << txn_info.label();
6335
62
                return 1;
6336
62
            }
6337
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6338
0
            return -1;
6339
62
        }
6340
23.0k
        ++num_recycled;
6341
6342
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6343
23.0k
        return 0;
6344
23.0k
    };
6345
6346
19
    auto loop_done = [&]() -> int {
6347
10
        DORIS_CLOUD_DEFER {
6348
10
            recycle_txn_info_keys.clear();
6349
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6347
1
        DORIS_CLOUD_DEFER {
6348
1
            recycle_txn_info_keys.clear();
6349
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6347
9
        DORIS_CLOUD_DEFER {
6348
9
            recycle_txn_info_keys.clear();
6349
9
        };
6350
10
        TEST_SYNC_POINT_CALLBACK(
6351
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6352
10
                &recycle_txn_info_keys);
6353
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6354
23.0k
            concurrent_delete_executor.add([&]() {
6355
23.0k
                int ret = delete_recycle_txn_kv(k);
6356
23.0k
                if (ret == 1) {
6357
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6358
54
                    for (int i = 1; i <= max_retry; ++i) {
6359
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6360
54
                        ret = delete_recycle_txn_kv(k);
6361
                        // clang-format off
6362
54
                        TEST_SYNC_POINT_CALLBACK(
6363
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6364
                        // clang-format off
6365
54
                        if (ret != 1) {
6366
18
                            break;
6367
18
                        }
6368
                        // random sleep 0-100 ms to retry
6369
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6370
36
                    }
6371
18
                }
6372
23.0k
                if (ret != 0) {
6373
9
                    LOG_WARNING("failed to delete recycle txn kv")
6374
9
                            .tag("instance id", instance_id_)
6375
9
                            .tag("key", hex(k));
6376
9
                    return -1;
6377
9
                }
6378
23.0k
                return 0;
6379
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6354
1
            concurrent_delete_executor.add([&]() {
6355
1
                int ret = delete_recycle_txn_kv(k);
6356
1
                if (ret == 1) {
6357
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6358
0
                    for (int i = 1; i <= max_retry; ++i) {
6359
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6360
0
                        ret = delete_recycle_txn_kv(k);
6361
                        // clang-format off
6362
0
                        TEST_SYNC_POINT_CALLBACK(
6363
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6364
                        // clang-format off
6365
0
                        if (ret != 1) {
6366
0
                            break;
6367
0
                        }
6368
                        // random sleep 0-100 ms to retry
6369
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6370
0
                    }
6371
0
                }
6372
1
                if (ret != 0) {
6373
0
                    LOG_WARNING("failed to delete recycle txn kv")
6374
0
                            .tag("instance id", instance_id_)
6375
0
                            .tag("key", hex(k));
6376
0
                    return -1;
6377
0
                }
6378
1
                return 0;
6379
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6354
23.0k
            concurrent_delete_executor.add([&]() {
6355
23.0k
                int ret = delete_recycle_txn_kv(k);
6356
23.0k
                if (ret == 1) {
6357
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6358
54
                    for (int i = 1; i <= max_retry; ++i) {
6359
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6360
54
                        ret = delete_recycle_txn_kv(k);
6361
                        // clang-format off
6362
54
                        TEST_SYNC_POINT_CALLBACK(
6363
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6364
                        // clang-format off
6365
54
                        if (ret != 1) {
6366
18
                            break;
6367
18
                        }
6368
                        // random sleep 0-100 ms to retry
6369
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6370
36
                    }
6371
18
                }
6372
23.0k
                if (ret != 0) {
6373
9
                    LOG_WARNING("failed to delete recycle txn kv")
6374
9
                            .tag("instance id", instance_id_)
6375
9
                            .tag("key", hex(k));
6376
9
                    return -1;
6377
9
                }
6378
23.0k
                return 0;
6379
23.0k
            });
6380
23.0k
        }
6381
10
        bool finished = true;
6382
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6383
23.0k
        for (int r : rets) {
6384
23.0k
            if (r != 0) {
6385
9
                ret = -1;
6386
9
            }
6387
23.0k
        }
6388
6389
10
        ret = finished ? ret : -1;
6390
6391
        // Update metrics after all concurrent tasks completed
6392
10
        metrics_context.total_recycled_num = num_recycled.load();
6393
10
        metrics_context.report();
6394
6395
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6396
6397
10
        if (ret != 0) {
6398
3
            LOG_WARNING("recycle txn kv ret!=0")
6399
3
                    .tag("finished", finished)
6400
3
                    .tag("ret", ret)
6401
3
                    .tag("instance_id", instance_id_);
6402
3
            return ret;
6403
3
        }
6404
7
        return ret;
6405
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6346
1
    auto loop_done = [&]() -> int {
6347
1
        DORIS_CLOUD_DEFER {
6348
1
            recycle_txn_info_keys.clear();
6349
1
        };
6350
1
        TEST_SYNC_POINT_CALLBACK(
6351
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6352
1
                &recycle_txn_info_keys);
6353
1
        for (const auto& k : recycle_txn_info_keys) {
6354
1
            concurrent_delete_executor.add([&]() {
6355
1
                int ret = delete_recycle_txn_kv(k);
6356
1
                if (ret == 1) {
6357
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6358
1
                    for (int i = 1; i <= max_retry; ++i) {
6359
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6360
1
                        ret = delete_recycle_txn_kv(k);
6361
                        // clang-format off
6362
1
                        TEST_SYNC_POINT_CALLBACK(
6363
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6364
                        // clang-format off
6365
1
                        if (ret != 1) {
6366
1
                            break;
6367
1
                        }
6368
                        // random sleep 0-100 ms to retry
6369
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6370
1
                    }
6371
1
                }
6372
1
                if (ret != 0) {
6373
1
                    LOG_WARNING("failed to delete recycle txn kv")
6374
1
                            .tag("instance id", instance_id_)
6375
1
                            .tag("key", hex(k));
6376
1
                    return -1;
6377
1
                }
6378
1
                return 0;
6379
1
            });
6380
1
        }
6381
1
        bool finished = true;
6382
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6383
1
        for (int r : rets) {
6384
1
            if (r != 0) {
6385
0
                ret = -1;
6386
0
            }
6387
1
        }
6388
6389
1
        ret = finished ? ret : -1;
6390
6391
        // Update metrics after all concurrent tasks completed
6392
1
        metrics_context.total_recycled_num = num_recycled.load();
6393
1
        metrics_context.report();
6394
6395
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6396
6397
1
        if (ret != 0) {
6398
0
            LOG_WARNING("recycle txn kv ret!=0")
6399
0
                    .tag("finished", finished)
6400
0
                    .tag("ret", ret)
6401
0
                    .tag("instance_id", instance_id_);
6402
0
            return ret;
6403
0
        }
6404
1
        return ret;
6405
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6346
9
    auto loop_done = [&]() -> int {
6347
9
        DORIS_CLOUD_DEFER {
6348
9
            recycle_txn_info_keys.clear();
6349
9
        };
6350
9
        TEST_SYNC_POINT_CALLBACK(
6351
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6352
9
                &recycle_txn_info_keys);
6353
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6354
23.0k
            concurrent_delete_executor.add([&]() {
6355
23.0k
                int ret = delete_recycle_txn_kv(k);
6356
23.0k
                if (ret == 1) {
6357
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6358
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6359
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6360
23.0k
                        ret = delete_recycle_txn_kv(k);
6361
                        // clang-format off
6362
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6363
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6364
                        // clang-format off
6365
23.0k
                        if (ret != 1) {
6366
23.0k
                            break;
6367
23.0k
                        }
6368
                        // random sleep 0-100 ms to retry
6369
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6370
23.0k
                    }
6371
23.0k
                }
6372
23.0k
                if (ret != 0) {
6373
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6374
23.0k
                            .tag("instance id", instance_id_)
6375
23.0k
                            .tag("key", hex(k));
6376
23.0k
                    return -1;
6377
23.0k
                }
6378
23.0k
                return 0;
6379
23.0k
            });
6380
23.0k
        }
6381
9
        bool finished = true;
6382
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6383
23.0k
        for (int r : rets) {
6384
23.0k
            if (r != 0) {
6385
9
                ret = -1;
6386
9
            }
6387
23.0k
        }
6388
6389
9
        ret = finished ? ret : -1;
6390
6391
        // Update metrics after all concurrent tasks completed
6392
9
        metrics_context.total_recycled_num = num_recycled.load();
6393
9
        metrics_context.report();
6394
6395
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6396
6397
9
        if (ret != 0) {
6398
3
            LOG_WARNING("recycle txn kv ret!=0")
6399
3
                    .tag("finished", finished)
6400
3
                    .tag("ret", ret)
6401
3
                    .tag("instance_id", instance_id_);
6402
3
            return ret;
6403
3
        }
6404
6
        return ret;
6405
9
    };
6406
6407
19
    if (config::enable_recycler_stats_metrics) {
6408
0
        scan_and_statistics_expired_txn_label();
6409
0
    }
6410
    // recycle_func and loop_done for scan and recycle
6411
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6412
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6413
19
}
6414
6415
struct CopyJobIdTuple {
6416
    std::string instance_id;
6417
    std::string stage_id;
6418
    long table_id;
6419
    std::string copy_id;
6420
    std::string stage_path;
6421
};
6422
struct BatchObjStoreAccessor {
6423
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6424
                          TxnKv* txn_kv)
6425
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6426
3
    ~BatchObjStoreAccessor() {
6427
3
        if (!paths_.empty()) {
6428
3
            consume();
6429
3
        }
6430
3
    }
6431
6432
    /**
6433
    * To implicitely do batch work and submit the batch delete task to s3
6434
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6435
    *
6436
    * @param copy_job The protubuf struct consists of the copy job files.
6437
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6438
    *            it would last until we finish the delete task, here we need pass one string value
6439
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6440
    */
6441
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6442
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6443
5
        auto& file_keys = copy_file_keys_[key];
6444
5
        file_keys.log_trace =
6445
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6446
5
                            instance_id, stage_id, table_id, copy_id, path);
6447
5
        std::string_view log_trace = file_keys.log_trace;
6448
2.03k
        for (const auto& file : copy_job.object_files()) {
6449
2.03k
            auto relative_path = file.relative_path();
6450
2.03k
            paths_.push_back(relative_path);
6451
2.03k
            file_keys.keys.push_back(copy_file_key(
6452
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6453
2.03k
            LOG_INFO(log_trace)
6454
2.03k
                    .tag("relative_path", relative_path)
6455
2.03k
                    .tag("batch_count", batch_count_);
6456
2.03k
        }
6457
5
        LOG_INFO(log_trace)
6458
5
                .tag("objects_num", copy_job.object_files().size())
6459
5
                .tag("batch_count", batch_count_);
6460
        // 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
6461
        // recommend using delete objects when objects num is less than 10)
6462
5
        if (paths_.size() < 1000) {
6463
3
            return;
6464
3
        }
6465
2
        consume();
6466
2
    }
6467
6468
private:
6469
5
    void consume() {
6470
5
        DORIS_CLOUD_DEFER {
6471
5
            paths_.clear();
6472
5
            copy_file_keys_.clear();
6473
5
            batch_count_++;
6474
6475
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6476
5
                        batch_count_);
6477
5
        };
6478
6479
5
        StopWatch sw;
6480
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6481
5
        if (0 != accessor_->delete_files(paths_)) {
6482
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6483
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6484
2
            return;
6485
2
        }
6486
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6487
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6488
        // delete fdb's keys
6489
3
        for (auto& file_keys : copy_file_keys_) {
6490
3
            auto& [log_trace, keys] = file_keys.second;
6491
3
            std::unique_ptr<Transaction> txn;
6492
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6493
0
                LOG(WARNING) << "failed to create txn";
6494
0
                continue;
6495
0
            }
6496
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6497
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6498
            // limited, should not cause the txn commit failed.
6499
1.02k
            for (const auto& key : keys) {
6500
1.02k
                txn->remove(key);
6501
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6502
1.02k
            }
6503
3
            txn->remove(file_keys.first);
6504
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6505
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6506
0
                continue;
6507
0
            }
6508
3
        }
6509
3
    }
6510
    std::shared_ptr<StorageVaultAccessor> accessor_;
6511
    // the path of the s3 files to be deleted
6512
    std::vector<std::string> paths_;
6513
    struct CopyFiles {
6514
        std::string log_trace;
6515
        std::vector<std::string> keys;
6516
    };
6517
    // pair<std::string, std::vector<std::string>>
6518
    // first: instance_id_ stage_id table_id query_id
6519
    // second: keys to be deleted
6520
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6521
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6522
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6523
    // which can together uniquely identifies different tasks for tracing log
6524
    uint64_t& batch_count_;
6525
    TxnKv* txn_kv_;
6526
};
6527
6528
13
int InstanceRecycler::recycle_copy_jobs() {
6529
13
    int64_t num_scanned = 0;
6530
13
    int64_t num_finished = 0;
6531
13
    int64_t num_expired = 0;
6532
13
    int64_t num_recycled = 0;
6533
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6534
13
    uint64_t batch_count = 0;
6535
13
    const std::string task_name = "recycle_copy_jobs";
6536
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6537
6538
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6539
6540
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6541
13
    register_recycle_task(task_name, start_time);
6542
6543
13
    DORIS_CLOUD_DEFER {
6544
13
        unregister_recycle_task(task_name);
6545
13
        int64_t cost =
6546
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6547
13
        metrics_context.finish_report();
6548
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6549
13
                .tag("instance_id", instance_id_)
6550
13
                .tag("num_scanned", num_scanned)
6551
13
                .tag("num_finished", num_finished)
6552
13
                .tag("num_expired", num_expired)
6553
13
                .tag("num_recycled", num_recycled);
6554
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6543
13
    DORIS_CLOUD_DEFER {
6544
13
        unregister_recycle_task(task_name);
6545
13
        int64_t cost =
6546
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6547
13
        metrics_context.finish_report();
6548
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6549
13
                .tag("instance_id", instance_id_)
6550
13
                .tag("num_scanned", num_scanned)
6551
13
                .tag("num_finished", num_finished)
6552
13
                .tag("num_expired", num_expired)
6553
13
                .tag("num_recycled", num_recycled);
6554
13
    };
6555
6556
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6557
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6558
13
    std::string key0;
6559
13
    std::string key1;
6560
13
    copy_job_key(key_info0, &key0);
6561
13
    copy_job_key(key_info1, &key1);
6562
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6563
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6564
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6565
16
                         this](std::string_view k, std::string_view v) -> int {
6566
16
        ++num_scanned;
6567
16
        CopyJobPB copy_job;
6568
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6569
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6570
0
            return -1;
6571
0
        }
6572
6573
        // decode copy job key
6574
16
        auto k1 = k;
6575
16
        k1.remove_prefix(1);
6576
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6577
16
        decode_key(&k1, &out);
6578
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6579
        // -> CopyJobPB
6580
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6581
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6582
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6583
6584
16
        bool check_storage = true;
6585
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6586
12
            ++num_finished;
6587
6588
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6589
7
                auto it = stage_accessor_map.find(stage_id);
6590
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6591
7
                std::string_view path;
6592
7
                if (it != stage_accessor_map.end()) {
6593
2
                    accessor = it->second;
6594
5
                } else {
6595
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6596
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6597
5
                                                      &inner_accessor);
6598
5
                    if (ret < 0) { // error
6599
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6600
0
                        return -1;
6601
5
                    } else if (ret == 0) {
6602
3
                        path = inner_accessor->uri();
6603
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6604
3
                                inner_accessor, batch_count, txn_kv_.get());
6605
3
                        stage_accessor_map.emplace(stage_id, accessor);
6606
3
                    } else { // stage not found, skip check storage
6607
2
                        check_storage = false;
6608
2
                    }
6609
5
                }
6610
7
                if (check_storage) {
6611
                    // TODO delete objects with key and etag is not supported
6612
5
                    accessor->add(std::move(copy_job), std::string(k),
6613
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6614
5
                    return 0;
6615
5
                }
6616
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6617
5
                int64_t current_time =
6618
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6619
5
                if (copy_job.finish_time_ms() > 0) {
6620
2
                    if (!config::force_immediate_recycle &&
6621
2
                        current_time < copy_job.finish_time_ms() +
6622
2
                                               config::copy_job_max_retention_second * 1000) {
6623
1
                        return 0;
6624
1
                    }
6625
3
                } else {
6626
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6627
3
                    if (!config::force_immediate_recycle &&
6628
3
                        current_time < copy_job.start_time_ms() +
6629
3
                                               config::copy_job_max_retention_second * 1000) {
6630
1
                        return 0;
6631
1
                    }
6632
3
                }
6633
5
            }
6634
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6635
4
            int64_t current_time =
6636
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6637
            // if copy job is timeout: delete all copy file kvs and copy job kv
6638
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6639
2
                return 0;
6640
2
            }
6641
2
            ++num_expired;
6642
2
        }
6643
6644
        // delete all copy files
6645
7
        std::vector<std::string> copy_file_keys;
6646
70
        for (auto& file : copy_job.object_files()) {
6647
70
            copy_file_keys.push_back(copy_file_key(
6648
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6649
70
        }
6650
7
        std::unique_ptr<Transaction> txn;
6651
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6652
0
            LOG(WARNING) << "failed to create txn";
6653
0
            return -1;
6654
0
        }
6655
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6656
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6657
        // limited, should not cause the txn commit failed.
6658
70
        for (const auto& key : copy_file_keys) {
6659
70
            txn->remove(key);
6660
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6661
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6662
70
                      << ", query_id=" << copy_id;
6663
70
        }
6664
7
        txn->remove(k);
6665
7
        TxnErrorCode err = txn->commit();
6666
7
        if (err != TxnErrorCode::TXN_OK) {
6667
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6668
0
            return -1;
6669
0
        }
6670
6671
7
        metrics_context.total_recycled_num = ++num_recycled;
6672
7
        metrics_context.report();
6673
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6674
7
        return 0;
6675
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
6565
16
                         this](std::string_view k, std::string_view v) -> int {
6566
16
        ++num_scanned;
6567
16
        CopyJobPB copy_job;
6568
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6569
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6570
0
            return -1;
6571
0
        }
6572
6573
        // decode copy job key
6574
16
        auto k1 = k;
6575
16
        k1.remove_prefix(1);
6576
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6577
16
        decode_key(&k1, &out);
6578
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6579
        // -> CopyJobPB
6580
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6581
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6582
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6583
6584
16
        bool check_storage = true;
6585
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6586
12
            ++num_finished;
6587
6588
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6589
7
                auto it = stage_accessor_map.find(stage_id);
6590
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6591
7
                std::string_view path;
6592
7
                if (it != stage_accessor_map.end()) {
6593
2
                    accessor = it->second;
6594
5
                } else {
6595
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6596
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6597
5
                                                      &inner_accessor);
6598
5
                    if (ret < 0) { // error
6599
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6600
0
                        return -1;
6601
5
                    } else if (ret == 0) {
6602
3
                        path = inner_accessor->uri();
6603
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6604
3
                                inner_accessor, batch_count, txn_kv_.get());
6605
3
                        stage_accessor_map.emplace(stage_id, accessor);
6606
3
                    } else { // stage not found, skip check storage
6607
2
                        check_storage = false;
6608
2
                    }
6609
5
                }
6610
7
                if (check_storage) {
6611
                    // TODO delete objects with key and etag is not supported
6612
5
                    accessor->add(std::move(copy_job), std::string(k),
6613
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6614
5
                    return 0;
6615
5
                }
6616
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6617
5
                int64_t current_time =
6618
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6619
5
                if (copy_job.finish_time_ms() > 0) {
6620
2
                    if (!config::force_immediate_recycle &&
6621
2
                        current_time < copy_job.finish_time_ms() +
6622
2
                                               config::copy_job_max_retention_second * 1000) {
6623
1
                        return 0;
6624
1
                    }
6625
3
                } else {
6626
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6627
3
                    if (!config::force_immediate_recycle &&
6628
3
                        current_time < copy_job.start_time_ms() +
6629
3
                                               config::copy_job_max_retention_second * 1000) {
6630
1
                        return 0;
6631
1
                    }
6632
3
                }
6633
5
            }
6634
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6635
4
            int64_t current_time =
6636
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6637
            // if copy job is timeout: delete all copy file kvs and copy job kv
6638
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6639
2
                return 0;
6640
2
            }
6641
2
            ++num_expired;
6642
2
        }
6643
6644
        // delete all copy files
6645
7
        std::vector<std::string> copy_file_keys;
6646
70
        for (auto& file : copy_job.object_files()) {
6647
70
            copy_file_keys.push_back(copy_file_key(
6648
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6649
70
        }
6650
7
        std::unique_ptr<Transaction> txn;
6651
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6652
0
            LOG(WARNING) << "failed to create txn";
6653
0
            return -1;
6654
0
        }
6655
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6656
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6657
        // limited, should not cause the txn commit failed.
6658
70
        for (const auto& key : copy_file_keys) {
6659
70
            txn->remove(key);
6660
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6661
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6662
70
                      << ", query_id=" << copy_id;
6663
70
        }
6664
7
        txn->remove(k);
6665
7
        TxnErrorCode err = txn->commit();
6666
7
        if (err != TxnErrorCode::TXN_OK) {
6667
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6668
0
            return -1;
6669
0
        }
6670
6671
7
        metrics_context.total_recycled_num = ++num_recycled;
6672
7
        metrics_context.report();
6673
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6674
7
        return 0;
6675
7
    };
6676
6677
13
    if (config::enable_recycler_stats_metrics) {
6678
0
        scan_and_statistics_copy_jobs();
6679
0
    }
6680
    // recycle_func and loop_done for scan and recycle
6681
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6682
13
}
6683
6684
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6685
                                             const StagePB::StageType& stage_type,
6686
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6687
5
#ifdef UNIT_TEST
6688
    // In unit test, external use the same accessor as the internal stage
6689
5
    auto it = accessor_map_.find(stage_id);
6690
5
    if (it != accessor_map_.end()) {
6691
3
        *accessor = it->second;
6692
3
    } else {
6693
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6694
2
        return 1;
6695
2
    }
6696
#else
6697
    // init s3 accessor and add to accessor map
6698
    auto stage_it =
6699
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6700
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6701
6702
    if (stage_it == instance_info_.stages().end()) {
6703
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6704
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6705
        return 1;
6706
    }
6707
6708
    const auto& object_store_info = stage_it->obj_info();
6709
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6710
6711
    S3Conf s3_conf;
6712
    if (stage_type == StagePB::EXTERNAL) {
6713
        if (stage_access_type == StagePB::AKSK) {
6714
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6715
            if (!conf) {
6716
                return -1;
6717
            }
6718
6719
            s3_conf = std::move(*conf);
6720
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6721
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6722
            if (!conf) {
6723
                return -1;
6724
            }
6725
6726
            s3_conf = std::move(*conf);
6727
            if (instance_info_.ram_user().has_encryption_info()) {
6728
                AkSkPair plain_ak_sk_pair;
6729
                int ret = decrypt_ak_sk_helper(
6730
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6731
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6732
                if (ret != 0) {
6733
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6734
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6735
                    return -1;
6736
                }
6737
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6738
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6739
            } else {
6740
                s3_conf.ak = instance_info_.ram_user().ak();
6741
                s3_conf.sk = instance_info_.ram_user().sk();
6742
            }
6743
        } else {
6744
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6745
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6746
            return -1;
6747
        }
6748
    } else if (stage_type == StagePB::INTERNAL) {
6749
        int idx = stoi(object_store_info.id());
6750
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6751
            LOG(WARNING) << "invalid idx: " << idx;
6752
            return -1;
6753
        }
6754
6755
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6756
        auto conf = S3Conf::from_obj_store_info(old_obj);
6757
        if (!conf) {
6758
            return -1;
6759
        }
6760
6761
        s3_conf = std::move(*conf);
6762
        s3_conf.prefix = object_store_info.prefix();
6763
    } else {
6764
        LOG(WARNING) << "unknown stage type " << stage_type;
6765
        return -1;
6766
    }
6767
6768
    std::shared_ptr<S3Accessor> s3_accessor;
6769
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6770
    if (ret != 0) {
6771
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6772
        return -1;
6773
    }
6774
6775
    *accessor = std::move(s3_accessor);
6776
#endif
6777
3
    return 0;
6778
5
}
6779
6780
11
int InstanceRecycler::recycle_stage() {
6781
11
    int64_t num_scanned = 0;
6782
11
    int64_t num_recycled = 0;
6783
11
    const std::string task_name = "recycle_stage";
6784
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6785
6786
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
6787
6788
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6789
11
    register_recycle_task(task_name, start_time);
6790
6791
11
    DORIS_CLOUD_DEFER {
6792
11
        unregister_recycle_task(task_name);
6793
11
        int64_t cost =
6794
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6795
11
        metrics_context.finish_report();
6796
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6797
11
                .tag("instance_id", instance_id_)
6798
11
                .tag("num_scanned", num_scanned)
6799
11
                .tag("num_recycled", num_recycled);
6800
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
6791
11
    DORIS_CLOUD_DEFER {
6792
11
        unregister_recycle_task(task_name);
6793
11
        int64_t cost =
6794
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6795
11
        metrics_context.finish_report();
6796
11
        LOG_WARNING("recycle stage, cost={}s", cost)
6797
11
                .tag("instance_id", instance_id_)
6798
11
                .tag("num_scanned", num_scanned)
6799
11
                .tag("num_recycled", num_recycled);
6800
11
    };
6801
6802
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
6803
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
6804
11
    std::string key0 = recycle_stage_key(key_info0);
6805
11
    std::string key1 = recycle_stage_key(key_info1);
6806
6807
11
    std::vector<std::string_view> stage_keys;
6808
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
6809
11
                         this](std::string_view k, std::string_view v) -> int {
6810
1
        ++num_scanned;
6811
1
        RecycleStagePB recycle_stage;
6812
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6813
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6814
0
            return -1;
6815
0
        }
6816
6817
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6818
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6819
0
            LOG(WARNING) << "invalid idx: " << idx;
6820
0
            return -1;
6821
0
        }
6822
6823
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6824
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6825
1
                [&] {
6826
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6827
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6828
1
                    if (!s3_conf) {
6829
1
                        return -1;
6830
1
                    }
6831
6832
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6833
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6834
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6835
1
                    if (ret != 0) {
6836
1
                        return -1;
6837
1
                    }
6838
6839
1
                    accessor = std::move(s3_accessor);
6840
1
                    return 0;
6841
1
                }(),
6842
1
                "recycle_stage:get_accessor", &accessor);
6843
6844
1
        if (ret != 0) {
6845
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6846
0
            return ret;
6847
0
        }
6848
6849
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6850
1
                .tag("instance_id", instance_id_)
6851
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6852
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6853
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6854
1
                .tag("obj_info_id", idx)
6855
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6856
1
        ret = accessor->delete_all();
6857
1
        if (ret != 0) {
6858
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6859
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6860
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6861
0
                         << ", ret=" << ret;
6862
0
            return -1;
6863
0
        }
6864
1
        metrics_context.total_recycled_num = ++num_recycled;
6865
1
        metrics_context.report();
6866
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6867
1
        stage_keys.push_back(k);
6868
1
        return 0;
6869
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6809
1
                         this](std::string_view k, std::string_view v) -> int {
6810
1
        ++num_scanned;
6811
1
        RecycleStagePB recycle_stage;
6812
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
6813
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
6814
0
            return -1;
6815
0
        }
6816
6817
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
6818
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6819
0
            LOG(WARNING) << "invalid idx: " << idx;
6820
0
            return -1;
6821
0
        }
6822
6823
1
        std::shared_ptr<StorageVaultAccessor> accessor;
6824
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
6825
1
                [&] {
6826
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
6827
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6828
1
                    if (!s3_conf) {
6829
1
                        return -1;
6830
1
                    }
6831
6832
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
6833
1
                    std::shared_ptr<S3Accessor> s3_accessor;
6834
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
6835
1
                    if (ret != 0) {
6836
1
                        return -1;
6837
1
                    }
6838
6839
1
                    accessor = std::move(s3_accessor);
6840
1
                    return 0;
6841
1
                }(),
6842
1
                "recycle_stage:get_accessor", &accessor);
6843
6844
1
        if (ret != 0) {
6845
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
6846
0
            return ret;
6847
0
        }
6848
6849
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
6850
1
                .tag("instance_id", instance_id_)
6851
1
                .tag("stage_id", recycle_stage.stage().stage_id())
6852
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
6853
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
6854
1
                .tag("obj_info_id", idx)
6855
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
6856
1
        ret = accessor->delete_all();
6857
1
        if (ret != 0) {
6858
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
6859
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
6860
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
6861
0
                         << ", ret=" << ret;
6862
0
            return -1;
6863
0
        }
6864
1
        metrics_context.total_recycled_num = ++num_recycled;
6865
1
        metrics_context.report();
6866
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
6867
1
        stage_keys.push_back(k);
6868
1
        return 0;
6869
1
    };
6870
6871
11
    auto loop_done = [&stage_keys, this]() -> int {
6872
1
        if (stage_keys.empty()) return 0;
6873
1
        DORIS_CLOUD_DEFER {
6874
1
            stage_keys.clear();
6875
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6873
1
        DORIS_CLOUD_DEFER {
6874
1
            stage_keys.clear();
6875
1
        };
6876
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6877
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6878
0
            return -1;
6879
0
        }
6880
1
        return 0;
6881
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
6871
1
    auto loop_done = [&stage_keys, this]() -> int {
6872
1
        if (stage_keys.empty()) return 0;
6873
1
        DORIS_CLOUD_DEFER {
6874
1
            stage_keys.clear();
6875
1
        };
6876
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
6877
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
6878
0
            return -1;
6879
0
        }
6880
1
        return 0;
6881
1
    };
6882
11
    if (config::enable_recycler_stats_metrics) {
6883
0
        scan_and_statistics_stage();
6884
0
    }
6885
    // recycle_func and loop_done for scan and recycle
6886
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
6887
11
}
6888
6889
10
int InstanceRecycler::recycle_expired_stage_objects() {
6890
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
6891
6892
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6893
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
6894
6895
10
    DORIS_CLOUD_DEFER {
6896
10
        int64_t cost =
6897
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6898
10
        metrics_context.finish_report();
6899
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6900
10
                .tag("instance_id", instance_id_);
6901
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
6895
10
    DORIS_CLOUD_DEFER {
6896
10
        int64_t cost =
6897
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6898
10
        metrics_context.finish_report();
6899
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
6900
10
                .tag("instance_id", instance_id_);
6901
10
    };
6902
6903
10
    int ret = 0;
6904
6905
10
    if (config::enable_recycler_stats_metrics) {
6906
0
        scan_and_statistics_expired_stage_objects();
6907
0
    }
6908
6909
10
    for (const auto& stage : instance_info_.stages()) {
6910
0
        std::stringstream ss;
6911
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
6912
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
6913
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
6914
0
           << ", prefix=" << stage.obj_info().prefix();
6915
6916
0
        if (stopped()) {
6917
0
            break;
6918
0
        }
6919
0
        if (stage.type() == StagePB::EXTERNAL) {
6920
0
            continue;
6921
0
        }
6922
0
        int idx = stoi(stage.obj_info().id());
6923
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6924
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
6925
0
            continue;
6926
0
        }
6927
6928
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6929
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
6930
0
        if (!s3_conf) {
6931
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
6932
0
            continue;
6933
0
        }
6934
6935
0
        s3_conf->prefix = stage.obj_info().prefix();
6936
0
        std::shared_ptr<S3Accessor> accessor;
6937
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
6938
0
        if (ret1 != 0) {
6939
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
6940
0
            ret = -1;
6941
0
            continue;
6942
0
        }
6943
6944
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
6945
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
6946
0
            ret = -1;
6947
0
            continue;
6948
0
        }
6949
6950
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
6951
0
        int64_t expiration_time =
6952
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
6953
0
                config::internal_stage_objects_expire_time_second;
6954
0
        if (config::force_immediate_recycle) {
6955
0
            expiration_time = INT64_MAX;
6956
0
        }
6957
0
        ret1 = accessor->delete_all(expiration_time);
6958
0
        if (ret1 != 0) {
6959
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
6960
0
                         << ss.str();
6961
0
            ret = -1;
6962
0
            continue;
6963
0
        }
6964
0
        metrics_context.total_recycled_num++;
6965
0
        metrics_context.report();
6966
0
    }
6967
10
    return ret;
6968
10
}
6969
6970
181
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
6971
181
    std::lock_guard lock(recycle_tasks_mutex);
6972
181
    running_recycle_tasks[task_name] = start_time;
6973
181
}
6974
6975
181
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
6976
181
    std::lock_guard lock(recycle_tasks_mutex);
6977
181
    DCHECK(running_recycle_tasks[task_name] > 0);
6978
181
    running_recycle_tasks.erase(task_name);
6979
181
}
6980
6981
21
bool InstanceRecycler::check_recycle_tasks() {
6982
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
6983
21
    {
6984
21
        std::lock_guard lock(recycle_tasks_mutex);
6985
21
        tmp_running_recycle_tasks = running_recycle_tasks;
6986
21
    }
6987
6988
21
    bool found = false;
6989
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6990
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
6991
20
        int64_t cost = now - start_time;
6992
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
6993
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
6994
20
                    .tag("instance_id", instance_id_)
6995
20
                    .tag("task", task_name);
6996
20
            found = true;
6997
20
        }
6998
20
    }
6999
7000
21
    return found;
7001
21
}
7002
7003
// Scan and statistics indexes that need to be recycled
7004
0
int InstanceRecycler::scan_and_statistics_indexes() {
7005
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7006
7007
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7008
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7009
0
    std::string index_key0;
7010
0
    std::string index_key1;
7011
0
    recycle_index_key(index_key_info0, &index_key0);
7012
0
    recycle_index_key(index_key_info1, &index_key1);
7013
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7014
7015
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7016
0
        RecycleIndexPB index_pb;
7017
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7018
0
            return 0;
7019
0
        }
7020
0
        int64_t current_time = ::time(nullptr);
7021
0
        if (current_time <
7022
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7023
0
            return 0;
7024
0
        }
7025
        // decode index_id
7026
0
        auto k1 = k;
7027
0
        k1.remove_prefix(1);
7028
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7029
0
        decode_key(&k1, &out);
7030
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7031
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7032
0
        std::unique_ptr<Transaction> txn;
7033
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7034
0
        if (err != TxnErrorCode::TXN_OK) {
7035
0
            return 0;
7036
0
        }
7037
0
        std::string val;
7038
0
        err = txn->get(k, &val);
7039
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7040
0
            return 0;
7041
0
        }
7042
0
        if (err != TxnErrorCode::TXN_OK) {
7043
0
            return 0;
7044
0
        }
7045
0
        index_pb.Clear();
7046
0
        if (!index_pb.ParseFromString(val)) {
7047
0
            return 0;
7048
0
        }
7049
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7050
0
            return 0;
7051
0
        }
7052
0
        metrics_context.total_need_recycle_num++;
7053
0
        return 0;
7054
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_
7055
7056
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7057
0
    metrics_context.report(true);
7058
0
    segment_metrics_context_.report(true);
7059
0
    tablet_metrics_context_.report(true);
7060
0
    return ret;
7061
0
}
7062
7063
// Scan and statistics partitions that need to be recycled
7064
0
int InstanceRecycler::scan_and_statistics_partitions() {
7065
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7066
7067
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7068
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7069
0
    std::string part_key0;
7070
0
    std::string part_key1;
7071
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7072
7073
0
    recycle_partition_key(part_key_info0, &part_key0);
7074
0
    recycle_partition_key(part_key_info1, &part_key1);
7075
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7076
0
        RecyclePartitionPB part_pb;
7077
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7078
0
            return 0;
7079
0
        }
7080
0
        int64_t current_time = ::time(nullptr);
7081
0
        if (current_time <
7082
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7083
0
            return 0;
7084
0
        }
7085
        // decode partition_id
7086
0
        auto k1 = k;
7087
0
        k1.remove_prefix(1);
7088
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7089
0
        decode_key(&k1, &out);
7090
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7091
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7092
        // Change state to RECYCLING
7093
0
        std::unique_ptr<Transaction> txn;
7094
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7095
0
        if (err != TxnErrorCode::TXN_OK) {
7096
0
            return 0;
7097
0
        }
7098
0
        std::string val;
7099
0
        err = txn->get(k, &val);
7100
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7101
0
            return 0;
7102
0
        }
7103
0
        if (err != TxnErrorCode::TXN_OK) {
7104
0
            return 0;
7105
0
        }
7106
0
        part_pb.Clear();
7107
0
        if (!part_pb.ParseFromString(val)) {
7108
0
            return 0;
7109
0
        }
7110
        // Partitions with PREPARED state MUST have no data
7111
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7112
0
        int ret = 0;
7113
0
        for (int64_t index_id : part_pb.index_id()) {
7114
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7115
0
                                            partition_id, is_empty_tablet) != 0) {
7116
0
                ret = 0;
7117
0
            }
7118
0
        }
7119
0
        metrics_context.total_need_recycle_num++;
7120
0
        return ret;
7121
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_
7122
7123
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7124
0
    metrics_context.report(true);
7125
0
    segment_metrics_context_.report(true);
7126
0
    tablet_metrics_context_.report(true);
7127
0
    return ret;
7128
0
}
7129
7130
// Scan and statistics rowsets that need to be recycled
7131
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7132
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7133
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7134
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7135
0
    std::string recyc_rs_key0;
7136
0
    std::string recyc_rs_key1;
7137
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7138
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7139
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7140
7141
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7142
0
        RecycleRowsetPB rowset;
7143
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7144
0
            return 0;
7145
0
        }
7146
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7147
0
        int64_t current_time = ::time(nullptr);
7148
0
        if (current_time <
7149
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7150
0
            return 0;
7151
0
        }
7152
7153
0
        if (!rowset.has_type()) {
7154
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7155
0
                return 0;
7156
0
            }
7157
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7158
0
                return 0;
7159
0
            }
7160
0
            metrics_context.total_need_recycle_num++;
7161
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7162
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7163
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7164
0
            return 0;
7165
0
        }
7166
7167
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7168
0
            return 0;
7169
0
        }
7170
7171
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7172
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7173
0
                return 0;
7174
0
            }
7175
0
        }
7176
0
        metrics_context.total_need_recycle_num++;
7177
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7178
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7179
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7180
0
        return 0;
7181
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_
7182
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7183
0
    metrics_context.report(true);
7184
0
    segment_metrics_context_.report(true);
7185
0
    return ret;
7186
0
}
7187
7188
// Scan and statistics tmp_rowsets that need to be recycled
7189
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7190
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7191
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7192
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7193
0
    std::string tmp_rs_key0;
7194
0
    std::string tmp_rs_key1;
7195
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7196
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7197
7198
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7199
7200
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7201
0
        doris::RowsetMetaCloudPB rowset;
7202
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7203
0
            return 0;
7204
0
        }
7205
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7206
0
        int64_t current_time = ::time(nullptr);
7207
0
        if (current_time < expiration) {
7208
0
            return 0;
7209
0
        }
7210
7211
0
        DCHECK_GT(rowset.txn_id(), 0)
7212
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7213
7214
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7215
0
            return 0;
7216
0
        }
7217
7218
0
        if (!rowset.has_resource_id()) {
7219
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7220
0
                return 0;
7221
0
            }
7222
0
            return 0;
7223
0
        }
7224
7225
0
        metrics_context.total_need_recycle_num++;
7226
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7227
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7228
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7229
0
        return 0;
7230
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_
7231
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7232
0
    metrics_context.report(true);
7233
0
    segment_metrics_context_.report(true);
7234
0
    return ret;
7235
0
}
7236
7237
// Scan and statistics abort_timeout_txn that need to be recycled
7238
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7239
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7240
7241
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7242
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7243
0
    std::string begin_txn_running_key;
7244
0
    std::string end_txn_running_key;
7245
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7246
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7247
7248
0
    int64_t current_time =
7249
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7250
7251
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7252
0
                                               std::string_view k, std::string_view v) -> int {
7253
0
        std::unique_ptr<Transaction> txn;
7254
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7255
0
        if (err != TxnErrorCode::TXN_OK) {
7256
0
            return 0;
7257
0
        }
7258
0
        std::string_view k1 = k;
7259
0
        k1.remove_prefix(1);
7260
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7261
0
        if (decode_key(&k1, &out) != 0) {
7262
0
            return 0;
7263
0
        }
7264
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7265
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7266
        // Update txn_info
7267
0
        std::string txn_inf_key, txn_inf_val;
7268
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7269
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7270
0
        if (err != TxnErrorCode::TXN_OK) {
7271
0
            return 0;
7272
0
        }
7273
0
        TxnInfoPB txn_info;
7274
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7275
0
            return 0;
7276
0
        }
7277
7278
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7279
0
            TxnRunningPB txn_running_pb;
7280
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7281
0
                return 0;
7282
0
            }
7283
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7284
0
                return 0;
7285
0
            }
7286
0
            metrics_context.total_need_recycle_num++;
7287
0
        }
7288
0
        return 0;
7289
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_
7290
7291
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7292
0
    metrics_context.report(true);
7293
0
    return ret;
7294
0
}
7295
7296
// Scan and statistics expired_txn_label that need to be recycled
7297
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7298
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7299
7300
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7301
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7302
0
    std::string begin_recycle_txn_key;
7303
0
    std::string end_recycle_txn_key;
7304
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7305
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7306
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7307
0
    int64_t current_time_ms =
7308
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7309
7310
    // for calculate the total num or bytes of recyled objects
7311
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7312
0
        RecycleTxnPB recycle_txn_pb;
7313
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7314
0
            return 0;
7315
0
        }
7316
0
        if ((config::force_immediate_recycle) ||
7317
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7318
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7319
0
             current_time_ms)) {
7320
0
            metrics_context.total_need_recycle_num++;
7321
0
        }
7322
0
        return 0;
7323
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_
7324
7325
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7326
0
    metrics_context.report(true);
7327
0
    return ret;
7328
0
}
7329
7330
// Scan and statistics copy_jobs that need to be recycled
7331
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7332
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7333
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7334
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7335
0
    std::string key0;
7336
0
    std::string key1;
7337
0
    copy_job_key(key_info0, &key0);
7338
0
    copy_job_key(key_info1, &key1);
7339
7340
    // for calculate the total num or bytes of recyled objects
7341
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7342
0
        CopyJobPB copy_job;
7343
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7344
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7345
0
            return 0;
7346
0
        }
7347
7348
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7349
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7350
0
                int64_t current_time =
7351
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7352
0
                if (copy_job.finish_time_ms() > 0) {
7353
0
                    if (!config::force_immediate_recycle &&
7354
0
                        current_time < copy_job.finish_time_ms() +
7355
0
                                               config::copy_job_max_retention_second * 1000) {
7356
0
                        return 0;
7357
0
                    }
7358
0
                } else {
7359
0
                    if (!config::force_immediate_recycle &&
7360
0
                        current_time < copy_job.start_time_ms() +
7361
0
                                               config::copy_job_max_retention_second * 1000) {
7362
0
                        return 0;
7363
0
                    }
7364
0
                }
7365
0
            }
7366
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7367
0
            int64_t current_time =
7368
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7369
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7370
0
                return 0;
7371
0
            }
7372
0
        }
7373
0
        metrics_context.total_need_recycle_num++;
7374
0
        return 0;
7375
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_
7376
7377
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7378
0
    metrics_context.report(true);
7379
0
    return ret;
7380
0
}
7381
7382
// Scan and statistics stage that need to be recycled
7383
0
int InstanceRecycler::scan_and_statistics_stage() {
7384
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7385
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7386
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7387
0
    std::string key0 = recycle_stage_key(key_info0);
7388
0
    std::string key1 = recycle_stage_key(key_info1);
7389
7390
    // for calculate the total num or bytes of recyled objects
7391
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7392
0
                                                        std::string_view v) -> int {
7393
0
        RecycleStagePB recycle_stage;
7394
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7395
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7396
0
            return 0;
7397
0
        }
7398
7399
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7400
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7401
0
            LOG(WARNING) << "invalid idx: " << idx;
7402
0
            return 0;
7403
0
        }
7404
7405
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7406
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7407
0
                [&] {
7408
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7409
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7410
0
                    if (!s3_conf) {
7411
0
                        return 0;
7412
0
                    }
7413
7414
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7415
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7416
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7417
0
                    if (ret != 0) {
7418
0
                        return 0;
7419
0
                    }
7420
7421
0
                    accessor = std::move(s3_accessor);
7422
0
                    return 0;
7423
0
                }(),
7424
0
                "recycle_stage:get_accessor", &accessor);
7425
7426
0
        if (ret != 0) {
7427
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7428
0
            return 0;
7429
0
        }
7430
7431
0
        metrics_context.total_need_recycle_num++;
7432
0
        return 0;
7433
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_
7434
7435
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7436
0
    metrics_context.report(true);
7437
0
    return ret;
7438
0
}
7439
7440
// Scan and statistics expired_stage_objects that need to be recycled
7441
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7442
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7443
7444
    // for calculate the total num or bytes of recyled objects
7445
0
    auto scan_and_statistics = [&metrics_context, this]() {
7446
0
        for (const auto& stage : instance_info_.stages()) {
7447
0
            if (stopped()) {
7448
0
                break;
7449
0
            }
7450
0
            if (stage.type() == StagePB::EXTERNAL) {
7451
0
                continue;
7452
0
            }
7453
0
            int idx = stoi(stage.obj_info().id());
7454
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7455
0
                continue;
7456
0
            }
7457
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7458
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7459
0
            if (!s3_conf) {
7460
0
                continue;
7461
0
            }
7462
0
            s3_conf->prefix = stage.obj_info().prefix();
7463
0
            std::shared_ptr<S3Accessor> accessor;
7464
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7465
0
            if (ret1 != 0) {
7466
0
                continue;
7467
0
            }
7468
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7469
0
                continue;
7470
0
            }
7471
0
            metrics_context.total_need_recycle_num++;
7472
0
        }
7473
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7474
7475
0
    scan_and_statistics();
7476
0
    metrics_context.report(true);
7477
0
    return 0;
7478
0
}
7479
7480
// Scan and statistics versions that need to be recycled
7481
0
int InstanceRecycler::scan_and_statistics_versions() {
7482
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7483
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7484
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7485
7486
0
    int64_t last_scanned_table_id = 0;
7487
0
    bool is_recycled = false; // Is last scanned kv recycled
7488
    // for calculate the total num or bytes of recyled objects
7489
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7490
0
                                       std::string_view k, std::string_view) {
7491
0
        auto k1 = k;
7492
0
        k1.remove_prefix(1);
7493
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7494
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7495
0
        decode_key(&k1, &out);
7496
0
        DCHECK_EQ(out.size(), 6) << k;
7497
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7498
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7499
0
            metrics_context.total_need_recycle_num +=
7500
0
                    is_recycled; // Version kv of this table has been recycled
7501
0
            return 0;
7502
0
        }
7503
0
        last_scanned_table_id = table_id;
7504
0
        is_recycled = false;
7505
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7506
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7507
0
        std::unique_ptr<Transaction> txn;
7508
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7509
0
        if (err != TxnErrorCode::TXN_OK) {
7510
0
            return 0;
7511
0
        }
7512
0
        std::unique_ptr<RangeGetIterator> iter;
7513
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7514
0
        if (err != TxnErrorCode::TXN_OK) {
7515
0
            return 0;
7516
0
        }
7517
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7518
0
            return 0;
7519
0
        }
7520
0
        metrics_context.total_need_recycle_num++;
7521
0
        is_recycled = true;
7522
0
        return 0;
7523
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_
7524
7525
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7526
0
    metrics_context.report(true);
7527
0
    return ret;
7528
0
}
7529
7530
// Scan and statistics restore jobs that need to be recycled
7531
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7532
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7533
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7534
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7535
0
    std::string restore_job_key0;
7536
0
    std::string restore_job_key1;
7537
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7538
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7539
7540
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7541
7542
    // for calculate the total num or bytes of recyled objects
7543
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7544
0
        RestoreJobCloudPB restore_job_pb;
7545
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7546
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7547
0
            return 0;
7548
0
        }
7549
0
        int64_t expiration =
7550
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7551
0
        int64_t current_time = ::time(nullptr);
7552
0
        if (current_time < expiration) { // not expired
7553
0
            return 0;
7554
0
        }
7555
0
        metrics_context.total_need_recycle_num++;
7556
0
        if(restore_job_pb.need_recycle_data()) {
7557
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7558
0
        }
7559
0
        return 0;
7560
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_
7561
7562
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7563
0
    metrics_context.report(true);
7564
0
    return ret;
7565
0
}
7566
7567
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7568
3
    if (!should_recycle_versioned_keys()) {
7569
0
        return;
7570
0
    }
7571
7572
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7573
7574
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7575
3
    if (recycle_checker.init() != 0) {
7576
0
        return;
7577
0
    }
7578
7579
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7580
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7581
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7582
7583
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7584
8
    for (; iter->valid(); iter->next()) {
7585
5
        OperationLogPB operation_log;
7586
5
        if (!iter->parse_value(&operation_log)) {
7587
0
            continue;
7588
0
        }
7589
7590
5
        std::string_view key = iter->key();
7591
5
        Versionstamp log_versionstamp;
7592
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7593
0
            continue;
7594
0
        }
7595
7596
5
        OperationLogReferenceInfo ref_info;
7597
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7598
5
                                         &ref_info)) {
7599
4
            metrics_context.total_need_recycle_num++;
7600
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7601
4
        }
7602
5
    }
7603
7604
3
    metrics_context.report(true);
7605
3
}
7606
7607
int InstanceRecycler::classify_rowset_task_by_ref_count(
7608
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7609
60
    constexpr int MAX_RETRY = 10;
7610
60
    const auto& rowset_meta = task.rowset_meta;
7611
60
    int64_t tablet_id = rowset_meta.tablet_id();
7612
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7613
60
    std::string_view reference_instance_id = instance_id_;
7614
60
    if (rowset_meta.has_reference_instance_id()) {
7615
5
        reference_instance_id = rowset_meta.reference_instance_id();
7616
5
    }
7617
7618
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7619
61
        std::unique_ptr<Transaction> txn;
7620
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7621
61
        if (err != TxnErrorCode::TXN_OK) {
7622
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7623
0
                    .tag("instance_id", instance_id_)
7624
0
                    .tag("tablet_id", tablet_id)
7625
0
                    .tag("rowset_id", rowset_id)
7626
0
                    .tag("err", err);
7627
0
            return -1;
7628
0
        }
7629
7630
61
        std::string rowset_ref_count_key =
7631
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7632
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7633
7634
61
        int64_t ref_count = 0;
7635
61
        {
7636
61
            std::string value;
7637
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7638
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7639
0
                ref_count = 1;
7640
61
            } else if (err != TxnErrorCode::TXN_OK) {
7641
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7642
0
                        .tag("instance_id", instance_id_)
7643
0
                        .tag("tablet_id", tablet_id)
7644
0
                        .tag("rowset_id", rowset_id)
7645
0
                        .tag("err", err);
7646
0
                return -1;
7647
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7648
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7649
0
                        .tag("instance_id", instance_id_)
7650
0
                        .tag("tablet_id", tablet_id)
7651
0
                        .tag("rowset_id", rowset_id)
7652
0
                        .tag("value", hex(value));
7653
0
                return -1;
7654
0
            }
7655
61
        }
7656
7657
61
        if (ref_count > 1) {
7658
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7659
12
            txn->atomic_add(rowset_ref_count_key, -1);
7660
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7661
12
                    .tag("instance_id", instance_id_)
7662
12
                    .tag("tablet_id", tablet_id)
7663
12
                    .tag("rowset_id", rowset_id)
7664
12
                    .tag("ref_count", ref_count - 1)
7665
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7666
7667
12
            if (!task.recycle_rowset_key.empty()) {
7668
12
                txn->remove(task.recycle_rowset_key);
7669
12
                LOG_INFO("remove recycle rowset key in classification phase")
7670
12
                        .tag("key", hex(task.recycle_rowset_key));
7671
12
            }
7672
12
            if (!task.non_versioned_rowset_key.empty()) {
7673
12
                txn->remove(task.non_versioned_rowset_key);
7674
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7675
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7676
12
            }
7677
7678
12
            err = txn->commit();
7679
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7680
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7681
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7682
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7683
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7684
1
                continue;
7685
11
            } else if (err != TxnErrorCode::TXN_OK) {
7686
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7687
0
                        .tag("instance_id", instance_id_)
7688
0
                        .tag("tablet_id", tablet_id)
7689
0
                        .tag("rowset_id", rowset_id)
7690
0
                        .tag("err", err);
7691
0
                return -1;
7692
0
            }
7693
11
            return 1; // handled, not added to batch delete
7694
49
        } else {
7695
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7696
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7697
49
            LOG_INFO("add rowset to batch delete plan")
7698
49
                    .tag("instance_id", instance_id_)
7699
49
                    .tag("tablet_id", tablet_id)
7700
49
                    .tag("rowset_id", rowset_id)
7701
49
                    .tag("resource_id", rowset_meta.resource_id())
7702
49
                    .tag("ref_count", ref_count);
7703
7704
49
            batch_delete_tasks.push_back(std::move(task));
7705
49
            return 0; // added to batch delete
7706
49
        }
7707
61
    }
7708
7709
0
    LOG_WARNING("failed to classify rowset task after retry")
7710
0
            .tag("instance_id", instance_id_)
7711
0
            .tag("tablet_id", tablet_id)
7712
0
            .tag("rowset_id", rowset_id)
7713
0
            .tag("retry", MAX_RETRY);
7714
0
    return -1;
7715
60
}
7716
7717
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7718
10
    int ret = 0;
7719
49
    for (const auto& task : tasks) {
7720
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7721
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7722
7723
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7724
        // so we don't need to call it again here.
7725
7726
        // Remove all metadata keys in one transaction
7727
49
        std::unique_ptr<Transaction> txn;
7728
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7729
49
        if (err != TxnErrorCode::TXN_OK) {
7730
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7731
0
                    .tag("instance_id", instance_id_)
7732
0
                    .tag("tablet_id", tablet_id)
7733
0
                    .tag("rowset_id", rowset_id)
7734
0
                    .tag("err", err);
7735
0
            ret = -1;
7736
0
            continue;
7737
0
        }
7738
7739
49
        std::string_view reference_instance_id = instance_id_;
7740
49
        if (task.rowset_meta.has_reference_instance_id()) {
7741
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
7742
0
        }
7743
7744
49
        txn->remove(task.rowset_ref_count_key);
7745
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7746
49
                .tag("instance_id", instance_id_)
7747
49
                .tag("tablet_id", tablet_id)
7748
49
                .tag("rowset_id", rowset_id)
7749
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7750
7751
49
        std::string dbm_start_key =
7752
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7753
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7754
49
                {reference_instance_id, tablet_id, rowset_id,
7755
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7756
49
        txn->remove(dbm_start_key, dbm_end_key);
7757
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7758
49
                .tag("instance_id", instance_id_)
7759
49
                .tag("tablet_id", tablet_id)
7760
49
                .tag("rowset_id", rowset_id)
7761
49
                .tag("begin", hex(dbm_start_key))
7762
49
                .tag("end", hex(dbm_end_key));
7763
7764
49
        std::string versioned_dbm_start_key =
7765
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7766
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7767
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7768
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7769
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7770
49
                .tag("instance_id", instance_id_)
7771
49
                .tag("tablet_id", tablet_id)
7772
49
                .tag("rowset_id", rowset_id)
7773
49
                .tag("begin", hex(versioned_dbm_start_key))
7774
49
                .tag("end", hex(versioned_dbm_end_key));
7775
7776
        // Remove versioned meta rowset key
7777
49
        if (!task.versioned_rowset_key.empty()) {
7778
49
            std::string versioned_rowset_key_end = task.versioned_rowset_key;
7779
49
            encode_int64(INT64_MAX, &versioned_rowset_key_end);
7780
49
            txn->remove(task.versioned_rowset_key, versioned_rowset_key_end);
7781
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7782
49
                    .tag("instance_id", instance_id_)
7783
49
                    .tag("tablet_id", tablet_id)
7784
49
                    .tag("rowset_id", rowset_id)
7785
49
                    .tag("begin", hex(task.versioned_rowset_key))
7786
49
                    .tag("end", hex(versioned_rowset_key_end));
7787
49
        }
7788
7789
49
        if (!task.non_versioned_rowset_key.empty()) {
7790
49
            txn->remove(task.non_versioned_rowset_key);
7791
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7792
49
                    .tag("instance_id", instance_id_)
7793
49
                    .tag("tablet_id", tablet_id)
7794
49
                    .tag("rowset_id", rowset_id)
7795
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7796
49
        }
7797
7798
        // Remove recycle_rowset_key last to ensure retry safety:
7799
        // if cleanup fails, this key remains and triggers next round retry.
7800
49
        if (!task.recycle_rowset_key.empty()) {
7801
49
            txn->remove(task.recycle_rowset_key);
7802
49
            LOG_INFO("remove recycle rowset key in cleanup phase")
7803
49
                    .tag("instance_id", instance_id_)
7804
49
                    .tag("tablet_id", tablet_id)
7805
49
                    .tag("rowset_id", rowset_id)
7806
49
                    .tag("key", hex(task.recycle_rowset_key));
7807
49
        }
7808
7809
49
        err = txn->commit();
7810
49
        if (err != TxnErrorCode::TXN_OK) {
7811
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
7812
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
7813
0
                    .tag("instance_id", instance_id_)
7814
0
                    .tag("tablet_id", tablet_id)
7815
0
                    .tag("rowset_id", rowset_id)
7816
0
                    .tag("err", err);
7817
0
            ret = -1;
7818
0
            continue;
7819
0
        }
7820
7821
49
        LOG_INFO("cleanup rowset metadata success")
7822
49
                .tag("instance_id", instance_id_)
7823
49
                .tag("tablet_id", tablet_id)
7824
49
                .tag("rowset_id", rowset_id);
7825
49
    }
7826
10
    return ret;
7827
10
}
7828
7829
} // namespace doris::cloud