Coverage Report

Created: 2026-08-12 21:34

/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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
109
868k
    const auto& locations = rowset.packed_slice_locations();
110
868k
    auto it = locations.find(path);
111
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
112
868k
           !it->second.packed_file_path().empty();
113
868k
}
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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
109
868k
    const auto& locations = rowset.packed_slice_locations();
110
868k
    auto it = locations.find(path);
111
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
112
868k
           !it->second.packed_file_path().empty();
113
868k
}
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
868k
    if (!is_packed_slice_path(rowset, path)) {
119
868k
        file_paths->push_back(path);
120
868k
    }
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
868k
    if (!is_packed_slice_path(rowset, path)) {
119
868k
        file_paths->push_back(path);
120
868k
    }
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
312
                   std::unique_ptr<RangeGetIterator>& it) {
145
312
    std::unique_ptr<Transaction> txn;
146
312
    TxnErrorCode err = txn_kv->create_txn(&txn);
147
312
    if (err != TxnErrorCode::TXN_OK) {
148
0
        return -1;
149
0
    }
150
312
    switch (txn->get(begin, end, &it, true)) {
151
312
    case TxnErrorCode::TXN_OK:
152
312
        return 0;
153
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
154
0
        return 1;
155
0
    default:
156
0
        return -1;
157
312
    };
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
281
                   std::unique_ptr<RangeGetIterator>& it) {
145
281
    std::unique_ptr<Transaction> txn;
146
281
    TxnErrorCode err = txn_kv->create_txn(&txn);
147
281
    if (err != TxnErrorCode::TXN_OK) {
148
0
        return -1;
149
0
    }
150
281
    switch (txn->get(begin, end, &it, true)) {
151
281
    case TxnErrorCode::TXN_OK:
152
281
        return 0;
153
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
154
0
        return 1;
155
0
    default:
156
0
        return -1;
157
281
    };
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
101
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
182
101
    std::unique_ptr<Transaction> txn;
183
101
    TxnErrorCode err = txn_kv->create_txn(&txn);
184
101
    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
101
    switch (txn->commit()) {
191
101
    case TxnErrorCode::TXN_OK:
192
101
        return 0;
193
0
    case TxnErrorCode::TXN_CONFLICT:
194
0
        return -1;
195
0
    default:
196
0
        return -1;
197
101
    }
198
101
}
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
67
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
182
67
    std::unique_ptr<Transaction> txn;
183
67
    TxnErrorCode err = txn_kv->create_txn(&txn);
184
67
    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
67
    switch (txn->commit()) {
191
67
    case TxnErrorCode::TXN_OK:
192
67
        return 0;
193
0
    case TxnErrorCode::TXN_CONFLICT:
194
0
        return -1;
195
0
    default:
196
0
        return -1;
197
67
    }
198
67
}
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.24k
    while (!stopped()) {
275
1.23k
        if (config::enable_recycler) {
276
3
            std::vector<InstanceInfoPB> instances;
277
3
            get_all_instances(txn_kv_.get(), instances);
278
            // TODO(plat1ko): delete job recycle kv of non-existent instances
279
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
280
3
                std::stringstream ss;
281
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
282
3
                return ss.str();
283
3
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
279
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
280
3
                std::stringstream ss;
281
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
282
3
                return ss.str();
283
3
            }();
284
3
            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.23k
        } else {
298
1.23k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
299
1.23k
        }
300
1.23k
        {
301
1.23k
            std::unique_lock lock(mtx_);
302
1.23k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
303
2.47k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
303
2.47k
                               [&]() { return stopped(); });
304
1.23k
        }
305
1.23k
    }
306
5
}
307
308
9
void Recycler::recycle_callback() {
309
39
    while (!stopped()) {
310
36
        InstanceInfoPB instance;
311
36
        {
312
36
            std::unique_lock lock(mtx_);
313
36
            pending_instance_cond_.wait(
314
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
314
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
315
36
            if (stopped()) {
316
6
                return;
317
6
            }
318
30
            instance = std::move(pending_instance_queue_.front());
319
30
            pending_instance_queue_.pop_front();
320
30
            pending_instance_set_.erase(instance.instance_id());
321
30
        }
322
0
        auto& instance_id = instance.instance_id();
323
30
        {
324
30
            std::lock_guard lock(mtx_);
325
            // skip instance in recycling
326
30
            if (recycling_instance_map_.count(instance_id)) continue;
327
30
        }
328
30
        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
29
        auto instance_recycler = std::make_shared<InstanceRecycler>(
334
29
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
335
336
29
        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
29
        std::string recycle_job_key;
342
29
        job_recycle_key({instance_id}, &recycle_job_key);
343
29
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
344
29
                                               ip_port_, config::recycle_interval_seconds * 1000);
345
29
        if (ret != 0) { // Prepare failed
346
19
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
347
19
                         << " ret=" << ret;
348
19
            continue;
349
19
        } else {
350
10
            std::lock_guard lock(mtx_);
351
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
352
10
        }
353
10
        if (stopped()) return;
354
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
355
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
356
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
357
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
358
10
        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
10
        {
369
10
            std::lock_guard lock(mtx_);
370
10
            recycling_instance_map_.erase(instance_id);
371
10
        }
372
373
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
374
10
        auto elpased_ms = now - ctime_ms;
375
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
376
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
377
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
378
10
                                             now + config::recycle_interval_seconds * 1000);
379
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
380
10
        LOG(INFO) << "recycle instance done, "
381
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
382
10
                  << " now: " << now;
383
384
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
385
386
10
        LOG_WARNING("finish recycle instance")
387
10
                .tag("instance_id", instance_id)
388
10
                .tag("cost_ms", elpased_ms);
389
10
    }
390
9
}
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
8
        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
139
            : 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
4.04k
                return 0;
537
4.04k
            }
538
24.3k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
539
24.3k
                it != inverted_index_id_map_.end()) {
540
17.6k
                res = it->second;
541
17.6k
                return 0;
542
17.6k
            }
543
24.3k
        }
544
        // Get schema from kv
545
        // TODO(plat1ko): Single flight
546
6.72k
        std::unique_ptr<Transaction> txn;
547
6.72k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
548
6.72k
        if (err != TxnErrorCode::TXN_OK) {
549
0
            LOG(WARNING) << "failed to create txn, err=" << err;
550
0
            return -1;
551
0
        }
552
6.72k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
553
6.72k
        ValueBuf val_buf;
554
6.72k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
555
6.72k
        if (err != TxnErrorCode::TXN_OK) {
556
504
            LOG(WARNING) << "failed to get schema, err=" << err;
557
504
            return static_cast<int>(err);
558
504
        }
559
6.22k
        doris::TabletSchemaCloudPB schema;
560
6.22k
        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.22k
        if (schema.index_size() > 0) {
565
4.56k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
566
4.56k
            if (schema.has_inverted_index_storage_format()) {
567
4.56k
                index_format = schema.inverted_index_storage_format();
568
4.56k
            }
569
4.56k
            res.first = index_format;
570
4.56k
            res.second.reserve(schema.index_size());
571
11.6k
            for (auto& i : schema.index()) {
572
11.6k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
573
11.6k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
574
11.6k
                }
575
11.6k
            }
576
4.56k
        }
577
6.22k
        insert(index_id, schema_version, res);
578
6.22k
        return 0;
579
6.22k
    }
580
581
    // Empty `ids` means this schema has no inverted index
582
6.22k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
583
6.22k
        if (index_info.second.empty()) {
584
1.65k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
585
1.65k
            std::lock_guard lock(mtx_);
586
1.65k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
587
4.56k
        } else {
588
4.56k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
589
4.56k
            std::lock_guard lock(mtx_);
590
4.56k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
591
4.56k
        }
592
6.22k
    }
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
139
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
625
139
    delete_bitmap_lock_white_list_->init();
626
139
    resource_mgr_->init();
627
139
    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
139
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
632
139
};
633
634
139
InstanceRecycler::~InstanceRecycler() = default;
635
636
121
int InstanceRecycler::init_obj_store_accessors() {
637
121
    for (const auto& obj_info : instance_info_.obj_info()) {
638
79
#ifdef UNIT_TEST
639
79
        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
79
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
656
79
    }
657
658
121
    return 0;
659
121
}
660
661
121
int InstanceRecycler::init_storage_vault_accessors() {
662
121
    if (instance_info_.resource_ids().empty()) {
663
114
        return 0;
664
114
    }
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
122
int InstanceRecycler::init() {
757
122
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
758
122
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
759
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
760
1
        return 0;
761
1
    }
762
763
121
    int ret = init_obj_store_accessors();
764
121
    if (ret != 0) {
765
0
        return ret;
766
0
    }
767
768
121
    return init_storage_vault_accessors();
769
121
}
770
771
template <typename... Func>
772
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
120
    return [funcs...]() {
774
120
        return [](std::initializer_list<int> ret_vals) {
775
120
            int i = 0;
776
140
            for (int ret : ret_vals) {
777
140
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
140
            }
781
120
            return i;
782
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
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
20
            for (int ret : ret_vals) {
777
20
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
20
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
20
            for (int ret : ret_vals) {
777
20
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
20
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
0
                    i = ret;
779
0
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
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
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
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
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
772
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
773
10
    return [funcs...]() {
774
10
        return [](std::initializer_list<int> ret_vals) {
775
10
            int i = 0;
776
10
            for (int ret : ret_vals) {
777
10
                if (ret != 0) {
778
10
                    i = ret;
779
10
                }
780
10
            }
781
10
            return i;
782
10
        }({funcs()...});
783
10
    };
784
10
}
785
786
11
int InstanceRecycler::do_recycle() {
787
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
788
11
    tablet_metrics_context_.reset();
789
11
    segment_metrics_context_.reset();
790
11
    DORIS_CLOUD_DEFER {
791
11
        tablet_metrics_context_.finish_report();
792
11
        segment_metrics_context_.finish_report();
793
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
790
11
    DORIS_CLOUD_DEFER {
791
11
        tablet_metrics_context_.finish_report();
792
11
        segment_metrics_context_.finish_report();
793
11
    };
794
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
795
1
        int res = recycle_cluster_snapshots();
796
1
        if (res != 0) {
797
0
            return -1;
798
0
        }
799
1
        return recycle_deleted_instance();
800
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
801
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
802
10
                                        fmt::format("instance id {}", instance_id_),
803
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
803
120
                                        [](int r) { return r != 0; });
804
10
        sync_executor
805
10
                .add(task_wrapper(
806
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
806
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
807
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
807
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
808
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
809
                                   // becase they may both recycle the same set of tablets
810
                        // recycle dropped table or idexes(mv, rollup)
811
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
811
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
812
                        // recycle dropped partitions
813
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
813
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
814
10
                .add(task_wrapper(
815
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
815
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
816
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
816
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
817
10
                .add(task_wrapper(
818
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
818
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
819
10
                .add(task_wrapper(
820
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
820
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
821
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
821
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
822
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
822
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
823
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
823
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
824
10
                .add(task_wrapper(
825
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
825
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
826
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
826
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
827
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
827
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
828
10
        bool finished = true;
829
10
        std::vector<int> rets = sync_executor.when_all(&finished);
830
120
        for (int ret : rets) {
831
120
            if (ret != 0) {
832
0
                return ret;
833
0
            }
834
120
        }
835
10
        return finished ? 0 : -1;
836
10
    } else {
837
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
838
0
                     << " instance_id=" << instance_id_;
839
0
        return -1;
840
0
    }
841
11
}
842
843
/**
844
* 1. delete all remote data
845
* 2. delete all kv
846
* 3. remove instance kv
847
*/
848
13
int InstanceRecycler::recycle_deleted_instance() {
849
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
850
851
13
    int ret = 0;
852
13
    auto start_time = steady_clock::now();
853
13
    const auto recycle_state = instance_info_.recycle_state();
854
855
13
    DORIS_CLOUD_DEFER {
856
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
857
13
        if (ret != 0) {
858
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
859
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
860
0
                         << "s, instance_id=" << instance_id_;
861
13
        } else if (recycle_state ==
862
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
863
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
864
4
                      << "s, instance_id=" << instance_id_;
865
9
        } else {
866
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
867
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
868
9
                      << "s, instance_id=" << instance_id_;
869
9
        }
870
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
855
13
    DORIS_CLOUD_DEFER {
856
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
857
13
        if (ret != 0) {
858
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
859
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
860
0
                         << "s, instance_id=" << instance_id_;
861
13
        } else if (recycle_state ==
862
13
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
863
4
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
864
4
                      << "s, instance_id=" << instance_id_;
865
9
        } else {
866
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
867
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
868
9
                      << "s, instance_id=" << instance_id_;
869
9
        }
870
13
    };
871
872
13
    switch (recycle_state) {
873
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
874
6
        ret = recycle_deleted_instance_data();
875
6
        break;
876
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
877
3
        ret = recycle_deleted_instance_metadata();
878
3
        break;
879
4
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
880
4
        ret = remove_instance_key();
881
4
        break;
882
0
    default:
883
0
        LOG_WARNING("invalid instance recycle state")
884
0
                .tag("instance_id", instance_id_)
885
0
                .tag("recycle_state", instance_info_.recycle_state());
886
0
        ret = -1;
887
0
        break;
888
13
    }
889
890
13
    return ret;
891
13
}
892
893
6
int InstanceRecycler::recycle_deleted_instance_data() {
894
6
    int ret = 0;
895
896
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
897
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
898
6
        int res = recycle_tmp_rowsets();
899
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
900
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
901
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
902
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
903
            // and cannot be recycled.
904
0
            res = recycle_tmp_rowsets();
905
0
        }
906
6
        return res;
907
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
897
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
898
6
        int res = recycle_tmp_rowsets();
899
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
900
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
901
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
902
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
903
            // and cannot be recycled.
904
0
            res = recycle_tmp_rowsets();
905
0
        }
906
6
        return res;
907
6
    };
908
909
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
910
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
911
0
        return -1;
912
0
    }
913
914
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
915
6
    if (recycle_versioned_rowsets() != 0) {
916
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
917
0
        return -1;
918
0
    }
919
920
    // Step 2: Recycle operation logs (can recycle logs not referenced by snapshots)
921
6
    if (recycle_operation_logs() != 0) {
922
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
923
0
        return -1;
924
0
    }
925
926
    // Step 3: Check if there are still cluster snapshots
927
6
    bool has_snapshots = false;
928
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
929
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
930
0
        return -1;
931
6
    } else if (has_snapshots) {
932
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
933
1
        return 0;
934
1
    }
935
936
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
937
5
                            instance_info().snapshot_switch_status() !=
938
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
939
5
    if (snapshot_enabled) {
940
1
        bool has_unrecycled_rowsets = false;
941
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
942
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
943
0
            return -1;
944
1
        } else if (has_unrecycled_rowsets) {
945
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
946
0
                    .tag("instance_id", instance_id_);
947
0
            return ret;
948
0
        }
949
4
    } else { // delete all remote data if snapshot is disabled
950
4
        for (auto& [_, accessor] : accessor_map_) {
951
4
            if (stopped()) {
952
0
                return ret;
953
0
            }
954
955
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
956
4
            int del_ret = accessor->delete_all();
957
4
            if (del_ret == 0) {
958
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
959
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
960
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
961
                // so the recycling has been successful.
962
0
                ret = -1;
963
0
            }
964
4
        }
965
966
4
        if (ret != 0) {
967
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
968
0
            return ret;
969
0
        }
970
4
    }
971
972
5
    if (update_instance_recycle_state(
973
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
974
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
975
0
        return -1;
976
0
    }
977
978
5
    return 0;
979
5
}
980
981
3
int InstanceRecycler::recycle_deleted_instance_metadata() {
982
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
983
3
    if (instance_info_.has_successor_instance_id() &&
984
3
        !instance_info_.successor_instance_id().empty()) {
985
0
        std::string key = instance_key(instance_info_.successor_instance_id());
986
0
        std::unique_ptr<Transaction> txn;
987
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
988
0
        if (err != TxnErrorCode::TXN_OK) {
989
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
990
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
991
0
                         << " err=" << err;
992
0
            return -1;
993
0
        }
994
995
0
        std::string value;
996
0
        err = txn->get(key, &value);
997
0
        if (err == TxnErrorCode::TXN_OK) {
998
0
            LOG(INFO) << "instance successor instance is still exist, skip deleting kv,"
999
0
                      << " instance_id=" << instance_id_
1000
0
                      << " successor_instance_id=" << instance_info_.successor_instance_id();
1001
0
            return 0;
1002
0
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1003
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1004
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1005
0
                         << " err=" << err;
1006
0
            return -1;
1007
0
        }
1008
0
    }
1009
1010
    // delete all kv
1011
3
    std::unique_ptr<Transaction> txn;
1012
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1013
3
    if (err != TxnErrorCode::TXN_OK) {
1014
0
        LOG(WARNING) << "failed to create txn";
1015
0
        return -1;
1016
0
    }
1017
3
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1018
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1019
3
    std::string start_txn_key = txn_key_prefix(instance_id_);
1020
3
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1021
3
    txn->remove(start_txn_key, end_txn_key);
1022
3
    std::string start_version_key = version_key_prefix(instance_id_);
1023
3
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1024
3
    txn->remove(start_version_key, end_version_key);
1025
3
    std::string start_meta_key = meta_key_prefix(instance_id_);
1026
3
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1027
3
    txn->remove(start_meta_key, end_meta_key);
1028
3
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1029
3
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1030
3
    txn->remove(start_recycle_key, end_recycle_key);
1031
3
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1032
3
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1033
3
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1034
3
    std::string start_copy_key = copy_key_prefix(instance_id_);
1035
3
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1036
3
    txn->remove(start_copy_key, end_copy_key);
1037
    // should not remove job key range, because we need to reserve job recycle kv
1038
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1039
3
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1040
3
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1041
3
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1042
3
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1043
3
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1044
3
    std::string start_vault_key = storage_vault_key(key_info0);
1045
3
    std::string end_vault_key = storage_vault_key(key_info1);
1046
3
    txn->remove(start_vault_key, end_vault_key);
1047
3
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1048
3
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1049
3
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1050
3
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1051
3
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1052
3
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1053
3
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1054
3
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1055
3
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1056
3
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1057
3
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1058
3
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1059
3
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1060
3
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1061
3
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1062
3
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1063
3
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1064
3
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1065
1066
    // Updating the recycle state also commits this transaction, making the metadata deletions
1067
    // and state transition atomic.
1068
3
    if (update_instance_recycle_state(
1069
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1070
3
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1071
0
        return -1;
1072
0
    }
1073
1074
3
    return 0;
1075
3
}
1076
1077
4
int InstanceRecycler::remove_instance_key() {
1078
4
    std::unique_ptr<Transaction> txn;
1079
4
    std::string key = instance_key(instance_info_.instance_id());
1080
4
    std::string value;
1081
4
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1082
4
    if (err != TxnErrorCode::TXN_OK) {
1083
0
        LOG(WARNING) << "failed to create txn";
1084
0
        return -1;
1085
0
    }
1086
1087
4
    err = txn->get(key, &value);
1088
4
    if (err != TxnErrorCode::TXN_OK) {
1089
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1090
0
                     << ", err=" << err;
1091
0
        return -1;
1092
0
    }
1093
1094
4
    InstanceInfoPB instance;
1095
4
    if (!instance.ParseFromString(value)) {
1096
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1097
0
        return -1;
1098
0
    }
1099
1100
4
    if (instance.status() != InstanceInfoPB::DELETED) {
1101
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1102
0
                     << instance_id_ << ", status=" << instance.status();
1103
0
        return -1;
1104
0
    }
1105
1106
4
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1107
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1108
0
                     << instance_id_
1109
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1110
0
                     << ", expected_state="
1111
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1112
0
        return -1;
1113
0
    }
1114
1115
4
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1116
4
    txn->remove(key);
1117
4
    err = txn->commit();
1118
4
    if (err != TxnErrorCode::TXN_OK) {
1119
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1120
0
                     << " err=" << err;
1121
0
        return -1;
1122
0
    }
1123
4
    return 0;
1124
4
}
1125
1126
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1127
7
                                                    InstanceRecycleState target_state) {
1128
7
    std::unique_ptr<Transaction> txn;
1129
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1130
7
    if (err != TxnErrorCode::TXN_OK) {
1131
0
        LOG(WARNING) << "failed to create txn";
1132
0
        return -1;
1133
0
    }
1134
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1135
7
}
1136
1137
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1138
                                                    InstanceRecycleState target_state,
1139
10
                                                    Transaction* txn) {
1140
10
    const bool valid_transition =
1141
10
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1142
10
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1143
10
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1144
4
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1145
1146
10
    if (!valid_transition) {
1147
1
        LOG_WARNING("invalid instance recycled state transition")
1148
1
                .tag("instance_id", instance_id_)
1149
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1150
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1151
1
        return -1;
1152
1
    }
1153
1154
9
    std::string key = instance_key({instance_id_});
1155
9
    std::string value;
1156
9
    TxnErrorCode err = txn->get(key, &value);
1157
9
    if (err != TxnErrorCode::TXN_OK) {
1158
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1159
0
                .tag("instance_id", instance_id_)
1160
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1161
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1162
0
                .tag("err", err);
1163
0
        return -1;
1164
0
    }
1165
1166
9
    InstanceInfoPB instance;
1167
9
    if (!instance.ParseFromString(value)) {
1168
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1169
0
                .tag("instance_id", instance_id_)
1170
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1171
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1172
0
        return -1;
1173
0
    }
1174
9
    if (instance.status() != InstanceInfoPB::DELETED) {
1175
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1176
0
                .tag("instance_id", instance_id_)
1177
0
                .tag("status", instance.status())
1178
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1179
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1180
0
        return -1;
1181
0
    }
1182
9
    if (instance.recycle_state() != current_state) {
1183
1
        LOG_WARNING("instance recycled state changed before update")
1184
1
                .tag("instance_id", instance_id_)
1185
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1186
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1187
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1188
1
        return -1;
1189
1
    }
1190
1191
8
    instance.set_recycle_state(target_state);
1192
8
    instance.set_recycle_state_update_time_ms(
1193
8
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1194
8
    if (!instance.SerializeToString(&value)) {
1195
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1196
0
                .tag("instance_id", instance_id_)
1197
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1198
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1199
0
        return -1;
1200
0
    }
1201
1202
8
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1203
8
    txn->put(key, value);
1204
8
    err = txn->commit();
1205
8
    if (err != TxnErrorCode::TXN_OK) {
1206
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1207
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1208
0
        return -1;
1209
0
    }
1210
1211
8
    instance_info_.Swap(&instance);
1212
8
    LOG_INFO("updated instance recycled state")
1213
8
            .tag("instance_id", instance_id_)
1214
8
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1215
8
    return 0;
1216
8
}
1217
1218
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1219
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1220
9
    if (exists == nullptr) {
1221
0
        return -1;
1222
0
    }
1223
9
    *exists = false;
1224
1225
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1226
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1227
9
    std::string scan_begin = begin;
1228
1229
9
    while (true) {
1230
9
        std::unique_ptr<RangeGetIterator> it_range;
1231
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1232
9
        if (get_ret < 0) {
1233
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1234
0
                    .tag("instance_id", instance_id_)
1235
0
                    .tag("tablet_id", tablet_id)
1236
0
                    .tag("ret", get_ret);
1237
0
            return -1;
1238
0
        }
1239
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1240
6
            return 0;
1241
6
        }
1242
1243
3
        std::string last_key;
1244
3
        while (it_range->has_next()) {
1245
3
            auto [k, v] = it_range->next();
1246
3
            last_key.assign(k.data(), k.size());
1247
3
            doris::RowsetMetaCloudPB rowset_meta;
1248
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1249
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1250
0
                        .tag("instance_id", instance_id_)
1251
0
                        .tag("tablet_id", tablet_id)
1252
0
                        .tag("key", hex(k));
1253
0
                continue;
1254
0
            }
1255
3
            if (stats) {
1256
3
                ++stats->rowset_scan_count;
1257
3
            }
1258
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1259
3
                *exists = true;
1260
3
                return 0;
1261
3
            }
1262
3
        }
1263
1264
0
        if (!it_range->more()) {
1265
0
            return 0;
1266
0
        }
1267
1268
        // Continue scanning from the next key to keep each transaction short.
1269
0
        scan_begin = std::move(last_key);
1270
0
        scan_begin.push_back('\x00');
1271
0
    }
1272
9
}
1273
1274
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1275
                                                          const std::string& rowset_id,
1276
                                                          int64_t txn_id, bool* recycle_exists,
1277
11
                                                          bool* tmp_exists) {
1278
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1279
0
        return -1;
1280
0
    }
1281
11
    *recycle_exists = false;
1282
11
    *tmp_exists = false;
1283
1284
11
    if (txn_id <= 0) {
1285
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1286
0
                .tag("instance_id", instance_id_)
1287
0
                .tag("tablet_id", tablet_id)
1288
0
                .tag("rowset_id", rowset_id)
1289
0
                .tag("txn_id", txn_id);
1290
0
        return -1;
1291
0
    }
1292
1293
11
    std::unique_ptr<Transaction> txn;
1294
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1295
11
    if (err != TxnErrorCode::TXN_OK) {
1296
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1297
0
                .tag("instance_id", instance_id_)
1298
0
                .tag("tablet_id", tablet_id)
1299
0
                .tag("rowset_id", rowset_id)
1300
0
                .tag("txn_id", txn_id)
1301
0
                .tag("err", err);
1302
0
        return -1;
1303
0
    }
1304
1305
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1306
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1307
11
    if (ret == TxnErrorCode::TXN_OK) {
1308
1
        *recycle_exists = true;
1309
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1310
0
        LOG_WARNING("failed to check recycle rowset existence")
1311
0
                .tag("instance_id", instance_id_)
1312
0
                .tag("tablet_id", tablet_id)
1313
0
                .tag("rowset_id", rowset_id)
1314
0
                .tag("key", hex(recycle_key))
1315
0
                .tag("err", ret);
1316
0
        return -1;
1317
0
    }
1318
1319
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1320
11
    ret = key_exists(txn.get(), tmp_key, true);
1321
11
    if (ret == TxnErrorCode::TXN_OK) {
1322
1
        *tmp_exists = true;
1323
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1324
0
        LOG_WARNING("failed to check tmp rowset existence")
1325
0
                .tag("instance_id", instance_id_)
1326
0
                .tag("tablet_id", tablet_id)
1327
0
                .tag("txn_id", txn_id)
1328
0
                .tag("key", hex(tmp_key))
1329
0
                .tag("err", ret);
1330
0
        return -1;
1331
0
    }
1332
1333
11
    return 0;
1334
11
}
1335
1336
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1337
8
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1338
8
    if (!hint.empty()) {
1339
8
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1340
8
            return {hint, it->second};
1341
8
        }
1342
8
    }
1343
1344
0
    return {"", nullptr};
1345
8
}
1346
1347
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1348
                                               const std::string& packed_file_path,
1349
3
                                               PackedFileRecycleStats* stats) {
1350
3
    bool local_changed = false;
1351
3
    int64_t left_num = 0;
1352
3
    int64_t left_bytes = 0;
1353
3
    bool all_small_files_confirmed = true;
1354
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1355
1356
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1357
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1358
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1359
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1360
14
        LOG_INFO("packed slice correction status")
1361
14
                .tag("instance_id", instance_id_)
1362
14
                .tag("packed_file_path", packed_file_path)
1363
14
                .tag("small_file_path", file.path())
1364
14
                .tag("tablet_id", tablet_id)
1365
14
                .tag("rowset_id", rowset_id)
1366
14
                .tag("txn_id", txn_id)
1367
14
                .tag("size", file.size())
1368
14
                .tag("deleted", file.deleted())
1369
14
                .tag("corrected", file.corrected())
1370
14
                .tag("confirmed_this_round", confirmed_this_round);
1371
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
1356
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1357
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1358
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1359
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1360
14
        LOG_INFO("packed slice correction status")
1361
14
                .tag("instance_id", instance_id_)
1362
14
                .tag("packed_file_path", packed_file_path)
1363
14
                .tag("small_file_path", file.path())
1364
14
                .tag("tablet_id", tablet_id)
1365
14
                .tag("rowset_id", rowset_id)
1366
14
                .tag("txn_id", txn_id)
1367
14
                .tag("size", file.size())
1368
14
                .tag("deleted", file.deleted())
1369
14
                .tag("corrected", file.corrected())
1370
14
                .tag("confirmed_this_round", confirmed_this_round);
1371
14
    };
1372
1373
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1374
14
        auto* small_file = packed_info->mutable_slices(i);
1375
14
        if (small_file->deleted()) {
1376
3
            log_small_file_status(*small_file, small_file->corrected());
1377
3
            continue;
1378
3
        }
1379
1380
11
        if (small_file->corrected()) {
1381
0
            left_num++;
1382
0
            left_bytes += small_file->size();
1383
0
            log_small_file_status(*small_file, true);
1384
0
            continue;
1385
0
        }
1386
1387
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1388
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1389
0
                    .tag("instance_id", instance_id_)
1390
0
                    .tag("small_file_path", small_file->path())
1391
0
                    .tag("index", i);
1392
0
            return -1;
1393
0
        }
1394
1395
11
        int64_t tablet_id = small_file->tablet_id();
1396
11
        const std::string& rowset_id = small_file->rowset_id();
1397
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1398
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1399
0
                    .tag("instance_id", instance_id_)
1400
0
                    .tag("small_file_path", small_file->path())
1401
0
                    .tag("index", i)
1402
0
                    .tag("tablet_id", tablet_id)
1403
0
                    .tag("rowset_id", rowset_id)
1404
0
                    .tag("has_txn_id", small_file->has_txn_id())
1405
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1406
0
            return -1;
1407
0
        }
1408
11
        int64_t txn_id = small_file->txn_id();
1409
11
        bool recycle_exists = false;
1410
11
        bool tmp_exists = false;
1411
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1412
11
                                                &tmp_exists) != 0) {
1413
0
            return -1;
1414
0
        }
1415
1416
11
        bool small_file_confirmed = false;
1417
11
        if (tmp_exists) {
1418
1
            left_num++;
1419
1
            left_bytes += small_file->size();
1420
1
            small_file_confirmed = true;
1421
10
        } else if (recycle_exists) {
1422
1
            left_num++;
1423
1
            left_bytes += small_file->size();
1424
            // keep small_file_confirmed=false so the packed file remains uncorrected
1425
9
        } else {
1426
9
            bool rowset_exists = false;
1427
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1428
0
                return -1;
1429
0
            }
1430
1431
9
            if (!rowset_exists) {
1432
6
                if (!small_file->deleted()) {
1433
6
                    small_file->set_deleted(true);
1434
6
                    local_changed = true;
1435
6
                }
1436
6
                if (!small_file->corrected()) {
1437
6
                    small_file->set_corrected(true);
1438
6
                    local_changed = true;
1439
6
                }
1440
6
                small_file_confirmed = true;
1441
6
            } else {
1442
3
                left_num++;
1443
3
                left_bytes += small_file->size();
1444
3
                small_file_confirmed = true;
1445
3
            }
1446
9
        }
1447
1448
11
        if (!small_file_confirmed) {
1449
1
            all_small_files_confirmed = false;
1450
1
        }
1451
1452
11
        if (small_file->corrected() != small_file_confirmed) {
1453
4
            small_file->set_corrected(small_file_confirmed);
1454
4
            local_changed = true;
1455
4
        }
1456
1457
11
        log_small_file_status(*small_file, small_file_confirmed);
1458
11
    }
1459
1460
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1461
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1462
3
        local_changed = true;
1463
3
    }
1464
3
    if (packed_info->ref_cnt() != left_num) {
1465
3
        auto old_ref_cnt = packed_info->ref_cnt();
1466
3
        packed_info->set_ref_cnt(left_num);
1467
3
        LOG_INFO("corrected packed file ref count")
1468
3
                .tag("instance_id", instance_id_)
1469
3
                .tag("resource_id", packed_info->resource_id())
1470
3
                .tag("packed_file_path", packed_file_path)
1471
3
                .tag("old_ref_cnt", old_ref_cnt)
1472
3
                .tag("new_ref_cnt", left_num);
1473
3
        local_changed = true;
1474
3
    }
1475
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1476
2
        packed_info->set_corrected(all_small_files_confirmed);
1477
2
        local_changed = true;
1478
2
    }
1479
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1480
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1481
1
        local_changed = true;
1482
1
    }
1483
1484
3
    if (changed != nullptr) {
1485
3
        *changed = local_changed;
1486
3
    }
1487
3
    return 0;
1488
3
}
1489
1490
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1491
                                                 const std::string& packed_file_path,
1492
4
                                                 PackedFileRecycleStats* stats) {
1493
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1494
4
    bool correction_ok = false;
1495
4
    cloud::PackedFileInfoPB packed_info;
1496
1497
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1498
4
        if (stopped()) {
1499
0
            LOG_WARNING("recycler stopped before processing packed file")
1500
0
                    .tag("instance_id", instance_id_)
1501
0
                    .tag("packed_file_path", packed_file_path)
1502
0
                    .tag("attempt", attempt);
1503
0
            return -1;
1504
0
        }
1505
1506
4
        std::unique_ptr<Transaction> txn;
1507
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1508
4
        if (err != TxnErrorCode::TXN_OK) {
1509
0
            LOG_WARNING("failed to create txn when processing packed file")
1510
0
                    .tag("instance_id", instance_id_)
1511
0
                    .tag("packed_file_path", packed_file_path)
1512
0
                    .tag("attempt", attempt)
1513
0
                    .tag("err", err);
1514
0
            return -1;
1515
0
        }
1516
1517
4
        std::string packed_val;
1518
4
        err = txn->get(packed_key, &packed_val);
1519
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1520
0
            return 0;
1521
0
        }
1522
4
        if (err != TxnErrorCode::TXN_OK) {
1523
0
            LOG_WARNING("failed to get packed file kv")
1524
0
                    .tag("instance_id", instance_id_)
1525
0
                    .tag("packed_file_path", packed_file_path)
1526
0
                    .tag("attempt", attempt)
1527
0
                    .tag("err", err);
1528
0
            return -1;
1529
0
        }
1530
1531
4
        if (!packed_info.ParseFromString(packed_val)) {
1532
0
            LOG_WARNING("failed to parse packed file info")
1533
0
                    .tag("instance_id", instance_id_)
1534
0
                    .tag("packed_file_path", packed_file_path)
1535
0
                    .tag("attempt", attempt);
1536
0
            return -1;
1537
0
        }
1538
1539
4
        int64_t now_sec = ::time(nullptr);
1540
4
        bool corrected = packed_info.corrected();
1541
4
        bool due = config::force_immediate_recycle ||
1542
4
                   now_sec - packed_info.created_at_sec() >=
1543
4
                           config::packed_file_correction_delay_seconds;
1544
1545
4
        if (!corrected && due) {
1546
3
            bool changed = false;
1547
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1548
0
                LOG_WARNING("correct_packed_file_info failed")
1549
0
                        .tag("instance_id", instance_id_)
1550
0
                        .tag("packed_file_path", packed_file_path)
1551
0
                        .tag("attempt", attempt);
1552
0
                return -1;
1553
0
            }
1554
3
            if (changed) {
1555
3
                std::string updated;
1556
3
                if (!packed_info.SerializeToString(&updated)) {
1557
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1558
0
                            .tag("instance_id", instance_id_)
1559
0
                            .tag("packed_file_path", packed_file_path)
1560
0
                            .tag("attempt", attempt);
1561
0
                    return -1;
1562
0
                }
1563
3
                txn->put(packed_key, updated);
1564
3
                err = txn->commit();
1565
3
                if (err == TxnErrorCode::TXN_OK) {
1566
3
                    if (stats) {
1567
3
                        ++stats->num_corrected;
1568
3
                    }
1569
3
                } else {
1570
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1571
0
                        LOG_WARNING(
1572
0
                                "failed to commit correction for packed file due to conflict, "
1573
0
                                "retrying")
1574
0
                                .tag("instance_id", instance_id_)
1575
0
                                .tag("packed_file_path", packed_file_path)
1576
0
                                .tag("attempt", attempt);
1577
0
                        sleep_for_packed_file_retry();
1578
0
                        packed_info.Clear();
1579
0
                        continue;
1580
0
                    }
1581
0
                    LOG_WARNING("failed to commit correction for packed file")
1582
0
                            .tag("instance_id", instance_id_)
1583
0
                            .tag("packed_file_path", packed_file_path)
1584
0
                            .tag("attempt", attempt)
1585
0
                            .tag("err", err);
1586
0
                    return -1;
1587
0
                }
1588
3
            }
1589
3
        }
1590
1591
4
        correction_ok = true;
1592
4
        break;
1593
4
    }
1594
1595
4
    if (!correction_ok) {
1596
0
        return -1;
1597
0
    }
1598
1599
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1600
4
          packed_info.ref_cnt() == 0)) {
1601
3
        return 0;
1602
3
    }
1603
1604
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1605
0
        LOG_WARNING("packed file missing resource id when recycling")
1606
0
                .tag("instance_id", instance_id_)
1607
0
                .tag("packed_file_path", packed_file_path);
1608
0
        return -1;
1609
0
    }
1610
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1611
1
    if (!accessor) {
1612
0
        LOG_WARNING("no accessor available to delete packed file")
1613
0
                .tag("instance_id", instance_id_)
1614
0
                .tag("packed_file_path", packed_file_path)
1615
0
                .tag("resource_id", packed_info.resource_id());
1616
0
        return -1;
1617
0
    }
1618
1
    int del_ret = accessor->delete_file(packed_file_path);
1619
1
    if (del_ret != 0 && del_ret != 1) {
1620
0
        LOG_WARNING("failed to delete packed file")
1621
0
                .tag("instance_id", instance_id_)
1622
0
                .tag("packed_file_path", packed_file_path)
1623
0
                .tag("resource_id", resource_id)
1624
0
                .tag("ret", del_ret);
1625
0
        return -1;
1626
0
    }
1627
1
    if (del_ret == 1) {
1628
0
        LOG_INFO("packed file already removed")
1629
0
                .tag("instance_id", instance_id_)
1630
0
                .tag("packed_file_path", packed_file_path)
1631
0
                .tag("resource_id", resource_id);
1632
1
    } else {
1633
1
        LOG_INFO("deleted packed file")
1634
1
                .tag("instance_id", instance_id_)
1635
1
                .tag("packed_file_path", packed_file_path)
1636
1
                .tag("resource_id", resource_id);
1637
1
    }
1638
1639
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1640
1
        std::unique_ptr<Transaction> del_txn;
1641
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1642
1
        if (err != TxnErrorCode::TXN_OK) {
1643
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1644
0
                    .tag("instance_id", instance_id_)
1645
0
                    .tag("packed_file_path", packed_file_path)
1646
0
                    .tag("del_attempt", del_attempt)
1647
0
                    .tag("err", err);
1648
0
            return -1;
1649
0
        }
1650
1651
1
        std::string latest_val;
1652
1
        err = del_txn->get(packed_key, &latest_val);
1653
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1654
0
            return 0;
1655
0
        }
1656
1
        if (err != TxnErrorCode::TXN_OK) {
1657
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1658
0
                    .tag("instance_id", instance_id_)
1659
0
                    .tag("packed_file_path", packed_file_path)
1660
0
                    .tag("del_attempt", del_attempt)
1661
0
                    .tag("err", err);
1662
0
            return -1;
1663
0
        }
1664
1665
1
        cloud::PackedFileInfoPB latest_info;
1666
1
        if (!latest_info.ParseFromString(latest_val)) {
1667
0
            LOG_WARNING("failed to parse packed file info before removal")
1668
0
                    .tag("instance_id", instance_id_)
1669
0
                    .tag("packed_file_path", packed_file_path)
1670
0
                    .tag("del_attempt", del_attempt);
1671
0
            return -1;
1672
0
        }
1673
1674
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1675
1
              latest_info.ref_cnt() == 0)) {
1676
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1677
0
                    .tag("instance_id", instance_id_)
1678
0
                    .tag("packed_file_path", packed_file_path)
1679
0
                    .tag("del_attempt", del_attempt);
1680
0
            return 0;
1681
0
        }
1682
1683
1
        del_txn->remove(packed_key);
1684
1
        err = del_txn->commit();
1685
1
        if (err == TxnErrorCode::TXN_OK) {
1686
1
            if (stats) {
1687
1
                ++stats->num_deleted;
1688
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1689
1
                                        static_cast<int64_t>(latest_val.size());
1690
1
                if (del_ret == 0 || del_ret == 1) {
1691
1
                    ++stats->num_object_deleted;
1692
1
                    int64_t object_size = latest_info.total_slice_bytes();
1693
1
                    if (object_size <= 0) {
1694
0
                        object_size = packed_info.total_slice_bytes();
1695
0
                    }
1696
1
                    stats->bytes_object_deleted += object_size;
1697
1
                }
1698
1
            }
1699
1
            LOG_INFO("removed packed file metadata")
1700
1
                    .tag("instance_id", instance_id_)
1701
1
                    .tag("packed_file_path", packed_file_path);
1702
1
            return 0;
1703
1
        }
1704
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1705
0
            if (del_attempt >= max_retry_times) {
1706
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1707
0
                        .tag("instance_id", instance_id_)
1708
0
                        .tag("packed_file_path", packed_file_path)
1709
0
                        .tag("del_attempt", del_attempt);
1710
0
                return -1;
1711
0
            }
1712
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1713
0
                    .tag("instance_id", instance_id_)
1714
0
                    .tag("packed_file_path", packed_file_path)
1715
0
                    .tag("del_attempt", del_attempt);
1716
0
            sleep_for_packed_file_retry();
1717
0
            continue;
1718
0
        }
1719
0
        LOG_WARNING("failed to remove packed file kv")
1720
0
                .tag("instance_id", instance_id_)
1721
0
                .tag("packed_file_path", packed_file_path)
1722
0
                .tag("del_attempt", del_attempt)
1723
0
                .tag("err", err);
1724
0
        return -1;
1725
0
    }
1726
1727
0
    return -1;
1728
1
}
1729
1730
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1731
4
                                            PackedFileRecycleStats* stats, int* ret) {
1732
4
    if (stats) {
1733
4
        ++stats->num_scanned;
1734
4
    }
1735
4
    std::string packed_file_path;
1736
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1737
0
        LOG_WARNING("failed to decode packed file key")
1738
0
                .tag("instance_id", instance_id_)
1739
0
                .tag("key", hex(key));
1740
0
        if (stats) {
1741
0
            ++stats->num_failed;
1742
0
        }
1743
0
        if (ret) {
1744
0
            *ret = -1;
1745
0
        }
1746
0
        return 0;
1747
0
    }
1748
1749
4
    std::string packed_key(key);
1750
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1751
4
    if (process_ret != 0) {
1752
0
        if (stats) {
1753
0
            ++stats->num_failed;
1754
0
        }
1755
0
        if (ret) {
1756
0
            *ret = -1;
1757
0
        }
1758
0
    }
1759
4
    return 0;
1760
4
}
1761
1762
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1763
6.02k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1764
6.02k
    if (config::force_immediate_recycle) {
1765
15
        return 0L;
1766
15
    }
1767
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1768
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1769
6.00k
    int64_t retention_seconds = config::retention_seconds;
1770
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1771
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1772
4.70k
    }
1773
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1774
6.00k
    if (*earlest_ts > final_expiration) {
1775
5
        *earlest_ts = final_expiration;
1776
5
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1777
5
    }
1778
6.00k
    return final_expiration;
1779
6.02k
}
1780
1781
int64_t calculate_partition_expired_time(
1782
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1783
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1784
9
    if (config::force_immediate_recycle) {
1785
3
        return 0L;
1786
3
    }
1787
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1788
6
                                                            : partition_meta_pb.creation_time();
1789
6
    int64_t retention_seconds = config::retention_seconds;
1790
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1791
6
        retention_seconds =
1792
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1793
6
    }
1794
6
    int64_t final_expiration = expiration + retention_seconds;
1795
6
    if (*earlest_ts > final_expiration) {
1796
2
        *earlest_ts = final_expiration;
1797
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1798
2
    }
1799
6
    return final_expiration;
1800
9
}
1801
1802
int64_t calculate_index_expired_time(const std::string& instance_id_,
1803
                                     const RecycleIndexPB& index_meta_pb,
1804
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1805
10
    if (config::force_immediate_recycle) {
1806
4
        return 0L;
1807
4
    }
1808
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1809
6
                                                        : index_meta_pb.creation_time();
1810
6
    int64_t retention_seconds = config::retention_seconds;
1811
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1812
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1813
6
    }
1814
6
    int64_t final_expiration = expiration + retention_seconds;
1815
6
    if (*earlest_ts > final_expiration) {
1816
2
        *earlest_ts = final_expiration;
1817
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1818
2
    }
1819
6
    return final_expiration;
1820
10
}
1821
1822
int64_t calculate_tmp_rowset_expired_time(
1823
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1824
53.0k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1825
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1826
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1827
    //  duration or timeout always < `retention_time` in practice.
1828
53.0k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1829
53.0k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1830
53.0k
                                 : tmp_rowset_meta_pb.creation_time();
1831
53.0k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1832
53.0k
    int64_t final_expiration = expiration + config::retention_seconds;
1833
53.0k
    if (*earlest_ts > final_expiration) {
1834
18
        *earlest_ts = final_expiration;
1835
18
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1836
18
    }
1837
53.0k
    return final_expiration;
1838
53.0k
}
1839
1840
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1841
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1842
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1843
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1844
8
        *earlest_ts = final_expiration / 1000;
1845
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1846
8
    }
1847
30.0k
    return final_expiration;
1848
30.0k
}
1849
1850
int64_t calculate_restore_job_expired_time(
1851
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1852
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1853
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1854
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1855
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1856
        // final state, recycle immediately
1857
41
        return 0L;
1858
41
    }
1859
    // not final state, wait much longer than the FE's timeout(1 day)
1860
0
    int64_t last_modified_s =
1861
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1862
0
    int64_t expiration = restore_job.expired_at_s() > 0
1863
0
                                 ? last_modified_s + restore_job.expired_at_s()
1864
0
                                 : last_modified_s;
1865
0
    int64_t final_expiration = expiration + config::retention_seconds;
1866
0
    if (*earlest_ts > final_expiration) {
1867
0
        *earlest_ts = final_expiration;
1868
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1869
0
    }
1870
0
    return final_expiration;
1871
41
}
1872
1873
int get_meta_rowset_key(Transaction* txn, const std::string& instance_id, int64_t tablet_id,
1874
                        const std::string& rowset_id, int64_t start_version, int64_t end_version,
1875
0
                        bool load_key, bool* exist) {
1876
0
    std::string key =
1877
0
            load_key ? versioned::meta_rowset_load_key({instance_id, tablet_id, end_version})
1878
0
                     : versioned::meta_rowset_compact_key({instance_id, tablet_id, end_version});
1879
0
    RowsetMetaCloudPB rowset_meta;
1880
0
    Versionstamp version;
1881
0
    TxnErrorCode err = versioned::document_get(txn, key, &rowset_meta, &version);
1882
0
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1883
0
        VLOG_DEBUG << "not found load or compact meta_rowset_key."
1884
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1885
0
                   << " end_version=" << end_version << " key=" << hex(key);
1886
0
    } else if (err != TxnErrorCode::TXN_OK) {
1887
0
        LOG_INFO("failed to get load or compact meta_rowset_key.")
1888
0
                .tag("rowset_id", rowset_id)
1889
0
                .tag("start_version", start_version)
1890
0
                .tag("end_version", end_version)
1891
0
                .tag("key", hex(key))
1892
0
                .tag("error_code", err);
1893
0
        return -1;
1894
0
    } else if (rowset_meta.rowset_id_v2() == rowset_id) {
1895
0
        *exist = true;
1896
0
        VLOG_DEBUG << "found load or compact meta_rowset_key."
1897
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1898
0
                   << " end_version=" << end_version << " key=" << hex(key);
1899
0
    } else {
1900
0
        VLOG_DEBUG << "rowset_id does not match when find load or compact meta_rowset_key."
1901
0
                   << " rowset_id=" << rowset_id << " start_version=" << start_version
1902
0
                   << " end_version=" << end_version << " key=" << hex(key)
1903
0
                   << " found_rowset_id=" << rowset_meta.rowset_id_v2();
1904
0
    }
1905
0
    return 0;
1906
0
}
1907
1908
2
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1909
2
    AbortTxnRequest req;
1910
2
    TxnInfoPB txn_info;
1911
2
    MetaServiceCode code = MetaServiceCode::OK;
1912
2
    std::string msg;
1913
2
    std::stringstream ss;
1914
2
    std::unique_ptr<Transaction> txn;
1915
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1916
2
    if (err != TxnErrorCode::TXN_OK) {
1917
0
        LOG_WARNING("failed to create txn").tag("err", err);
1918
0
        return -1;
1919
0
    }
1920
1921
    // get txn index
1922
2
    TxnIndexPB txn_idx_pb;
1923
2
    auto index_key = txn_index_key({instance_id_, txn_id});
1924
2
    std::string index_val;
1925
2
    err = txn->get(index_key, &index_val);
1926
2
    if (err != TxnErrorCode::TXN_OK) {
1927
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1928
            // maybe recycled
1929
0
            LOG_INFO("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1930
0
                    .tag("key", hex(index_key))
1931
0
                    .tag("txn_id", txn_id);
1932
0
            return 0;
1933
0
        }
1934
0
        LOG_WARNING("failed to get txn index")
1935
0
                .tag("err", err)
1936
0
                .tag("key", hex(index_key))
1937
0
                .tag("txn_id", txn_id);
1938
0
        return -1;
1939
0
    }
1940
2
    if (!txn_idx_pb.ParseFromString(index_val)) {
1941
0
        LOG_WARNING("failed to parse txn index")
1942
0
                .tag("err", err)
1943
0
                .tag("key", hex(index_key))
1944
0
                .tag("txn_id", txn_id);
1945
0
        return -1;
1946
0
    }
1947
1948
2
    auto info_key = txn_info_key({instance_id_, txn_idx_pb.tablet_index().db_id(), txn_id});
1949
2
    std::string info_val;
1950
2
    err = txn->get(info_key, &info_val);
1951
2
    if (err != TxnErrorCode::TXN_OK) {
1952
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1953
            // maybe recycled
1954
0
            LOG_INFO("txn info not found, txn_id={} instance_id={}", txn_id, instance_id_)
1955
0
                    .tag("key", hex(info_key))
1956
0
                    .tag("txn_id", txn_id);
1957
0
            return 0;
1958
0
        }
1959
0
        LOG_WARNING("failed to get txn info")
1960
0
                .tag("err", err)
1961
0
                .tag("key", hex(info_key))
1962
0
                .tag("txn_id", txn_id);
1963
0
        return -1;
1964
0
    }
1965
2
    if (!txn_info.ParseFromString(info_val)) {
1966
0
        LOG_WARNING("failed to parse txn info")
1967
0
                .tag("err", err)
1968
0
                .tag("key", hex(info_key))
1969
0
                .tag("txn_id", txn_id);
1970
0
        return -1;
1971
0
    }
1972
1973
2
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
1974
0
        LOG_INFO("txn is not prepared status, txn_id={} status={}", txn_id, txn_info.status())
1975
0
                .tag("key", hex(info_key))
1976
0
                .tag("txn_id", txn_id);
1977
0
        return 0;
1978
0
    }
1979
1980
2
    req.set_txn_id(txn_id);
1981
1982
2
    LOG(INFO) << "begin abort txn for related rowset, txn_id=" << txn_id
1983
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString();
1984
1985
2
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
1986
2
    err = txn->commit();
1987
2
    if (err != TxnErrorCode::TXN_OK) {
1988
0
        code = cast_as<ErrCategory::COMMIT>(err);
1989
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
1990
0
        msg = ss.str();
1991
0
        return -1;
1992
0
    }
1993
1994
2
    LOG(INFO) << "finish abort txn for related rowset, txn_id=" << txn_id
1995
2
              << " instance_id=" << instance_id_ << " txn_info=" << txn_info.ShortDebugString()
1996
2
              << " code=" << code << " msg=" << msg;
1997
1998
2
    return 0;
1999
2
}
2000
2001
4
int InstanceRecycler::abort_job_for_related_rowset(const RowsetMetaCloudPB& rowset_meta) {
2002
4
    FinishTabletJobRequest req;
2003
4
    FinishTabletJobResponse res;
2004
4
    req.set_action(FinishTabletJobRequest::ABORT);
2005
4
    MetaServiceCode code = MetaServiceCode::OK;
2006
4
    std::string msg;
2007
4
    std::stringstream ss;
2008
2009
4
    TabletIndexPB tablet_idx;
2010
4
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, rowset_meta.tablet_id(), tablet_idx);
2011
4
    if (ret == 1) {
2012
        // tablet maybe recycled, directly return 0
2013
1
        return 0;
2014
3
    } else if (ret != 0) {
2015
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << rowset_meta.tablet_id()
2016
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2017
0
        return ret;
2018
0
    }
2019
2020
3
    std::unique_ptr<Transaction> txn;
2021
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2022
3
    if (err != TxnErrorCode::TXN_OK) {
2023
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2024
0
        return -1;
2025
0
    }
2026
2027
3
    std::string job_key =
2028
3
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2029
3
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2030
3
    std::string job_val;
2031
3
    err = txn->get(job_key, &job_val);
2032
3
    if (err != TxnErrorCode::TXN_OK) {
2033
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2034
0
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2035
0
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2036
0
            return 0;
2037
0
        }
2038
0
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2039
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2040
0
                     << " key=" << hex(job_key);
2041
0
        return -1;
2042
0
    }
2043
2044
3
    TabletJobInfoPB job_pb;
2045
3
    if (!job_pb.ParseFromString(job_val)) {
2046
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2047
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2048
0
        return -1;
2049
0
    }
2050
2051
3
    std::string job_id {};
2052
3
    if (!job_pb.compaction().empty()) {
2053
2
        for (const auto& c : job_pb.compaction()) {
2054
2
            if (c.id() == rowset_meta.job_id()) {
2055
2
                job_id = c.id();
2056
2
                break;
2057
2
            }
2058
2
        }
2059
2
    } else if (job_pb.has_schema_change()) {
2060
1
        job_id = job_pb.schema_change().id();
2061
1
    }
2062
2063
3
    if (!job_id.empty() && rowset_meta.job_id() == job_id) {
2064
3
        LOG(INFO) << "begin to abort job for related rowset, job_id=" << rowset_meta.job_id()
2065
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2066
3
        req.mutable_job()->CopyFrom(job_pb);
2067
3
        req.set_action(FinishTabletJobRequest::ABORT);
2068
3
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2069
3
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2070
3
                           ss);
2071
3
        if (code != MetaServiceCode::OK) {
2072
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2073
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2074
0
                         << " msg=" << msg;
2075
0
            return -1;
2076
0
        }
2077
3
        LOG(INFO) << "finish abort job for related rowset, job_id=" << rowset_meta.job_id()
2078
3
                  << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2079
3
                  << " code=" << code << " msg=" << msg;
2080
3
    } else {
2081
        // clang-format off
2082
0
        LOG(INFO) << "there is no job for related rowset, directly recycle rowset data"
2083
0
                  << ", instance_id=" << instance_id_ 
2084
0
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2085
0
                  << ", job_id=" << job_id
2086
0
                  << ", rowset_id=" << rowset_meta.rowset_id_v2();
2087
        // clang-format on
2088
0
    }
2089
2090
3
    return 0;
2091
3
}
2092
2093
template <typename T>
2094
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2095
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2096
9
        return rowset_meta_pb.mutable_rowset_meta();
2097
9
    } else {
2098
9
        return &rowset_meta_pb;
2099
9
    }
2100
13
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2094
4
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2095
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2096
4
        return rowset_meta_pb.mutable_rowset_meta();
2097
4
    } else {
2098
4
        return &rowset_meta_pb;
2099
4
    }
2100
4
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2094
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2095
9
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2096
9
        return rowset_meta_pb.mutable_rowset_meta();
2097
9
    } else {
2098
9
        return &rowset_meta_pb;
2099
9
    }
2100
9
}
2101
2102
template <typename T>
2103
51
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2104
51
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2105
35
        return rowset_meta_pb.rowset_meta();
2106
35
    } else {
2107
35
        return rowset_meta_pb;
2108
35
    }
2109
51
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2103
16
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2104
16
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2105
16
        return rowset_meta_pb.rowset_meta();
2106
16
    } else {
2107
16
        return rowset_meta_pb;
2108
16
    }
2109
16
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2103
35
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2104
35
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2105
35
        return rowset_meta_pb.rowset_meta();
2106
35
    } else {
2107
35
        return rowset_meta_pb;
2108
35
    }
2109
35
}
2110
2111
struct DeferredRecycleAbortTask {
2112
    enum class Type : uint8_t {
2113
        TXN,
2114
        JOB,
2115
    };
2116
2117
    Type type = Type::TXN;
2118
    int64_t txn_id = 0;
2119
    int64_t tablet_id = 0;
2120
    int64_t start_version = 0;
2121
    int64_t end_version = 0;
2122
    std::string rowset_id;
2123
    std::string job_id;
2124
};
2125
2126
struct DeferredRecyclePrepareDeleteTask {
2127
    std::string key;
2128
    std::string resource_id;
2129
    std::string rowset_id;
2130
    int64_t tablet_id = 0;
2131
};
2132
2133
template <typename T>
2134
14
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2135
14
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2136
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2137
0
            return std::nullopt;
2138
0
        }
2139
4
    }
2140
2141
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2142
4
    DeferredRecycleAbortTask task;
2143
4
    task.tablet_id = rs_meta.tablet_id();
2144
4
    task.start_version = rs_meta.start_version();
2145
4
    task.end_version = rs_meta.end_version();
2146
14
    if (rs_meta.has_load_id()) {
2147
4
        task.type = DeferredRecycleAbortTask::Type::TXN;
2148
4
        task.txn_id = rs_meta.txn_id();
2149
4
        return task;
2150
4
    }
2151
10
    if (rs_meta.has_job_id()) {
2152
6
        task.type = DeferredRecycleAbortTask::Type::JOB;
2153
6
        task.rowset_id = rs_meta.rowset_id_v2();
2154
6
        task.job_id = rs_meta.job_id();
2155
6
        return task;
2156
6
    }
2157
4
    return std::nullopt;
2158
10
}
_ZN5doris5cloud24make_deferred_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2134
4
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2135
4
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2136
4
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2137
0
            return std::nullopt;
2138
0
        }
2139
4
    }
2140
2141
4
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2142
4
    DeferredRecycleAbortTask task;
2143
4
    task.tablet_id = rs_meta.tablet_id();
2144
4
    task.start_version = rs_meta.start_version();
2145
4
    task.end_version = rs_meta.end_version();
2146
4
    if (rs_meta.has_load_id()) {
2147
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2148
2
        task.txn_id = rs_meta.txn_id();
2149
2
        return task;
2150
2
    }
2151
2
    if (rs_meta.has_job_id()) {
2152
2
        task.type = DeferredRecycleAbortTask::Type::JOB;
2153
2
        task.rowset_id = rs_meta.rowset_id_v2();
2154
2
        task.job_id = rs_meta.job_id();
2155
2
        return task;
2156
2
    }
2157
0
    return std::nullopt;
2158
2
}
_ZN5doris5cloud24make_deferred_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24DeferredRecycleAbortTaskEERKT_
Line
Count
Source
2134
10
std::optional<DeferredRecycleAbortTask> make_deferred_abort_task(const T& rowset_meta_pb) {
2135
10
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2136
10
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2137
10
            return std::nullopt;
2138
10
        }
2139
10
    }
2140
2141
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2142
10
    DeferredRecycleAbortTask task;
2143
10
    task.tablet_id = rs_meta.tablet_id();
2144
10
    task.start_version = rs_meta.start_version();
2145
10
    task.end_version = rs_meta.end_version();
2146
10
    if (rs_meta.has_load_id()) {
2147
2
        task.type = DeferredRecycleAbortTask::Type::TXN;
2148
2
        task.txn_id = rs_meta.txn_id();
2149
2
        return task;
2150
2
    }
2151
8
    if (rs_meta.has_job_id()) {
2152
4
        task.type = DeferredRecycleAbortTask::Type::JOB;
2153
4
        task.rowset_id = rs_meta.rowset_id_v2();
2154
4
        task.job_id = rs_meta.job_id();
2155
4
        return task;
2156
4
    }
2157
4
    return std::nullopt;
2158
8
}
2159
2160
template <typename T>
2161
35
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2162
35
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2163
35
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2164
35
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS0_15RecycleRowsetPBEEEbRKT_
Line
Count
Source
2161
10
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2162
10
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2163
10
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2164
10
}
_ZN5doris5cloud28need_mark_rowset_as_recycledINS_17RowsetMetaCloudPBEEEbRKT_
Line
Count
Source
2161
25
bool need_mark_rowset_as_recycled(const T& rowset_meta_pb) {
2162
25
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2163
25
    return !rs_meta.has_is_recycled() || !rs_meta.is_recycled();
2164
25
}
2165
2166
template <typename T>
2167
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2168
11
                                   const std::vector<std::string>& keys) {
2169
11
    std::unique_ptr<Transaction> txn;
2170
11
    TxnErrorCode err = txn_kv->create_txn(&txn);
2171
11
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2173
0
        return -1;
2174
0
    }
2175
11
    std::vector<std::optional<std::string>> values;
2176
11
    err = txn->batch_get(&values, keys);
2177
11
    if (err != TxnErrorCode::TXN_OK) {
2178
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2179
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2180
0
        return -1;
2181
0
    }
2182
11
    size_t total_keys = keys.size();
2183
24
    for (size_t i = 0; i < total_keys; i++) {
2184
13
        if (!values[i].has_value()) {
2185
            // has already been removed by commit_rowset
2186
0
            continue;
2187
0
        }
2188
13
        auto key = keys[i];
2189
13
        auto val = values[i].value();
2190
13
        T rowset_meta_pb;
2191
13
        if (!rowset_meta_pb.ParseFromString(val)) {
2192
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2193
0
                         << " key=" << hex(key);
2194
0
            return -1;
2195
0
        }
2196
13
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2197
0
            continue;
2198
0
        }
2199
13
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2200
13
        val.clear();
2201
13
        rowset_meta_pb.SerializeToString(&val);
2202
13
        txn->put(key, val);
2203
13
    }
2204
11
    err = txn->commit();
2205
11
    if (err != TxnErrorCode::TXN_OK) {
2206
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2207
0
        return -1;
2208
0
    }
2209
2210
11
    return 0;
2211
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2168
4
                                   const std::vector<std::string>& keys) {
2169
4
    std::unique_ptr<Transaction> txn;
2170
4
    TxnErrorCode err = txn_kv->create_txn(&txn);
2171
4
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2173
0
        return -1;
2174
0
    }
2175
4
    std::vector<std::optional<std::string>> values;
2176
4
    err = txn->batch_get(&values, keys);
2177
4
    if (err != TxnErrorCode::TXN_OK) {
2178
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2179
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2180
0
        return -1;
2181
0
    }
2182
4
    size_t total_keys = keys.size();
2183
8
    for (size_t i = 0; i < total_keys; i++) {
2184
4
        if (!values[i].has_value()) {
2185
            // has already been removed by commit_rowset
2186
0
            continue;
2187
0
        }
2188
4
        auto key = keys[i];
2189
4
        auto val = values[i].value();
2190
4
        T rowset_meta_pb;
2191
4
        if (!rowset_meta_pb.ParseFromString(val)) {
2192
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2193
0
                         << " key=" << hex(key);
2194
0
            return -1;
2195
0
        }
2196
4
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2197
0
            continue;
2198
0
        }
2199
4
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2200
4
        val.clear();
2201
4
        rowset_meta_pb.SerializeToString(&val);
2202
4
        txn->put(key, val);
2203
4
    }
2204
4
    err = txn->commit();
2205
4
    if (err != TxnErrorCode::TXN_OK) {
2206
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2207
0
        return -1;
2208
0
    }
2209
2210
4
    return 0;
2211
4
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2168
7
                                   const std::vector<std::string>& keys) {
2169
7
    std::unique_ptr<Transaction> txn;
2170
7
    TxnErrorCode err = txn_kv->create_txn(&txn);
2171
7
    if (err != TxnErrorCode::TXN_OK) {
2172
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2173
0
        return -1;
2174
0
    }
2175
7
    std::vector<std::optional<std::string>> values;
2176
7
    err = txn->batch_get(&values, keys);
2177
7
    if (err != TxnErrorCode::TXN_OK) {
2178
0
        LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2179
0
                     << "keys size=" << keys.size() << ' ' << "err=" << err;
2180
0
        return -1;
2181
0
    }
2182
7
    size_t total_keys = keys.size();
2183
16
    for (size_t i = 0; i < total_keys; i++) {
2184
9
        if (!values[i].has_value()) {
2185
            // has already been removed by commit_rowset
2186
0
            continue;
2187
0
        }
2188
9
        auto key = keys[i];
2189
9
        auto val = values[i].value();
2190
9
        T rowset_meta_pb;
2191
9
        if (!rowset_meta_pb.ParseFromString(val)) {
2192
0
            LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2193
0
                         << " key=" << hex(key);
2194
0
            return -1;
2195
0
        }
2196
9
        if (!need_mark_rowset_as_recycled(rowset_meta_pb)) {
2197
0
            continue;
2198
0
        }
2199
9
        mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2200
9
        val.clear();
2201
9
        rowset_meta_pb.SerializeToString(&val);
2202
9
        txn->put(key, val);
2203
9
    }
2204
7
    err = txn->commit();
2205
7
    if (err != TxnErrorCode::TXN_OK) {
2206
0
        LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2207
0
        return -1;
2208
0
    }
2209
2210
7
    return 0;
2211
7
}
2212
2213
template <typename T>
2214
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2215
                                 const std::vector<std::string>& keys,
2216
                                 std::vector<DeferredRecycleAbortTask>* abort_tasks,
2217
5
                                 bool skip_base_version) {
2218
5
    constexpr size_t kAbortCheckBatchSize = 256;
2219
10
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2220
5
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2221
5
        std::unique_ptr<Transaction> txn;
2222
5
        TxnErrorCode err = txn_kv->create_txn(&txn);
2223
5
        if (err != TxnErrorCode::TXN_OK) {
2224
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2225
0
            return -1;
2226
0
        }
2227
10
        for (size_t idx = offset; idx < limit; ++idx) {
2228
5
            const std::string& key = keys[idx];
2229
5
            std::string val;
2230
5
            err = txn->get(key, &val);
2231
5
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2232
                // has already been removed
2233
0
                continue;
2234
0
            }
2235
5
            if (err != TxnErrorCode::TXN_OK) {
2236
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
5
            T rowset_meta_pb;
2241
5
            if (!rowset_meta_pb.ParseFromString(val)) {
2242
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2243
0
                             << " key=" << hex(key);
2244
0
                return -1;
2245
0
            }
2246
5
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2247
0
                continue;
2248
0
            }
2249
5
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2250
5
                abort_task.has_value()) {
2251
5
                abort_tasks->emplace_back(std::move(*abort_task));
2252
5
            }
2253
5
        }
2254
5
    }
2255
5
    return 0;
2256
5
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2217
2
                                 bool skip_base_version) {
2218
2
    constexpr size_t kAbortCheckBatchSize = 256;
2219
4
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2220
2
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2221
2
        std::unique_ptr<Transaction> txn;
2222
2
        TxnErrorCode err = txn_kv->create_txn(&txn);
2223
2
        if (err != TxnErrorCode::TXN_OK) {
2224
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2225
0
            return -1;
2226
0
        }
2227
4
        for (size_t idx = offset; idx < limit; ++idx) {
2228
2
            const std::string& key = keys[idx];
2229
2
            std::string val;
2230
2
            err = txn->get(key, &val);
2231
2
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2232
                // has already been removed
2233
0
                continue;
2234
0
            }
2235
2
            if (err != TxnErrorCode::TXN_OK) {
2236
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
2
            T rowset_meta_pb;
2241
2
            if (!rowset_meta_pb.ParseFromString(val)) {
2242
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2243
0
                             << " key=" << hex(key);
2244
0
                return -1;
2245
0
            }
2246
2
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2247
0
                continue;
2248
0
            }
2249
2
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2250
2
                abort_task.has_value()) {
2251
2
                abort_tasks->emplace_back(std::move(*abort_task));
2252
2
            }
2253
2
        }
2254
2
    }
2255
2
    return 0;
2256
2
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24DeferredRecycleAbortTaskESaISI_EEb
Line
Count
Source
2217
3
                                 bool skip_base_version) {
2218
3
    constexpr size_t kAbortCheckBatchSize = 256;
2219
6
    for (size_t offset = 0; offset < keys.size(); offset += kAbortCheckBatchSize) {
2220
3
        size_t limit = std::min(keys.size(), offset + kAbortCheckBatchSize);
2221
3
        std::unique_ptr<Transaction> txn;
2222
3
        TxnErrorCode err = txn_kv->create_txn(&txn);
2223
3
        if (err != TxnErrorCode::TXN_OK) {
2224
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2225
0
            return -1;
2226
0
        }
2227
6
        for (size_t idx = offset; idx < limit; ++idx) {
2228
3
            const std::string& key = keys[idx];
2229
3
            std::string val;
2230
3
            err = txn->get(key, &val);
2231
3
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2232
                // has already been removed
2233
0
                continue;
2234
0
            }
2235
3
            if (err != TxnErrorCode::TXN_OK) {
2236
0
                LOG(WARNING) << "failed to get rowset meta, instance_id=" << instance_id
2237
0
                             << " key=" << hex(key);
2238
0
                return -1;
2239
0
            }
2240
3
            T rowset_meta_pb;
2241
3
            if (!rowset_meta_pb.ParseFromString(val)) {
2242
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2243
0
                             << " key=" << hex(key);
2244
0
                return -1;
2245
0
            }
2246
3
            if (skip_base_version && rowset_meta(rowset_meta_pb).end_version() == 1) {
2247
0
                continue;
2248
0
            }
2249
3
            if (auto abort_task = make_deferred_abort_task(rowset_meta_pb);
2250
3
                abort_task.has_value()) {
2251
3
                abort_tasks->emplace_back(std::move(*abort_task));
2252
3
            }
2253
3
        }
2254
3
    }
2255
3
    return 0;
2256
3
}
2257
2258
template <typename T>
2259
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(const std::vector<std::string>& keys,
2260
5
                                                         bool skip_base_version) {
2261
5
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2262
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2263
5
                                        skip_base_version) != 0) {
2264
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2265
0
        return -1;
2266
0
    }
2267
5
    for (const auto& abort_task : abort_tasks) {
2268
5
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2269
5
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2270
5
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2271
5
        int abort_ret = 0;
2272
5
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2273
2
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2274
3
        } else {
2275
3
            RowsetMetaCloudPB rowset_meta;
2276
3
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2277
3
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2278
3
            rowset_meta.set_job_id(abort_task.job_id);
2279
3
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2280
3
        }
2281
5
        if (abort_ret != 0) {
2282
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2283
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2284
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2285
0
            return abort_ret;
2286
0
        }
2287
5
    }
2288
5
    return 0;
2289
5
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2260
2
                                                         bool skip_base_version) {
2261
2
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2262
2
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2263
2
                                        skip_base_version) != 0) {
2264
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2265
0
        return -1;
2266
0
    }
2267
2
    for (const auto& abort_task : abort_tasks) {
2268
2
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2269
2
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2270
2
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2271
2
        int abort_ret = 0;
2272
2
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2273
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2274
1
        } else {
2275
1
            RowsetMetaCloudPB rowset_meta;
2276
1
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2277
1
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2278
1
            rowset_meta.set_job_id(abort_task.job_id);
2279
1
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2280
1
        }
2281
2
        if (abort_ret != 0) {
2282
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2283
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2284
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2285
0
            return abort_ret;
2286
0
        }
2287
2
    }
2288
2
    return 0;
2289
2
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEb
Line
Count
Source
2260
3
                                                         bool skip_base_version) {
2261
3
    std::vector<DeferredRecycleAbortTask> abort_tasks;
2262
3
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks,
2263
3
                                        skip_base_version) != 0) {
2264
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2265
0
        return -1;
2266
0
    }
2267
3
    for (const auto& abort_task : abort_tasks) {
2268
3
        LOG(INFO) << "begin to abort txn or job for related rowset, instance_id=" << instance_id_
2269
3
                  << " tablet_id=" << abort_task.tablet_id << " version=["
2270
3
                  << abort_task.start_version << '-' << abort_task.end_version << "]";
2271
3
        int abort_ret = 0;
2272
3
        if (abort_task.type == DeferredRecycleAbortTask::Type::TXN) {
2273
1
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2274
2
        } else {
2275
2
            RowsetMetaCloudPB rowset_meta;
2276
2
            rowset_meta.set_tablet_id(abort_task.tablet_id);
2277
2
            rowset_meta.set_rowset_id_v2(abort_task.rowset_id);
2278
2
            rowset_meta.set_job_id(abort_task.job_id);
2279
2
            abort_ret = abort_job_for_related_rowset(rowset_meta);
2280
2
        }
2281
3
        if (abort_ret != 0) {
2282
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2283
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2284
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2285
0
            return abort_ret;
2286
0
        }
2287
3
    }
2288
3
    return 0;
2289
3
}
2290
2291
int collect_prepare_delete_tasks(TxnKv* txn_kv, const std::string& instance_id,
2292
                                 const std::vector<std::string>& keys,
2293
24
                                 std::vector<DeferredRecyclePrepareDeleteTask>* delete_tasks) {
2294
24
    constexpr size_t kPrepareCheckBatchSize = 256;
2295
48
    for (size_t offset = 0; offset < keys.size(); offset += kPrepareCheckBatchSize) {
2296
24
        size_t limit = std::min(keys.size(), offset + kPrepareCheckBatchSize);
2297
24
        std::unique_ptr<Transaction> txn;
2298
24
        TxnErrorCode err = txn_kv->create_txn(&txn);
2299
24
        if (err != TxnErrorCode::TXN_OK) {
2300
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2301
0
            return -1;
2302
0
        }
2303
677
        for (size_t idx = offset; idx < limit; ++idx) {
2304
653
            const std::string& key = keys[idx];
2305
653
            std::string val;
2306
653
            err = txn->get(key, &val);
2307
653
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2308
                // has already been removed
2309
0
                continue;
2310
0
            }
2311
653
            if (err != TxnErrorCode::TXN_OK) {
2312
0
                LOG(WARNING) << "failed to get recycle rowset, instance_id=" << instance_id
2313
0
                             << " key=" << hex(key);
2314
0
                return -1;
2315
0
            }
2316
653
            RecycleRowsetPB rowset;
2317
653
            if (!rowset.ParseFromString(val)) {
2318
0
                LOG(WARNING) << "failed to parse recycle rowset, instance_id=" << instance_id
2319
0
                             << " key=" << hex(key);
2320
0
                return -1;
2321
0
            }
2322
653
            if (rowset.type() != RecycleRowsetPB::PREPARE) {
2323
0
                continue;
2324
0
            }
2325
653
            const auto& rs_meta = rowset.rowset_meta();
2326
653
            delete_tasks->push_back(
2327
653
                    {key, rs_meta.resource_id(), rs_meta.rowset_id_v2(), rs_meta.tablet_id()});
2328
653
        }
2329
24
    }
2330
24
    return 0;
2331
24
}
2332
2333
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2334
1
    const std::string task_name = "recycle_ref_rowsets";
2335
1
    *has_unrecycled_rowsets = false;
2336
2337
1
    std::string data_rowset_ref_count_key_start =
2338
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2339
1
    std::string data_rowset_ref_count_key_end =
2340
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2341
2342
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2343
2344
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2345
1
    register_recycle_task(task_name, start_time);
2346
2347
1
    DORIS_CLOUD_DEFER {
2348
1
        unregister_recycle_task(task_name);
2349
1
        int64_t cost =
2350
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2351
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2352
1
                .tag("instance_id", instance_id_);
2353
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2347
1
    DORIS_CLOUD_DEFER {
2348
1
        unregister_recycle_task(task_name);
2349
1
        int64_t cost =
2350
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2351
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2352
1
                .tag("instance_id", instance_id_);
2353
1
    };
2354
2355
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2356
1
    std::set<int64_t> tablets_with_refs;
2357
1
    int64_t num_scanned = 0;
2358
2359
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2360
0
        ++num_scanned;
2361
0
        int64_t tablet_id;
2362
0
        std::string rowset_id;
2363
0
        std::string_view key(k);
2364
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2365
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2366
0
            return 0; // Continue scanning
2367
0
        }
2368
2369
0
        tablets_with_refs.insert(tablet_id);
2370
0
        return 0;
2371
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2372
2373
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2374
1
                         std::move(scan_func)) != 0) {
2375
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2376
0
        return -1;
2377
0
    }
2378
2379
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2380
1
             tablets_with_refs.size(), num_scanned)
2381
1
            .tag("instance_id", instance_id_);
2382
2383
    // Phase 2: Recycle each tablet
2384
1
    int64_t num_recycled_tablets = 0;
2385
1
    for (int64_t tablet_id : tablets_with_refs) {
2386
0
        if (stopped()) {
2387
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2388
0
                    .tag("instance_id", instance_id_)
2389
0
                    .tag("tablets_processed", num_recycled_tablets)
2390
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2391
0
            break;
2392
0
        }
2393
2394
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2395
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2396
0
            LOG_WARNING("failed to recycle tablet")
2397
0
                    .tag("instance_id", instance_id_)
2398
0
                    .tag("tablet_id", tablet_id);
2399
0
            return -1;
2400
0
        }
2401
0
        ++num_recycled_tablets;
2402
0
    }
2403
2404
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2405
1
            .tag("instance_id", instance_id_)
2406
1
            .tag("total_tablets", tablets_with_refs.size());
2407
2408
    // Phase 3: Scan again to check if any ref count keys still exist
2409
1
    std::unique_ptr<Transaction> txn;
2410
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2411
1
    if (err != TxnErrorCode::TXN_OK) {
2412
0
        LOG_WARNING("failed to create txn for final check")
2413
0
                .tag("instance_id", instance_id_)
2414
0
                .tag("err", err);
2415
0
        return -1;
2416
0
    }
2417
2418
1
    std::unique_ptr<RangeGetIterator> iter;
2419
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2420
1
    if (err != TxnErrorCode::TXN_OK) {
2421
0
        LOG_WARNING("failed to create range iterator for final check")
2422
0
                .tag("instance_id", instance_id_)
2423
0
                .tag("err", err);
2424
0
        return -1;
2425
0
    }
2426
2427
1
    *has_unrecycled_rowsets = iter->has_next();
2428
1
    if (*has_unrecycled_rowsets) {
2429
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2430
0
                .tag("instance_id", instance_id_);
2431
0
    }
2432
2433
1
    return 0;
2434
1
}
2435
2436
17
int InstanceRecycler::recycle_indexes() {
2437
17
    const std::string task_name = "recycle_indexes";
2438
17
    int64_t num_scanned = 0;
2439
17
    int64_t num_expired = 0;
2440
17
    int64_t num_recycled = 0;
2441
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2442
2443
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2444
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2445
17
    std::string index_key0;
2446
17
    std::string index_key1;
2447
17
    recycle_index_key(index_key_info0, &index_key0);
2448
17
    recycle_index_key(index_key_info1, &index_key1);
2449
2450
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2451
2452
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2453
17
    register_recycle_task(task_name, start_time);
2454
2455
17
    DORIS_CLOUD_DEFER {
2456
17
        unregister_recycle_task(task_name);
2457
17
        int64_t cost =
2458
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2459
17
        metrics_context.finish_report();
2460
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2461
17
                .tag("instance_id", instance_id_)
2462
17
                .tag("num_scanned", num_scanned)
2463
17
                .tag("num_expired", num_expired)
2464
17
                .tag("num_recycled", num_recycled);
2465
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2455
2
    DORIS_CLOUD_DEFER {
2456
2
        unregister_recycle_task(task_name);
2457
2
        int64_t cost =
2458
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2459
2
        metrics_context.finish_report();
2460
2
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2461
2
                .tag("instance_id", instance_id_)
2462
2
                .tag("num_scanned", num_scanned)
2463
2
                .tag("num_expired", num_expired)
2464
2
                .tag("num_recycled", num_recycled);
2465
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2455
15
    DORIS_CLOUD_DEFER {
2456
15
        unregister_recycle_task(task_name);
2457
15
        int64_t cost =
2458
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2459
15
        metrics_context.finish_report();
2460
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2461
15
                .tag("instance_id", instance_id_)
2462
15
                .tag("num_scanned", num_scanned)
2463
15
                .tag("num_expired", num_expired)
2464
15
                .tag("num_recycled", num_recycled);
2465
15
    };
2466
2467
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2468
2469
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2470
17
    std::vector<std::string_view> index_keys;
2471
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2472
10
        ++num_scanned;
2473
10
        RecycleIndexPB index_pb;
2474
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2475
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2476
0
            return -1;
2477
0
        }
2478
10
        int64_t current_time = ::time(nullptr);
2479
10
        if (current_time <
2480
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2481
0
            return 0;
2482
0
        }
2483
10
        ++num_expired;
2484
        // decode index_id
2485
10
        auto k1 = k;
2486
10
        k1.remove_prefix(1);
2487
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2488
10
        decode_key(&k1, &out);
2489
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2490
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2491
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2492
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2493
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2494
        // Change state to RECYCLING
2495
10
        std::unique_ptr<Transaction> txn;
2496
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2497
10
        if (err != TxnErrorCode::TXN_OK) {
2498
0
            LOG_WARNING("failed to create txn").tag("err", err);
2499
0
            return -1;
2500
0
        }
2501
10
        std::string val;
2502
10
        err = txn->get(k, &val);
2503
10
        if (err ==
2504
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2505
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2506
0
            return 0;
2507
0
        }
2508
10
        if (err != TxnErrorCode::TXN_OK) {
2509
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2510
0
            return -1;
2511
0
        }
2512
10
        index_pb.Clear();
2513
10
        if (!index_pb.ParseFromString(val)) {
2514
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2515
0
            return -1;
2516
0
        }
2517
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2518
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2519
9
            txn->put(k, index_pb.SerializeAsString());
2520
9
            err = txn->commit();
2521
9
            if (err != TxnErrorCode::TXN_OK) {
2522
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2523
0
                return -1;
2524
0
            }
2525
9
        }
2526
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2527
1
            LOG_WARNING("failed to recycle tablets under index")
2528
1
                    .tag("table_id", index_pb.table_id())
2529
1
                    .tag("instance_id", instance_id_)
2530
1
                    .tag("index_id", index_id);
2531
1
            return -1;
2532
1
        }
2533
2534
9
        if (index_pb.has_db_id()) {
2535
            // Recycle the versioned keys
2536
3
            std::unique_ptr<Transaction> txn;
2537
3
            err = txn_kv_->create_txn(&txn);
2538
3
            if (err != TxnErrorCode::TXN_OK) {
2539
0
                LOG_WARNING("failed to create txn").tag("err", err);
2540
0
                return -1;
2541
0
            }
2542
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2543
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2544
3
            std::string index_inverted_key = versioned::index_inverted_key(
2545
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2546
3
            versioned_remove_all(txn.get(), meta_key);
2547
3
            txn->remove(index_key);
2548
3
            txn->remove(index_inverted_key);
2549
3
            err = txn->commit();
2550
3
            if (err != TxnErrorCode::TXN_OK) {
2551
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2552
0
                return -1;
2553
0
            }
2554
3
        }
2555
2556
9
        metrics_context.total_recycled_num = ++num_recycled;
2557
9
        metrics_context.report();
2558
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2559
9
        index_keys.push_back(k);
2560
9
        return 0;
2561
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2471
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2472
2
        ++num_scanned;
2473
2
        RecycleIndexPB index_pb;
2474
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2475
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2476
0
            return -1;
2477
0
        }
2478
2
        int64_t current_time = ::time(nullptr);
2479
2
        if (current_time <
2480
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2481
0
            return 0;
2482
0
        }
2483
2
        ++num_expired;
2484
        // decode index_id
2485
2
        auto k1 = k;
2486
2
        k1.remove_prefix(1);
2487
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2488
2
        decode_key(&k1, &out);
2489
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2490
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2491
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2492
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2493
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2494
        // Change state to RECYCLING
2495
2
        std::unique_ptr<Transaction> txn;
2496
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2497
2
        if (err != TxnErrorCode::TXN_OK) {
2498
0
            LOG_WARNING("failed to create txn").tag("err", err);
2499
0
            return -1;
2500
0
        }
2501
2
        std::string val;
2502
2
        err = txn->get(k, &val);
2503
2
        if (err ==
2504
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2505
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2506
0
            return 0;
2507
0
        }
2508
2
        if (err != TxnErrorCode::TXN_OK) {
2509
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2510
0
            return -1;
2511
0
        }
2512
2
        index_pb.Clear();
2513
2
        if (!index_pb.ParseFromString(val)) {
2514
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2515
0
            return -1;
2516
0
        }
2517
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2518
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2519
1
            txn->put(k, index_pb.SerializeAsString());
2520
1
            err = txn->commit();
2521
1
            if (err != TxnErrorCode::TXN_OK) {
2522
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2523
0
                return -1;
2524
0
            }
2525
1
        }
2526
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2527
1
            LOG_WARNING("failed to recycle tablets under index")
2528
1
                    .tag("table_id", index_pb.table_id())
2529
1
                    .tag("instance_id", instance_id_)
2530
1
                    .tag("index_id", index_id);
2531
1
            return -1;
2532
1
        }
2533
2534
1
        if (index_pb.has_db_id()) {
2535
            // Recycle the versioned keys
2536
1
            std::unique_ptr<Transaction> txn;
2537
1
            err = txn_kv_->create_txn(&txn);
2538
1
            if (err != TxnErrorCode::TXN_OK) {
2539
0
                LOG_WARNING("failed to create txn").tag("err", err);
2540
0
                return -1;
2541
0
            }
2542
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2543
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2544
1
            std::string index_inverted_key = versioned::index_inverted_key(
2545
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2546
1
            versioned_remove_all(txn.get(), meta_key);
2547
1
            txn->remove(index_key);
2548
1
            txn->remove(index_inverted_key);
2549
1
            err = txn->commit();
2550
1
            if (err != TxnErrorCode::TXN_OK) {
2551
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2552
0
                return -1;
2553
0
            }
2554
1
        }
2555
2556
1
        metrics_context.total_recycled_num = ++num_recycled;
2557
1
        metrics_context.report();
2558
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2559
1
        index_keys.push_back(k);
2560
1
        return 0;
2561
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2471
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2472
8
        ++num_scanned;
2473
8
        RecycleIndexPB index_pb;
2474
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2475
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2476
0
            return -1;
2477
0
        }
2478
8
        int64_t current_time = ::time(nullptr);
2479
8
        if (current_time <
2480
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2481
0
            return 0;
2482
0
        }
2483
8
        ++num_expired;
2484
        // decode index_id
2485
8
        auto k1 = k;
2486
8
        k1.remove_prefix(1);
2487
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2488
8
        decode_key(&k1, &out);
2489
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2490
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2491
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2492
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2493
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2494
        // Change state to RECYCLING
2495
8
        std::unique_ptr<Transaction> txn;
2496
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2497
8
        if (err != TxnErrorCode::TXN_OK) {
2498
0
            LOG_WARNING("failed to create txn").tag("err", err);
2499
0
            return -1;
2500
0
        }
2501
8
        std::string val;
2502
8
        err = txn->get(k, &val);
2503
8
        if (err ==
2504
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2505
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2506
0
            return 0;
2507
0
        }
2508
8
        if (err != TxnErrorCode::TXN_OK) {
2509
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2510
0
            return -1;
2511
0
        }
2512
8
        index_pb.Clear();
2513
8
        if (!index_pb.ParseFromString(val)) {
2514
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2515
0
            return -1;
2516
0
        }
2517
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2518
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2519
8
            txn->put(k, index_pb.SerializeAsString());
2520
8
            err = txn->commit();
2521
8
            if (err != TxnErrorCode::TXN_OK) {
2522
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2523
0
                return -1;
2524
0
            }
2525
8
        }
2526
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2527
0
            LOG_WARNING("failed to recycle tablets under index")
2528
0
                    .tag("table_id", index_pb.table_id())
2529
0
                    .tag("instance_id", instance_id_)
2530
0
                    .tag("index_id", index_id);
2531
0
            return -1;
2532
0
        }
2533
2534
8
        if (index_pb.has_db_id()) {
2535
            // Recycle the versioned keys
2536
2
            std::unique_ptr<Transaction> txn;
2537
2
            err = txn_kv_->create_txn(&txn);
2538
2
            if (err != TxnErrorCode::TXN_OK) {
2539
0
                LOG_WARNING("failed to create txn").tag("err", err);
2540
0
                return -1;
2541
0
            }
2542
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2543
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2544
2
            std::string index_inverted_key = versioned::index_inverted_key(
2545
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2546
2
            versioned_remove_all(txn.get(), meta_key);
2547
2
            txn->remove(index_key);
2548
2
            txn->remove(index_inverted_key);
2549
2
            err = txn->commit();
2550
2
            if (err != TxnErrorCode::TXN_OK) {
2551
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2552
0
                return -1;
2553
0
            }
2554
2
        }
2555
2556
8
        metrics_context.total_recycled_num = ++num_recycled;
2557
8
        metrics_context.report();
2558
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2559
8
        index_keys.push_back(k);
2560
8
        return 0;
2561
8
    };
2562
2563
17
    auto loop_done = [&index_keys, this]() -> int {
2564
6
        if (index_keys.empty()) return 0;
2565
5
        DORIS_CLOUD_DEFER {
2566
5
            index_keys.clear();
2567
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2565
1
        DORIS_CLOUD_DEFER {
2566
1
            index_keys.clear();
2567
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2565
4
        DORIS_CLOUD_DEFER {
2566
4
            index_keys.clear();
2567
4
        };
2568
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2569
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2570
0
            return -1;
2571
0
        }
2572
5
        return 0;
2573
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2563
2
    auto loop_done = [&index_keys, this]() -> int {
2564
2
        if (index_keys.empty()) return 0;
2565
1
        DORIS_CLOUD_DEFER {
2566
1
            index_keys.clear();
2567
1
        };
2568
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2569
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2570
0
            return -1;
2571
0
        }
2572
1
        return 0;
2573
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2563
4
    auto loop_done = [&index_keys, this]() -> int {
2564
4
        if (index_keys.empty()) return 0;
2565
4
        DORIS_CLOUD_DEFER {
2566
4
            index_keys.clear();
2567
4
        };
2568
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2569
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2570
0
            return -1;
2571
0
        }
2572
4
        return 0;
2573
4
    };
2574
2575
17
    if (config::enable_recycler_stats_metrics) {
2576
0
        scan_and_statistics_indexes();
2577
0
    }
2578
    // recycle_func and loop_done for scan and recycle
2579
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2580
17
}
2581
2582
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2583
8.25k
                             int64_t tablet_id) {
2584
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2585
2586
8.25k
    std::unique_ptr<Transaction> txn;
2587
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2588
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2589
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2590
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2591
0
        return false;
2592
0
    }
2593
2594
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2595
8.25k
    std::string tablet_idx_val;
2596
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2597
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2598
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2599
0
                     << " tablet_id=" << tablet_id << " err=" << err
2600
0
                     << " key=" << hex(tablet_idx_key);
2601
0
        return false;
2602
0
    }
2603
2604
8.25k
    TabletIndexPB tablet_idx_pb;
2605
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2606
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2607
0
                     << " tablet_id=" << tablet_id;
2608
0
        return false;
2609
0
    }
2610
2611
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2612
        // In the previous version, the db_id was not set in the index_pb.
2613
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2614
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2615
0
                  << " instance_id=" << instance_id
2616
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2617
0
        return true;
2618
0
    }
2619
2620
8.25k
    std::string ver_val;
2621
8.25k
    std::string ver_key =
2622
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2623
8.25k
                                   tablet_idx_pb.partition_id()});
2624
8.25k
    err = txn->get(ver_key, &ver_val);
2625
2626
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2627
214
        LOG(INFO) << ""
2628
214
                     "partition version not found, instance_id="
2629
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2630
214
                  << " table_id=" << tablet_idx_pb.table_id()
2631
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2632
214
                  << " key=" << hex(ver_key);
2633
214
        return true;
2634
214
    }
2635
2636
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2637
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2638
0
                     << " db_id=" << tablet_idx_pb.db_id()
2639
0
                     << " table_id=" << tablet_idx_pb.table_id()
2640
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2641
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2642
0
        return false;
2643
0
    }
2644
2645
8.03k
    VersionPB version_pb;
2646
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2647
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2648
0
                     << " db_id=" << tablet_idx_pb.db_id()
2649
0
                     << " table_id=" << tablet_idx_pb.table_id()
2650
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2651
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2652
0
        return false;
2653
0
    }
2654
2655
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2656
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2657
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2658
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2659
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2660
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2661
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2662
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2663
4.00k
                     << " key=" << hex(ver_key);
2664
4.00k
        return false;
2665
4.00k
    }
2666
4.03k
    return true;
2667
8.03k
}
2668
2669
15
int InstanceRecycler::recycle_partitions() {
2670
15
    const std::string task_name = "recycle_partitions";
2671
15
    int64_t num_scanned = 0;
2672
15
    int64_t num_expired = 0;
2673
15
    int64_t num_recycled = 0;
2674
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2675
2676
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2677
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2678
15
    std::string part_key0;
2679
15
    std::string part_key1;
2680
15
    recycle_partition_key(part_key_info0, &part_key0);
2681
15
    recycle_partition_key(part_key_info1, &part_key1);
2682
2683
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2684
2685
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2686
15
    register_recycle_task(task_name, start_time);
2687
2688
15
    DORIS_CLOUD_DEFER {
2689
15
        unregister_recycle_task(task_name);
2690
15
        int64_t cost =
2691
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2692
15
        metrics_context.finish_report();
2693
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2694
15
                .tag("instance_id", instance_id_)
2695
15
                .tag("num_scanned", num_scanned)
2696
15
                .tag("num_expired", num_expired)
2697
15
                .tag("num_recycled", num_recycled);
2698
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2688
2
    DORIS_CLOUD_DEFER {
2689
2
        unregister_recycle_task(task_name);
2690
2
        int64_t cost =
2691
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2692
2
        metrics_context.finish_report();
2693
2
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2694
2
                .tag("instance_id", instance_id_)
2695
2
                .tag("num_scanned", num_scanned)
2696
2
                .tag("num_expired", num_expired)
2697
2
                .tag("num_recycled", num_recycled);
2698
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2688
13
    DORIS_CLOUD_DEFER {
2689
13
        unregister_recycle_task(task_name);
2690
13
        int64_t cost =
2691
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2692
13
        metrics_context.finish_report();
2693
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
2694
13
                .tag("instance_id", instance_id_)
2695
13
                .tag("num_scanned", num_scanned)
2696
13
                .tag("num_expired", num_expired)
2697
13
                .tag("num_recycled", num_recycled);
2698
13
    };
2699
2700
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2701
2702
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
2703
15
    std::vector<std::string_view> partition_keys;
2704
15
    std::vector<std::string> partition_version_keys;
2705
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2706
9
        ++num_scanned;
2707
9
        RecyclePartitionPB part_pb;
2708
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2709
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2710
0
            return -1;
2711
0
        }
2712
9
        int64_t current_time = ::time(nullptr);
2713
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2714
9
                                                            &earlest_ts)) { // not expired
2715
0
            return 0;
2716
0
        }
2717
9
        ++num_expired;
2718
        // decode partition_id
2719
9
        auto k1 = k;
2720
9
        k1.remove_prefix(1);
2721
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2722
9
        decode_key(&k1, &out);
2723
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2724
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2725
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2726
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2727
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2728
        // Change state to RECYCLING
2729
9
        std::unique_ptr<Transaction> txn;
2730
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2731
9
        if (err != TxnErrorCode::TXN_OK) {
2732
0
            LOG_WARNING("failed to create txn").tag("err", err);
2733
0
            return -1;
2734
0
        }
2735
9
        std::string val;
2736
9
        err = txn->get(k, &val);
2737
9
        if (err ==
2738
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2739
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2740
0
            return 0;
2741
0
        }
2742
9
        if (err != TxnErrorCode::TXN_OK) {
2743
0
            LOG_WARNING("failed to get kv");
2744
0
            return -1;
2745
0
        }
2746
9
        part_pb.Clear();
2747
9
        if (!part_pb.ParseFromString(val)) {
2748
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2749
0
            return -1;
2750
0
        }
2751
        // Partitions with PREPARED state MUST have no data
2752
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2753
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2754
8
            txn->put(k, part_pb.SerializeAsString());
2755
8
            err = txn->commit();
2756
8
            if (err != TxnErrorCode::TXN_OK) {
2757
0
                LOG_WARNING("failed to commit txn: {}", err);
2758
0
                return -1;
2759
0
            }
2760
8
        }
2761
2762
9
        int ret = 0;
2763
33
        for (int64_t index_id : part_pb.index_id()) {
2764
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2765
1
                LOG_WARNING("failed to recycle tablets under partition")
2766
1
                        .tag("table_id", part_pb.table_id())
2767
1
                        .tag("instance_id", instance_id_)
2768
1
                        .tag("index_id", index_id)
2769
1
                        .tag("partition_id", partition_id);
2770
1
                ret = -1;
2771
1
            }
2772
33
        }
2773
9
        if (ret == 0 && part_pb.has_db_id()) {
2774
            // Recycle the versioned keys
2775
8
            std::unique_ptr<Transaction> txn;
2776
8
            err = txn_kv_->create_txn(&txn);
2777
8
            if (err != TxnErrorCode::TXN_OK) {
2778
0
                LOG_WARNING("failed to create txn").tag("err", err);
2779
0
                return -1;
2780
0
            }
2781
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2782
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2783
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2784
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2785
8
            std::string partition_version_key =
2786
8
                    versioned::partition_version_key({instance_id_, partition_id});
2787
8
            versioned_remove_all(txn.get(), meta_key);
2788
8
            txn->remove(index_key);
2789
8
            txn->remove(inverted_index_key);
2790
8
            versioned_remove_all(txn.get(), partition_version_key);
2791
8
            err = txn->commit();
2792
8
            if (err != TxnErrorCode::TXN_OK) {
2793
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2794
0
                return -1;
2795
0
            }
2796
8
        }
2797
2798
9
        if (ret == 0) {
2799
8
            ++num_recycled;
2800
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2801
8
            partition_keys.push_back(k);
2802
8
            if (part_pb.db_id() > 0) {
2803
8
                partition_version_keys.push_back(partition_version_key(
2804
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2805
8
            }
2806
8
            metrics_context.total_recycled_num = num_recycled;
2807
8
            metrics_context.report();
2808
8
        }
2809
9
        return ret;
2810
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2705
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2706
2
        ++num_scanned;
2707
2
        RecyclePartitionPB part_pb;
2708
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2709
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2710
0
            return -1;
2711
0
        }
2712
2
        int64_t current_time = ::time(nullptr);
2713
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2714
2
                                                            &earlest_ts)) { // not expired
2715
0
            return 0;
2716
0
        }
2717
2
        ++num_expired;
2718
        // decode partition_id
2719
2
        auto k1 = k;
2720
2
        k1.remove_prefix(1);
2721
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2722
2
        decode_key(&k1, &out);
2723
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2724
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2725
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2726
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2727
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2728
        // Change state to RECYCLING
2729
2
        std::unique_ptr<Transaction> txn;
2730
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2731
2
        if (err != TxnErrorCode::TXN_OK) {
2732
0
            LOG_WARNING("failed to create txn").tag("err", err);
2733
0
            return -1;
2734
0
        }
2735
2
        std::string val;
2736
2
        err = txn->get(k, &val);
2737
2
        if (err ==
2738
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2739
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2740
0
            return 0;
2741
0
        }
2742
2
        if (err != TxnErrorCode::TXN_OK) {
2743
0
            LOG_WARNING("failed to get kv");
2744
0
            return -1;
2745
0
        }
2746
2
        part_pb.Clear();
2747
2
        if (!part_pb.ParseFromString(val)) {
2748
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2749
0
            return -1;
2750
0
        }
2751
        // Partitions with PREPARED state MUST have no data
2752
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2753
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2754
1
            txn->put(k, part_pb.SerializeAsString());
2755
1
            err = txn->commit();
2756
1
            if (err != TxnErrorCode::TXN_OK) {
2757
0
                LOG_WARNING("failed to commit txn: {}", err);
2758
0
                return -1;
2759
0
            }
2760
1
        }
2761
2762
2
        int ret = 0;
2763
2
        for (int64_t index_id : part_pb.index_id()) {
2764
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2765
1
                LOG_WARNING("failed to recycle tablets under partition")
2766
1
                        .tag("table_id", part_pb.table_id())
2767
1
                        .tag("instance_id", instance_id_)
2768
1
                        .tag("index_id", index_id)
2769
1
                        .tag("partition_id", partition_id);
2770
1
                ret = -1;
2771
1
            }
2772
2
        }
2773
2
        if (ret == 0 && part_pb.has_db_id()) {
2774
            // Recycle the versioned keys
2775
1
            std::unique_ptr<Transaction> txn;
2776
1
            err = txn_kv_->create_txn(&txn);
2777
1
            if (err != TxnErrorCode::TXN_OK) {
2778
0
                LOG_WARNING("failed to create txn").tag("err", err);
2779
0
                return -1;
2780
0
            }
2781
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2782
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2783
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2784
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2785
1
            std::string partition_version_key =
2786
1
                    versioned::partition_version_key({instance_id_, partition_id});
2787
1
            versioned_remove_all(txn.get(), meta_key);
2788
1
            txn->remove(index_key);
2789
1
            txn->remove(inverted_index_key);
2790
1
            versioned_remove_all(txn.get(), partition_version_key);
2791
1
            err = txn->commit();
2792
1
            if (err != TxnErrorCode::TXN_OK) {
2793
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2794
0
                return -1;
2795
0
            }
2796
1
        }
2797
2798
2
        if (ret == 0) {
2799
1
            ++num_recycled;
2800
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2801
1
            partition_keys.push_back(k);
2802
1
            if (part_pb.db_id() > 0) {
2803
1
                partition_version_keys.push_back(partition_version_key(
2804
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2805
1
            }
2806
1
            metrics_context.total_recycled_num = num_recycled;
2807
1
            metrics_context.report();
2808
1
        }
2809
2
        return ret;
2810
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2705
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2706
7
        ++num_scanned;
2707
7
        RecyclePartitionPB part_pb;
2708
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
2709
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2710
0
            return -1;
2711
0
        }
2712
7
        int64_t current_time = ::time(nullptr);
2713
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
2714
7
                                                            &earlest_ts)) { // not expired
2715
0
            return 0;
2716
0
        }
2717
7
        ++num_expired;
2718
        // decode partition_id
2719
7
        auto k1 = k;
2720
7
        k1.remove_prefix(1);
2721
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2722
7
        decode_key(&k1, &out);
2723
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
2724
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
2725
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
2726
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
2727
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
2728
        // Change state to RECYCLING
2729
7
        std::unique_ptr<Transaction> txn;
2730
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2731
7
        if (err != TxnErrorCode::TXN_OK) {
2732
0
            LOG_WARNING("failed to create txn").tag("err", err);
2733
0
            return -1;
2734
0
        }
2735
7
        std::string val;
2736
7
        err = txn->get(k, &val);
2737
7
        if (err ==
2738
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2739
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
2740
0
            return 0;
2741
0
        }
2742
7
        if (err != TxnErrorCode::TXN_OK) {
2743
0
            LOG_WARNING("failed to get kv");
2744
0
            return -1;
2745
0
        }
2746
7
        part_pb.Clear();
2747
7
        if (!part_pb.ParseFromString(val)) {
2748
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
2749
0
            return -1;
2750
0
        }
2751
        // Partitions with PREPARED state MUST have no data
2752
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
2753
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
2754
7
            txn->put(k, part_pb.SerializeAsString());
2755
7
            err = txn->commit();
2756
7
            if (err != TxnErrorCode::TXN_OK) {
2757
0
                LOG_WARNING("failed to commit txn: {}", err);
2758
0
                return -1;
2759
0
            }
2760
7
        }
2761
2762
7
        int ret = 0;
2763
31
        for (int64_t index_id : part_pb.index_id()) {
2764
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
2765
0
                LOG_WARNING("failed to recycle tablets under partition")
2766
0
                        .tag("table_id", part_pb.table_id())
2767
0
                        .tag("instance_id", instance_id_)
2768
0
                        .tag("index_id", index_id)
2769
0
                        .tag("partition_id", partition_id);
2770
0
                ret = -1;
2771
0
            }
2772
31
        }
2773
7
        if (ret == 0 && part_pb.has_db_id()) {
2774
            // Recycle the versioned keys
2775
7
            std::unique_ptr<Transaction> txn;
2776
7
            err = txn_kv_->create_txn(&txn);
2777
7
            if (err != TxnErrorCode::TXN_OK) {
2778
0
                LOG_WARNING("failed to create txn").tag("err", err);
2779
0
                return -1;
2780
0
            }
2781
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
2782
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
2783
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
2784
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
2785
7
            std::string partition_version_key =
2786
7
                    versioned::partition_version_key({instance_id_, partition_id});
2787
7
            versioned_remove_all(txn.get(), meta_key);
2788
7
            txn->remove(index_key);
2789
7
            txn->remove(inverted_index_key);
2790
7
            versioned_remove_all(txn.get(), partition_version_key);
2791
7
            err = txn->commit();
2792
7
            if (err != TxnErrorCode::TXN_OK) {
2793
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2794
0
                return -1;
2795
0
            }
2796
7
        }
2797
2798
7
        if (ret == 0) {
2799
7
            ++num_recycled;
2800
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2801
7
            partition_keys.push_back(k);
2802
7
            if (part_pb.db_id() > 0) {
2803
7
                partition_version_keys.push_back(partition_version_key(
2804
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
2805
7
            }
2806
7
            metrics_context.total_recycled_num = num_recycled;
2807
7
            metrics_context.report();
2808
7
        }
2809
7
        return ret;
2810
7
    };
2811
2812
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2813
5
        if (partition_keys.empty()) return 0;
2814
4
        DORIS_CLOUD_DEFER {
2815
4
            partition_keys.clear();
2816
4
            partition_version_keys.clear();
2817
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2814
1
        DORIS_CLOUD_DEFER {
2815
1
            partition_keys.clear();
2816
1
            partition_version_keys.clear();
2817
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2814
3
        DORIS_CLOUD_DEFER {
2815
3
            partition_keys.clear();
2816
3
            partition_version_keys.clear();
2817
3
        };
2818
4
        std::unique_ptr<Transaction> txn;
2819
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2820
4
        if (err != TxnErrorCode::TXN_OK) {
2821
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2822
0
            return -1;
2823
0
        }
2824
8
        for (auto& k : partition_keys) {
2825
8
            txn->remove(k);
2826
8
        }
2827
8
        for (auto& k : partition_version_keys) {
2828
8
            txn->remove(k);
2829
8
        }
2830
4
        err = txn->commit();
2831
4
        if (err != TxnErrorCode::TXN_OK) {
2832
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2833
0
                         << " err=" << err;
2834
0
            return -1;
2835
0
        }
2836
4
        return 0;
2837
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2812
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2813
2
        if (partition_keys.empty()) return 0;
2814
1
        DORIS_CLOUD_DEFER {
2815
1
            partition_keys.clear();
2816
1
            partition_version_keys.clear();
2817
1
        };
2818
1
        std::unique_ptr<Transaction> txn;
2819
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2820
1
        if (err != TxnErrorCode::TXN_OK) {
2821
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2822
0
            return -1;
2823
0
        }
2824
1
        for (auto& k : partition_keys) {
2825
1
            txn->remove(k);
2826
1
        }
2827
1
        for (auto& k : partition_version_keys) {
2828
1
            txn->remove(k);
2829
1
        }
2830
1
        err = txn->commit();
2831
1
        if (err != TxnErrorCode::TXN_OK) {
2832
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2833
0
                         << " err=" << err;
2834
0
            return -1;
2835
0
        }
2836
1
        return 0;
2837
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
2812
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
2813
3
        if (partition_keys.empty()) return 0;
2814
3
        DORIS_CLOUD_DEFER {
2815
3
            partition_keys.clear();
2816
3
            partition_version_keys.clear();
2817
3
        };
2818
3
        std::unique_ptr<Transaction> txn;
2819
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2820
3
        if (err != TxnErrorCode::TXN_OK) {
2821
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
2822
0
            return -1;
2823
0
        }
2824
7
        for (auto& k : partition_keys) {
2825
7
            txn->remove(k);
2826
7
        }
2827
7
        for (auto& k : partition_version_keys) {
2828
7
            txn->remove(k);
2829
7
        }
2830
3
        err = txn->commit();
2831
3
        if (err != TxnErrorCode::TXN_OK) {
2832
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
2833
0
                         << " err=" << err;
2834
0
            return -1;
2835
0
        }
2836
3
        return 0;
2837
3
    };
2838
2839
15
    if (config::enable_recycler_stats_metrics) {
2840
0
        scan_and_statistics_partitions();
2841
0
    }
2842
    // recycle_func and loop_done for scan and recycle
2843
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
2844
15
}
2845
2846
14
int InstanceRecycler::recycle_versions() {
2847
14
    if (should_recycle_versioned_keys()) {
2848
2
        return recycle_orphan_partitions();
2849
2
    }
2850
2851
12
    int64_t num_scanned = 0;
2852
12
    int64_t num_recycled = 0;
2853
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
2854
2855
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
2856
2857
12
    auto start_time = steady_clock::now();
2858
2859
12
    DORIS_CLOUD_DEFER {
2860
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2861
12
        metrics_context.finish_report();
2862
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2863
12
                .tag("instance_id", instance_id_)
2864
12
                .tag("num_scanned", num_scanned)
2865
12
                .tag("num_recycled", num_recycled);
2866
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
2859
12
    DORIS_CLOUD_DEFER {
2860
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2861
12
        metrics_context.finish_report();
2862
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
2863
12
                .tag("instance_id", instance_id_)
2864
12
                .tag("num_scanned", num_scanned)
2865
12
                .tag("num_recycled", num_recycled);
2866
12
    };
2867
2868
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
2869
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
2870
12
    int64_t last_scanned_table_id = 0;
2871
12
    bool is_recycled = false; // Is last scanned kv recycled
2872
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
2873
12
                         &metrics_context, this](std::string_view k, std::string_view) {
2874
2
        ++num_scanned;
2875
2
        auto k1 = k;
2876
2
        k1.remove_prefix(1);
2877
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2878
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2879
2
        decode_key(&k1, &out);
2880
2
        DCHECK_EQ(out.size(), 6) << k;
2881
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2882
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2883
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2884
0
            return 0;
2885
0
        }
2886
2
        last_scanned_table_id = table_id;
2887
2
        is_recycled = false;
2888
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2889
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2890
2
        std::unique_ptr<Transaction> txn;
2891
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2892
2
        if (err != TxnErrorCode::TXN_OK) {
2893
0
            return -1;
2894
0
        }
2895
2
        std::unique_ptr<RangeGetIterator> iter;
2896
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2897
2
        if (err != TxnErrorCode::TXN_OK) {
2898
0
            return -1;
2899
0
        }
2900
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2901
1
            return 0;
2902
1
        }
2903
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2904
        // 1. Remove all partition version kvs of this table
2905
1
        auto partition_version_key_begin =
2906
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2907
1
        auto partition_version_key_end =
2908
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2909
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2910
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2911
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2912
1
                     << " table_id=" << table_id;
2913
        // 2. Remove the table version kv of this table
2914
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2915
1
        txn->remove(tbl_version_key);
2916
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2917
        // 3. Remove mow delete bitmap update lock and tablet job lock
2918
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2919
1
        txn->remove(lock_key);
2920
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2921
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2922
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2923
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2924
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2925
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2926
1
                     << " table_id=" << table_id;
2927
1
        err = txn->commit();
2928
1
        if (err != TxnErrorCode::TXN_OK) {
2929
0
            return -1;
2930
0
        }
2931
1
        metrics_context.total_recycled_num = ++num_recycled;
2932
1
        metrics_context.report();
2933
1
        is_recycled = true;
2934
1
        return 0;
2935
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2873
2
                         &metrics_context, this](std::string_view k, std::string_view) {
2874
2
        ++num_scanned;
2875
2
        auto k1 = k;
2876
2
        k1.remove_prefix(1);
2877
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2878
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2879
2
        decode_key(&k1, &out);
2880
2
        DCHECK_EQ(out.size(), 6) << k;
2881
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2882
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
2883
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
2884
0
            return 0;
2885
0
        }
2886
2
        last_scanned_table_id = table_id;
2887
2
        is_recycled = false;
2888
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
2889
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
2890
2
        std::unique_ptr<Transaction> txn;
2891
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2892
2
        if (err != TxnErrorCode::TXN_OK) {
2893
0
            return -1;
2894
0
        }
2895
2
        std::unique_ptr<RangeGetIterator> iter;
2896
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
2897
2
        if (err != TxnErrorCode::TXN_OK) {
2898
0
            return -1;
2899
0
        }
2900
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
2901
1
            return 0;
2902
1
        }
2903
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2904
        // 1. Remove all partition version kvs of this table
2905
1
        auto partition_version_key_begin =
2906
1
                partition_version_key({instance_id_, db_id, table_id, 0});
2907
1
        auto partition_version_key_end =
2908
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2909
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
2910
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
2911
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
2912
1
                     << " table_id=" << table_id;
2913
        // 2. Remove the table version kv of this table
2914
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
2915
1
        txn->remove(tbl_version_key);
2916
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
2917
        // 3. Remove mow delete bitmap update lock and tablet job lock
2918
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
2919
1
        txn->remove(lock_key);
2920
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
2921
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
2922
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
2923
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
2924
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
2925
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
2926
1
                     << " table_id=" << table_id;
2927
1
        err = txn->commit();
2928
1
        if (err != TxnErrorCode::TXN_OK) {
2929
0
            return -1;
2930
0
        }
2931
1
        metrics_context.total_recycled_num = ++num_recycled;
2932
1
        metrics_context.report();
2933
1
        is_recycled = true;
2934
1
        return 0;
2935
1
    };
2936
2937
12
    if (config::enable_recycler_stats_metrics) {
2938
0
        scan_and_statistics_versions();
2939
0
    }
2940
    // recycle_func and loop_done for scan and recycle
2941
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
2942
14
}
2943
2944
3
int InstanceRecycler::recycle_orphan_partitions() {
2945
3
    int64_t num_scanned = 0;
2946
3
    int64_t num_recycled = 0;
2947
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
2948
2949
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
2950
3
            .tag("instance_id", instance_id_);
2951
2952
3
    auto start_time = steady_clock::now();
2953
2954
3
    DORIS_CLOUD_DEFER {
2955
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2956
3
        metrics_context.finish_report();
2957
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2958
3
                .tag("instance_id", instance_id_)
2959
3
                .tag("num_scanned", num_scanned)
2960
3
                .tag("num_recycled", num_recycled);
2961
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
2954
3
    DORIS_CLOUD_DEFER {
2955
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2956
3
        metrics_context.finish_report();
2957
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
2958
3
                .tag("instance_id", instance_id_)
2959
3
                .tag("num_scanned", num_scanned)
2960
3
                .tag("num_recycled", num_recycled);
2961
3
    };
2962
2963
3
    bool is_empty_table = false;        // whether the table has no indexes
2964
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
2965
3
    int64_t current_table_id = 0;       // current scanning table id
2966
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
2967
3
                         &current_table_id, &is_table_kvs_recycled,
2968
3
                         this](std::string_view k, std::string_view) {
2969
2
        ++num_scanned;
2970
2971
2
        std::string_view k1(k);
2972
2
        int64_t db_id, table_id, partition_id;
2973
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2974
2
                                                            &partition_id)) {
2975
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2976
0
            return -1;
2977
2
        } else if (table_id != current_table_id) {
2978
2
            current_table_id = table_id;
2979
2
            is_table_kvs_recycled = false;
2980
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2981
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2982
2
            if (err != TxnErrorCode::TXN_OK) {
2983
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2984
0
                             << " table_id=" << table_id << " err=" << err;
2985
0
                return -1;
2986
0
            }
2987
2
        }
2988
2989
2
        if (!is_empty_table) {
2990
            // table is not empty, skip recycle
2991
1
            return 0;
2992
1
        }
2993
2994
1
        std::unique_ptr<Transaction> txn;
2995
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2996
1
        if (err != TxnErrorCode::TXN_OK) {
2997
0
            return -1;
2998
0
        }
2999
3000
        // 1. Remove all partition related kvs
3001
1
        std::string partition_meta_key =
3002
1
                versioned::meta_partition_key({instance_id_, partition_id});
3003
1
        std::string partition_index_key =
3004
1
                versioned::partition_index_key({instance_id_, partition_id});
3005
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3006
1
                {instance_id_, db_id, table_id, partition_id});
3007
1
        std::string partition_version_key =
3008
1
                versioned::partition_version_key({instance_id_, partition_id});
3009
1
        txn->remove(partition_index_key);
3010
1
        txn->remove(partition_inverted_key);
3011
1
        versioned_remove_all(txn.get(), partition_meta_key);
3012
1
        versioned_remove_all(txn.get(), partition_version_key);
3013
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3014
1
                     << " table_id=" << table_id << " db_id=" << db_id
3015
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3016
1
                     << " partition_version_key=" << hex(partition_version_key);
3017
3018
1
        if (!is_table_kvs_recycled) {
3019
1
            is_table_kvs_recycled = true;
3020
3021
            // 2. Remove the table version kv of this table
3022
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3023
1
            versioned_remove_all(txn.get(), table_version_key);
3024
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3025
            // 3. Remove mow delete bitmap update lock and tablet job lock
3026
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3027
1
            txn->remove(lock_key);
3028
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3029
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3030
1
            std::string tablet_job_key_end =
3031
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3032
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3033
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3034
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3035
1
                         << " table_id=" << table_id;
3036
1
        }
3037
3038
1
        err = txn->commit();
3039
1
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            return -1;
3041
0
        }
3042
1
        metrics_context.total_recycled_num = ++num_recycled;
3043
1
        metrics_context.report();
3044
1
        return 0;
3045
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
2968
2
                         this](std::string_view k, std::string_view) {
2969
2
        ++num_scanned;
2970
2971
2
        std::string_view k1(k);
2972
2
        int64_t db_id, table_id, partition_id;
2973
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
2974
2
                                                            &partition_id)) {
2975
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
2976
0
            return -1;
2977
2
        } else if (table_id != current_table_id) {
2978
2
            current_table_id = table_id;
2979
2
            is_table_kvs_recycled = false;
2980
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
2981
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
2982
2
            if (err != TxnErrorCode::TXN_OK) {
2983
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
2984
0
                             << " table_id=" << table_id << " err=" << err;
2985
0
                return -1;
2986
0
            }
2987
2
        }
2988
2989
2
        if (!is_empty_table) {
2990
            // table is not empty, skip recycle
2991
1
            return 0;
2992
1
        }
2993
2994
1
        std::unique_ptr<Transaction> txn;
2995
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2996
1
        if (err != TxnErrorCode::TXN_OK) {
2997
0
            return -1;
2998
0
        }
2999
3000
        // 1. Remove all partition related kvs
3001
1
        std::string partition_meta_key =
3002
1
                versioned::meta_partition_key({instance_id_, partition_id});
3003
1
        std::string partition_index_key =
3004
1
                versioned::partition_index_key({instance_id_, partition_id});
3005
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3006
1
                {instance_id_, db_id, table_id, partition_id});
3007
1
        std::string partition_version_key =
3008
1
                versioned::partition_version_key({instance_id_, partition_id});
3009
1
        txn->remove(partition_index_key);
3010
1
        txn->remove(partition_inverted_key);
3011
1
        versioned_remove_all(txn.get(), partition_meta_key);
3012
1
        versioned_remove_all(txn.get(), partition_version_key);
3013
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3014
1
                     << " table_id=" << table_id << " db_id=" << db_id
3015
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3016
1
                     << " partition_version_key=" << hex(partition_version_key);
3017
3018
1
        if (!is_table_kvs_recycled) {
3019
1
            is_table_kvs_recycled = true;
3020
3021
            // 2. Remove the table version kv of this table
3022
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3023
1
            versioned_remove_all(txn.get(), table_version_key);
3024
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3025
            // 3. Remove mow delete bitmap update lock and tablet job lock
3026
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3027
1
            txn->remove(lock_key);
3028
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3029
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3030
1
            std::string tablet_job_key_end =
3031
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3032
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3033
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3034
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3035
1
                         << " table_id=" << table_id;
3036
1
        }
3037
3038
1
        err = txn->commit();
3039
1
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            return -1;
3041
0
        }
3042
1
        metrics_context.total_recycled_num = ++num_recycled;
3043
1
        metrics_context.report();
3044
1
        return 0;
3045
1
    };
3046
3047
    // recycle_func and loop_done for scan and recycle
3048
3
    return scan_and_recycle(
3049
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3050
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3051
3
            std::move(recycle_func));
3052
3
}
3053
3054
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3055
                                      RecyclerMetricsContext& metrics_context,
3056
52
                                      int64_t partition_id) {
3057
52
    bool is_multi_version =
3058
52
            instance_info_.has_multi_version_status() &&
3059
52
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3060
52
    int64_t num_scanned = 0;
3061
52
    std::atomic_long num_recycled = 0;
3062
3063
52
    std::string tablet_key_begin, tablet_key_end;
3064
52
    std::string stats_key_begin, stats_key_end;
3065
52
    std::string job_key_begin, job_key_end;
3066
3067
52
    std::string tablet_belongs;
3068
52
    if (partition_id > 0) {
3069
        // recycle tablets in a partition belonging to the index
3070
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3071
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3072
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3073
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3074
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3075
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3076
33
        tablet_belongs = "partition";
3077
33
    } else {
3078
        // recycle tablets in the index
3079
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3080
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3081
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3082
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3083
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3084
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3085
19
        tablet_belongs = "index";
3086
19
    }
3087
3088
52
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3089
52
            .tag("table_id", table_id)
3090
52
            .tag("index_id", index_id)
3091
52
            .tag("partition_id", partition_id);
3092
3093
52
    auto start_time = steady_clock::now();
3094
3095
52
    DORIS_CLOUD_DEFER {
3096
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3097
52
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3098
52
                .tag("instance_id", instance_id_)
3099
52
                .tag("table_id", table_id)
3100
52
                .tag("index_id", index_id)
3101
52
                .tag("partition_id", partition_id)
3102
52
                .tag("num_scanned", num_scanned)
3103
52
                .tag("num_recycled", num_recycled);
3104
52
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3095
4
    DORIS_CLOUD_DEFER {
3096
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3097
4
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3098
4
                .tag("instance_id", instance_id_)
3099
4
                .tag("table_id", table_id)
3100
4
                .tag("index_id", index_id)
3101
4
                .tag("partition_id", partition_id)
3102
4
                .tag("num_scanned", num_scanned)
3103
4
                .tag("num_recycled", num_recycled);
3104
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3095
48
    DORIS_CLOUD_DEFER {
3096
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3097
48
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3098
48
                .tag("instance_id", instance_id_)
3099
48
                .tag("table_id", table_id)
3100
48
                .tag("index_id", index_id)
3101
48
                .tag("partition_id", partition_id)
3102
48
                .tag("num_scanned", num_scanned)
3103
48
                .tag("num_recycled", num_recycled);
3104
48
    };
3105
3106
    // The tablet key and id which have been recycled.
3107
52
    struct TabletInfo {
3108
52
        std::string_view tablet_meta_key;
3109
52
        int64_t tablet_id;
3110
52
    };
3111
52
    SyncExecutor<TabletInfo> sync_executor(
3112
52
            _thread_pool_group.recycle_tablet_pool,
3113
52
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3114
52
                        index_id, partition_id),
3115
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3115
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3115
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3116
3117
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3118
52
    std::vector<std::string> init_rs_keys;
3119
52
    bool has_failure = false;
3120
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3121
8.25k
        ++num_scanned;
3122
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3123
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3124
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3125
0
            has_failure = true;
3126
0
            return -1;
3127
0
        }
3128
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3129
3130
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3131
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3132
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3133
4.00k
            has_failure = true;
3134
4.00k
            return -1;
3135
4.00k
        }
3136
3137
4.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3138
4.25k
        sync_executor.add(
3139
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3140
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3141
2
                        LOG_WARNING("failed to recycle tablet")
3142
2
                                .tag("instance_id", instance_id_)
3143
2
                                .tag("tablet_id", tid);
3144
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3145
2
                    }
3146
4.25k
                    ++num_recycled;
3147
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3148
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3149
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3139
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3140
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3141
0
                        LOG_WARNING("failed to recycle tablet")
3142
0
                                .tag("instance_id", instance_id_)
3143
0
                                .tag("tablet_id", tid);
3144
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3145
0
                    }
3146
4.00k
                    ++num_recycled;
3147
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3148
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3149
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3139
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3140
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3141
2
                        LOG_WARNING("failed to recycle tablet")
3142
2
                                .tag("instance_id", instance_id_)
3143
2
                                .tag("tablet_id", tid);
3144
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3145
2
                    }
3146
248
                    ++num_recycled;
3147
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3148
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3149
250
                });
3150
4.25k
        return 0;
3151
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3120
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3121
8.00k
        ++num_scanned;
3122
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3123
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3124
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3125
0
            has_failure = true;
3126
0
            return -1;
3127
0
        }
3128
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3129
3130
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3131
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3132
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3133
4.00k
            has_failure = true;
3134
4.00k
            return -1;
3135
4.00k
        }
3136
3137
4.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3138
4.00k
        sync_executor.add(
3139
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3140
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3141
4.00k
                        LOG_WARNING("failed to recycle tablet")
3142
4.00k
                                .tag("instance_id", instance_id_)
3143
4.00k
                                .tag("tablet_id", tid);
3144
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3145
4.00k
                    }
3146
4.00k
                    ++num_recycled;
3147
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3148
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3149
4.00k
                });
3150
4.00k
        return 0;
3151
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3120
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3121
251
        ++num_scanned;
3122
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3123
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3124
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3125
0
            has_failure = true;
3126
0
            return -1;
3127
0
        }
3128
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3129
3130
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3131
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3132
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3133
1
            has_failure = true;
3134
1
            return -1;
3135
1
        }
3136
3137
250
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3138
250
        sync_executor.add(
3139
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3140
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3141
250
                        LOG_WARNING("failed to recycle tablet")
3142
250
                                .tag("instance_id", instance_id_)
3143
250
                                .tag("tablet_id", tid);
3144
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3145
250
                    }
3146
250
                    ++num_recycled;
3147
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3148
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3149
250
                });
3150
250
        return 0;
3151
250
    };
3152
3153
52
    auto loop_done = [&, this]() -> int {
3154
52
        int ret = 0;
3155
52
        bool finished = true;
3156
52
        bool has_empty_key = false;
3157
52
        DORIS_CLOUD_DEFER {
3158
52
            init_rs_keys.clear();
3159
52
            has_failure = false;
3160
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3157
4
        DORIS_CLOUD_DEFER {
3158
4
            init_rs_keys.clear();
3159
4
            has_failure = false;
3160
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3157
48
        DORIS_CLOUD_DEFER {
3158
48
            init_rs_keys.clear();
3159
48
            has_failure = false;
3160
48
        };
3161
52
        auto tablets_info = sync_executor.when_all(&finished);
3162
52
        if (!finished) {
3163
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3164
1
            return -1;
3165
1
        }
3166
3167
51
        size_t size_before_erase = tablets_info.size();
3168
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
3168
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
3168
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3169
51
        if (tablets_info.empty()) {
3170
2
            return size_before_erase == 0 ? 0 : -1;
3171
49
        } else if (size_before_erase != tablets_info.size()) {
3172
1
            has_empty_key = true;
3173
1
        }
3174
3175
49
        ret = has_empty_key ? -1 : 0;
3176
        // sort the vector using key's order
3177
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3178
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3179
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3177
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3178
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3179
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3177
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3178
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3179
958
        });
3180
49
        std::unique_ptr<Transaction> txn;
3181
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3182
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3183
0
            return -1;
3184
0
        }
3185
49
        std::string tablet_key_end;
3186
49
        if (!tablets_info.empty()) {
3187
49
            if (!has_empty_key && !has_failure) {
3188
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3189
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3190
47
            } else {
3191
8
                for (auto& tablet_info : tablets_info) {
3192
8
                    txn->remove(tablet_info.tablet_meta_key);
3193
8
                }
3194
2
            }
3195
49
        }
3196
49
        if (is_multi_version) {
3197
6
            for (auto& tablet_info : tablets_info) {
3198
                // Remove all versions of tablet compact stats for recycled tablet
3199
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3200
6
                LOG_INFO("remove versioned tablet compact stats key")
3201
6
                        .tag("compact_stats_key", hex(k));
3202
6
                versioned_remove_all(txn.get(), k);
3203
6
            }
3204
6
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet load stats for recycled tablet
3206
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3207
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3208
6
                versioned_remove_all(txn.get(), k);
3209
6
            }
3210
6
            for (auto& tablet_info : tablets_info) {
3211
                // Remove all versions of meta tablet for recycled tablet
3212
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3213
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3214
6
                versioned_remove_all(txn.get(), k);
3215
6
            }
3216
5
        }
3217
4.25k
        for (auto& tablet_info : tablets_info) {
3218
4.25k
            std::string k;
3219
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3220
4.25k
            txn->remove(k);
3221
4.25k
        }
3222
4.25k
        for (auto& tablet_info : tablets_info) {
3223
4.25k
            std::string k;
3224
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3225
4.25k
            txn->remove(k);
3226
4.25k
        }
3227
49
        for (auto& k : init_rs_keys) {
3228
0
            txn->remove(k);
3229
0
        }
3230
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3231
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3232
0
                         << ", err=" << err;
3233
0
            return -1;
3234
0
        }
3235
49
        return ret;
3236
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3153
4
    auto loop_done = [&, this]() -> int {
3154
4
        int ret = 0;
3155
4
        bool finished = true;
3156
4
        bool has_empty_key = false;
3157
4
        DORIS_CLOUD_DEFER {
3158
4
            init_rs_keys.clear();
3159
4
            has_failure = false;
3160
4
        };
3161
4
        auto tablets_info = sync_executor.when_all(&finished);
3162
4
        if (!finished) {
3163
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3164
0
            return -1;
3165
0
        }
3166
3167
4
        size_t size_before_erase = tablets_info.size();
3168
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3169
4
        if (tablets_info.empty()) {
3170
2
            return size_before_erase == 0 ? 0 : -1;
3171
2
        } else if (size_before_erase != tablets_info.size()) {
3172
0
            has_empty_key = true;
3173
0
        }
3174
3175
2
        ret = has_empty_key ? -1 : 0;
3176
        // sort the vector using key's order
3177
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3178
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3179
2
        });
3180
2
        std::unique_ptr<Transaction> txn;
3181
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3182
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3183
0
            return -1;
3184
0
        }
3185
2
        std::string tablet_key_end;
3186
2
        if (!tablets_info.empty()) {
3187
2
            if (!has_empty_key && !has_failure) {
3188
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3189
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3190
2
            } else {
3191
0
                for (auto& tablet_info : tablets_info) {
3192
0
                    txn->remove(tablet_info.tablet_meta_key);
3193
0
                }
3194
0
            }
3195
2
        }
3196
2
        if (is_multi_version) {
3197
0
            for (auto& tablet_info : tablets_info) {
3198
                // Remove all versions of tablet compact stats for recycled tablet
3199
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3200
0
                LOG_INFO("remove versioned tablet compact stats key")
3201
0
                        .tag("compact_stats_key", hex(k));
3202
0
                versioned_remove_all(txn.get(), k);
3203
0
            }
3204
0
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet load stats for recycled tablet
3206
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3207
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3208
0
                versioned_remove_all(txn.get(), k);
3209
0
            }
3210
0
            for (auto& tablet_info : tablets_info) {
3211
                // Remove all versions of meta tablet for recycled tablet
3212
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3213
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3214
0
                versioned_remove_all(txn.get(), k);
3215
0
            }
3216
0
        }
3217
4.00k
        for (auto& tablet_info : tablets_info) {
3218
4.00k
            std::string k;
3219
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3220
4.00k
            txn->remove(k);
3221
4.00k
        }
3222
4.00k
        for (auto& tablet_info : tablets_info) {
3223
4.00k
            std::string k;
3224
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3225
4.00k
            txn->remove(k);
3226
4.00k
        }
3227
2
        for (auto& k : init_rs_keys) {
3228
0
            txn->remove(k);
3229
0
        }
3230
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3231
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3232
0
                         << ", err=" << err;
3233
0
            return -1;
3234
0
        }
3235
2
        return ret;
3236
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clEv
Line
Count
Source
3153
48
    auto loop_done = [&, this]() -> int {
3154
48
        int ret = 0;
3155
48
        bool finished = true;
3156
48
        bool has_empty_key = false;
3157
48
        DORIS_CLOUD_DEFER {
3158
48
            init_rs_keys.clear();
3159
48
            has_failure = false;
3160
48
        };
3161
48
        auto tablets_info = sync_executor.when_all(&finished);
3162
48
        if (!finished) {
3163
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3164
1
            return -1;
3165
1
        }
3166
3167
47
        size_t size_before_erase = tablets_info.size();
3168
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3169
47
        if (tablets_info.empty()) {
3170
0
            return size_before_erase == 0 ? 0 : -1;
3171
47
        } else if (size_before_erase != tablets_info.size()) {
3172
1
            has_empty_key = true;
3173
1
        }
3174
3175
47
        ret = has_empty_key ? -1 : 0;
3176
        // sort the vector using key's order
3177
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3178
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3179
47
        });
3180
47
        std::unique_ptr<Transaction> txn;
3181
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3182
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3183
0
            return -1;
3184
0
        }
3185
47
        std::string tablet_key_end;
3186
47
        if (!tablets_info.empty()) {
3187
47
            if (!has_empty_key && !has_failure) {
3188
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3189
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3190
45
            } else {
3191
8
                for (auto& tablet_info : tablets_info) {
3192
8
                    txn->remove(tablet_info.tablet_meta_key);
3193
8
                }
3194
2
            }
3195
47
        }
3196
47
        if (is_multi_version) {
3197
6
            for (auto& tablet_info : tablets_info) {
3198
                // Remove all versions of tablet compact stats for recycled tablet
3199
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3200
6
                LOG_INFO("remove versioned tablet compact stats key")
3201
6
                        .tag("compact_stats_key", hex(k));
3202
6
                versioned_remove_all(txn.get(), k);
3203
6
            }
3204
6
            for (auto& tablet_info : tablets_info) {
3205
                // Remove all versions of tablet load stats for recycled tablet
3206
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3207
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3208
6
                versioned_remove_all(txn.get(), k);
3209
6
            }
3210
6
            for (auto& tablet_info : tablets_info) {
3211
                // Remove all versions of meta tablet for recycled tablet
3212
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3213
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3214
6
                versioned_remove_all(txn.get(), k);
3215
6
            }
3216
5
        }
3217
248
        for (auto& tablet_info : tablets_info) {
3218
248
            std::string k;
3219
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3220
248
            txn->remove(k);
3221
248
        }
3222
248
        for (auto& tablet_info : tablets_info) {
3223
248
            std::string k;
3224
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3225
248
            txn->remove(k);
3226
248
        }
3227
47
        for (auto& k : init_rs_keys) {
3228
0
            txn->remove(k);
3229
0
        }
3230
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3231
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3232
0
                         << ", err=" << err;
3233
0
            return -1;
3234
0
        }
3235
47
        return ret;
3236
47
    };
3237
3238
52
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3239
52
                               std::move(loop_done));
3240
52
    if (ret != 0) {
3241
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3242
5
        return ret;
3243
5
    }
3244
3245
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3246
47
    std::unique_ptr<Transaction> txn;
3247
47
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3248
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3249
0
        return -1;
3250
0
    }
3251
47
    txn->remove(stats_key_begin, stats_key_end);
3252
47
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3253
47
                 << " end=" << hex(stats_key_end);
3254
47
    txn->remove(job_key_begin, job_key_end);
3255
47
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3256
47
    std::string schema_key_begin, schema_key_end;
3257
47
    std::string schema_dict_key;
3258
47
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3259
47
    if (partition_id <= 0) {
3260
        // Delete schema kv of this index
3261
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3262
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3263
15
        txn->remove(schema_key_begin, schema_key_end);
3264
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3265
15
                     << " end=" << hex(schema_key_end);
3266
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3267
15
        txn->remove(schema_dict_key);
3268
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3269
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3270
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3271
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3272
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3273
15
                     << " end=" << hex(versioned_schema_key_end);
3274
15
    }
3275
3276
47
    TxnErrorCode err = txn->commit();
3277
47
    if (err != TxnErrorCode::TXN_OK) {
3278
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3279
0
                     << " err=" << err;
3280
0
        return -1;
3281
0
    }
3282
3283
47
    return ret;
3284
47
}
3285
3286
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3287
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3288
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3289
5.61k
    if (num_segments <= 0) return 0;
3290
3291
5.61k
    std::vector<std::string> file_paths;
3292
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3293
0
        return -1;
3294
0
    }
3295
3296
    // Process inverted indexes
3297
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3298
    // default format as v1.
3299
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3300
5.61k
    bool delete_rowset_data_by_prefix = false;
3301
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3302
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3303
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3304
0
        delete_rowset_data_by_prefix = true;
3305
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3306
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3307
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3308
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3309
10.0k
            }
3310
10.0k
        }
3311
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3312
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3313
2.00k
        }
3314
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3315
        // schema version and index id are not found, delete rowset data by prefix directly.
3316
0
        delete_rowset_data_by_prefix = true;
3317
809
    } else {
3318
        // otherwise, try to get schema kv
3319
809
        InvertedIndexInfo index_info;
3320
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3321
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3322
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3323
809
                                 &inverted_index_get_ret);
3324
809
        if (inverted_index_get_ret == 0) {
3325
809
            index_format = index_info.first;
3326
809
            index_ids = index_info.second;
3327
809
        } else if (inverted_index_get_ret == 1) {
3328
            // 1. Schema kv not found means tablet has been recycled
3329
            // Maybe some tablet recycle failed by some bugs
3330
            // We need to delete again to double check
3331
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3332
            // because we are uncertain about the inverted index information.
3333
            // If there are inverted indexes, some data might not be deleted,
3334
            // but this is acceptable as we have made our best effort to delete the data.
3335
0
            LOG_INFO(
3336
0
                    "delete rowset data schema kv not found, need to delete again to double "
3337
0
                    "check")
3338
0
                    .tag("instance_id", instance_id_)
3339
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3340
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3341
            // Currently index_ids is guaranteed to be empty,
3342
            // but we clear it again here as a safeguard against future code changes
3343
            // that might cause index_ids to no longer be empty
3344
0
            index_format = InvertedIndexStorageFormatPB::V2;
3345
0
            index_ids.clear();
3346
0
        } else {
3347
            // failed to get schema kv, delete rowset data by prefix directly.
3348
0
            delete_rowset_data_by_prefix = true;
3349
0
        }
3350
809
    }
3351
3352
5.61k
    if (delete_rowset_data_by_prefix) {
3353
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3354
0
                                  rs_meta_pb.rowset_id_v2());
3355
0
    }
3356
3357
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3358
5.61k
    if (it == accessor_map_.end()) {
3359
1.59k
        LOG_WARNING("instance has no such resource id")
3360
1.59k
                .tag("instance_id", instance_id_)
3361
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3362
1.59k
        return -1;
3363
1.59k
    }
3364
4.01k
    auto& accessor = it->second;
3365
3366
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3367
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3368
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3369
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3370
20.0k
                                         &file_paths);
3371
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3372
40.0k
            for (const auto& index_id : index_ids) {
3373
40.0k
                add_file_to_delete_if_not_packed(
3374
40.0k
                        rs_meta_pb,
3375
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3376
40.0k
                                               index_id.second),
3377
40.0k
                        &file_paths);
3378
40.0k
            }
3379
20.0k
        } else if (!index_ids.empty()) {
3380
0
            add_file_to_delete_if_not_packed(
3381
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3382
0
        }
3383
20.0k
    }
3384
3385
    // Process delete bitmap - check where it's stored.
3386
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3387
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3388
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3389
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3390
0
                .tag("instance_id", instance_id_)
3391
0
                .tag("tablet_id", tablet_id)
3392
0
                .tag("rowset_id", rowset_id);
3393
0
        return -1;
3394
0
    }
3395
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3396
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3397
2.00k
    }
3398
    // TODO(AlexYue): seems could do do batch
3399
4.01k
    return accessor->delete_files(file_paths);
3400
4.01k
}
3401
3402
62.3k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3403
62.3k
    LOG_INFO("begin process_packed_file_location_index")
3404
62.3k
            .tag("instance_id", instance_id_)
3405
62.3k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3406
62.3k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3407
62.3k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3408
62.3k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3409
62.3k
    if (index_map.empty()) {
3410
62.3k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3411
62.3k
                .tag("instance_id", instance_id_)
3412
62.3k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3413
62.3k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3414
62.3k
        return 0;
3415
62.3k
    }
3416
3417
19
    struct PackedSmallFileInfo {
3418
19
        std::string small_file_path;
3419
19
    };
3420
19
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3421
19
    packed_file_updates.reserve(index_map.size());
3422
27
    for (const auto& [small_path, index_pb] : index_map) {
3423
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3424
0
            continue;
3425
0
        }
3426
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3427
27
                PackedSmallFileInfo {small_path});
3428
27
    }
3429
19
    if (packed_file_updates.empty()) {
3430
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3431
0
                .tag("instance_id", instance_id_)
3432
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3433
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3434
0
                .tag("index_map_size", index_map.size());
3435
0
        return 0;
3436
0
    }
3437
3438
19
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3439
19
    int ret = 0;
3440
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3441
24
        if (small_files.empty()) {
3442
0
            continue;
3443
0
        }
3444
3445
24
        bool success = false;
3446
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3447
24
            std::unique_ptr<Transaction> txn;
3448
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3449
24
            if (err != TxnErrorCode::TXN_OK) {
3450
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3451
0
                        .tag("instance_id", instance_id_)
3452
0
                        .tag("packed_file_path", packed_file_path)
3453
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3454
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3455
0
                        .tag("err", err);
3456
0
                ret = -1;
3457
0
                break;
3458
0
            }
3459
3460
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3461
24
            std::string packed_val;
3462
24
            err = txn->get(packed_key, &packed_val);
3463
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3464
0
                LOG_WARNING("packed file info not found when recycling rowset")
3465
0
                        .tag("instance_id", instance_id_)
3466
0
                        .tag("packed_file_path", packed_file_path)
3467
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3468
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3469
0
                        .tag("key", hex(packed_key))
3470
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3471
                // Skip this packed file entry and continue with others
3472
0
                success = true;
3473
0
                break;
3474
0
            }
3475
24
            if (err != TxnErrorCode::TXN_OK) {
3476
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3477
0
                        .tag("instance_id", instance_id_)
3478
0
                        .tag("packed_file_path", packed_file_path)
3479
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3480
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3481
0
                        .tag("err", err);
3482
0
                ret = -1;
3483
0
                break;
3484
0
            }
3485
3486
24
            cloud::PackedFileInfoPB packed_info;
3487
24
            if (!packed_info.ParseFromString(packed_val)) {
3488
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3489
0
                        .tag("instance_id", instance_id_)
3490
0
                        .tag("packed_file_path", packed_file_path)
3491
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3492
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3493
0
                ret = -1;
3494
0
                break;
3495
0
            }
3496
3497
24
            LOG_INFO("packed file update check")
3498
24
                    .tag("instance_id", instance_id_)
3499
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3500
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3501
24
                    .tag("merged_file_path", packed_file_path)
3502
24
                    .tag("requested_small_files", small_files.size())
3503
24
                    .tag("merge_entries", packed_info.slices_size());
3504
3505
24
            auto* small_file_entries = packed_info.mutable_slices();
3506
24
            int64_t changed_files = 0;
3507
24
            int64_t missing_entries = 0;
3508
24
            int64_t already_deleted = 0;
3509
27
            for (const auto& small_file_info : small_files) {
3510
27
                bool found = false;
3511
87
                for (auto& small_file_entry : *small_file_entries) {
3512
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3513
27
                        if (!small_file_entry.deleted()) {
3514
27
                            small_file_entry.set_deleted(true);
3515
27
                            if (!small_file_entry.corrected()) {
3516
27
                                small_file_entry.set_corrected(true);
3517
27
                            }
3518
27
                            ++changed_files;
3519
27
                        } else {
3520
0
                            ++already_deleted;
3521
0
                        }
3522
27
                        found = true;
3523
27
                        break;
3524
27
                    }
3525
87
                }
3526
27
                if (!found) {
3527
0
                    ++missing_entries;
3528
0
                    LOG_WARNING("packed file info missing small file entry")
3529
0
                            .tag("instance_id", instance_id_)
3530
0
                            .tag("packed_file_path", packed_file_path)
3531
0
                            .tag("small_file_path", small_file_info.small_file_path)
3532
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3533
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3534
0
                }
3535
27
            }
3536
3537
24
            if (changed_files == 0) {
3538
0
                LOG_INFO("skip merge file update: no merge entries changed")
3539
0
                        .tag("instance_id", instance_id_)
3540
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3541
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3542
0
                        .tag("merged_file_path", packed_file_path)
3543
0
                        .tag("missing_entries", missing_entries)
3544
0
                        .tag("already_deleted", already_deleted)
3545
0
                        .tag("requested_small_files", small_files.size())
3546
0
                        .tag("merge_entries", packed_info.slices_size());
3547
0
                success = true;
3548
0
                break;
3549
0
            }
3550
3551
            // Calculate remaining files
3552
24
            int64_t left_file_count = 0;
3553
24
            int64_t left_file_bytes = 0;
3554
141
            for (const auto& small_file_entry : packed_info.slices()) {
3555
141
                if (!small_file_entry.deleted()) {
3556
57
                    ++left_file_count;
3557
57
                    left_file_bytes += small_file_entry.size();
3558
57
                }
3559
141
            }
3560
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3561
24
            packed_info.set_ref_cnt(left_file_count);
3562
24
            LOG_INFO("updated packed file reference info")
3563
24
                    .tag("instance_id", instance_id_)
3564
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3565
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3566
24
                    .tag("packed_file_path", packed_file_path)
3567
24
                    .tag("ref_cnt", left_file_count)
3568
24
                    .tag("left_file_bytes", left_file_bytes);
3569
3570
24
            if (left_file_count == 0) {
3571
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3572
7
            }
3573
3574
24
            std::string updated_val;
3575
24
            if (!packed_info.SerializeToString(&updated_val)) {
3576
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3577
0
                        .tag("instance_id", instance_id_)
3578
0
                        .tag("packed_file_path", packed_file_path)
3579
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3580
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3581
0
                ret = -1;
3582
0
                break;
3583
0
            }
3584
3585
24
            txn->put(packed_key, updated_val);
3586
24
            err = txn->commit();
3587
24
            if (err == TxnErrorCode::TXN_OK) {
3588
24
                success = true;
3589
24
                if (left_file_count == 0) {
3590
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3591
7
                            .tag("instance_id", instance_id_)
3592
7
                            .tag("packed_file_path", packed_file_path);
3593
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3594
0
                        ret = -1;
3595
0
                    }
3596
7
                }
3597
24
                break;
3598
24
            }
3599
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3600
0
                if (attempt >= max_retry_times) {
3601
0
                    LOG_WARNING("packed file info update conflict after max retry")
3602
0
                            .tag("instance_id", instance_id_)
3603
0
                            .tag("packed_file_path", packed_file_path)
3604
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3605
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3606
0
                            .tag("changed_files", changed_files)
3607
0
                            .tag("attempt", attempt);
3608
0
                    ret = -1;
3609
0
                    break;
3610
0
                }
3611
0
                LOG_WARNING("packed file info update conflict, retrying")
3612
0
                        .tag("instance_id", instance_id_)
3613
0
                        .tag("packed_file_path", packed_file_path)
3614
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3615
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3616
0
                        .tag("changed_files", changed_files)
3617
0
                        .tag("attempt", attempt);
3618
0
                sleep_for_packed_file_retry();
3619
0
                continue;
3620
0
            }
3621
3622
0
            LOG_WARNING("failed to commit packed file info update")
3623
0
                    .tag("instance_id", instance_id_)
3624
0
                    .tag("packed_file_path", packed_file_path)
3625
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3626
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3627
0
                    .tag("err", err)
3628
0
                    .tag("changed_files", changed_files);
3629
0
            ret = -1;
3630
0
            break;
3631
0
        }
3632
3633
24
        if (!success) {
3634
0
            ret = -1;
3635
0
        }
3636
24
    }
3637
3638
19
    return ret;
3639
19
}
3640
3641
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3642
        int64_t tablet_id, const std::string& rowset_id,
3643
58.2k
        DeleteBitmapStorageType* out_storage_type) {
3644
58.2k
    if (out_storage_type) {
3645
58.2k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3646
58.2k
    }
3647
3648
    // Get delete bitmap storage info from FDB
3649
58.2k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3650
58.2k
    std::unique_ptr<Transaction> txn;
3651
58.2k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3652
58.2k
    if (err != TxnErrorCode::TXN_OK) {
3653
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3654
0
                .tag("instance_id", instance_id_)
3655
0
                .tag("tablet_id", tablet_id)
3656
0
                .tag("rowset_id", rowset_id)
3657
0
                .tag("err", err);
3658
0
        return -1;
3659
0
    }
3660
3661
58.2k
    std::string dbm_val;
3662
58.2k
    err = txn->get(dbm_key, &dbm_val);
3663
58.2k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3664
        // No delete bitmap for this rowset, nothing to do
3665
4.63k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3666
4.63k
                .tag("instance_id", instance_id_)
3667
4.63k
                .tag("tablet_id", tablet_id)
3668
4.63k
                .tag("rowset_id", rowset_id);
3669
4.63k
        return 0;
3670
4.63k
    }
3671
53.5k
    if (err != TxnErrorCode::TXN_OK) {
3672
0
        LOG_WARNING("failed to get delete bitmap storage")
3673
0
                .tag("instance_id", instance_id_)
3674
0
                .tag("tablet_id", tablet_id)
3675
0
                .tag("rowset_id", rowset_id)
3676
0
                .tag("err", err);
3677
0
        return -1;
3678
0
    }
3679
3680
53.5k
    DeleteBitmapStoragePB storage;
3681
53.5k
    if (!storage.ParseFromString(dbm_val)) {
3682
0
        LOG_WARNING("failed to parse delete bitmap storage")
3683
0
                .tag("instance_id", instance_id_)
3684
0
                .tag("tablet_id", tablet_id)
3685
0
                .tag("rowset_id", rowset_id);
3686
0
        return -1;
3687
0
    }
3688
3689
53.5k
    if (storage.store_in_fdb()) {
3690
0
        if (out_storage_type) {
3691
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
3692
0
        }
3693
0
        return 0;
3694
0
    }
3695
3696
    // Check if delete bitmap is stored in standalone file.
3697
53.5k
    if (!storage.has_packed_slice_location() ||
3698
53.5k
        storage.packed_slice_location().packed_file_path().empty()) {
3699
53.5k
        if (out_storage_type) {
3700
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
3701
53.5k
        }
3702
53.5k
        return 0;
3703
53.5k
    }
3704
3705
18.4E
    if (out_storage_type) {
3706
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
3707
0
    }
3708
3709
18.4E
    const auto& packed_loc = storage.packed_slice_location();
3710
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
3711
3712
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
3713
18.4E
            .tag("instance_id", instance_id_)
3714
18.4E
            .tag("tablet_id", tablet_id)
3715
18.4E
            .tag("rowset_id", rowset_id)
3716
18.4E
            .tag("packed_file_path", packed_file_path);
3717
3718
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3719
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3720
0
        std::unique_ptr<Transaction> update_txn;
3721
0
        err = txn_kv_->create_txn(&update_txn);
3722
0
        if (err != TxnErrorCode::TXN_OK) {
3723
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
3724
0
                    .tag("instance_id", instance_id_)
3725
0
                    .tag("tablet_id", tablet_id)
3726
0
                    .tag("rowset_id", rowset_id)
3727
0
                    .tag("err", err);
3728
0
            return -1;
3729
0
        }
3730
3731
0
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3732
0
        std::string packed_val;
3733
0
        err = update_txn->get(packed_key, &packed_val);
3734
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3735
0
            LOG_WARNING("packed file info not found for delete bitmap")
3736
0
                    .tag("instance_id", instance_id_)
3737
0
                    .tag("tablet_id", tablet_id)
3738
0
                    .tag("rowset_id", rowset_id)
3739
0
                    .tag("packed_file_path", packed_file_path);
3740
0
            return 0;
3741
0
        }
3742
0
        if (err != TxnErrorCode::TXN_OK) {
3743
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
3744
0
                    .tag("instance_id", instance_id_)
3745
0
                    .tag("tablet_id", tablet_id)
3746
0
                    .tag("rowset_id", rowset_id)
3747
0
                    .tag("packed_file_path", packed_file_path)
3748
0
                    .tag("err", err);
3749
0
            return -1;
3750
0
        }
3751
3752
0
        cloud::PackedFileInfoPB packed_info;
3753
0
        if (!packed_info.ParseFromString(packed_val)) {
3754
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
3755
0
                    .tag("instance_id", instance_id_)
3756
0
                    .tag("tablet_id", tablet_id)
3757
0
                    .tag("rowset_id", rowset_id)
3758
0
                    .tag("packed_file_path", packed_file_path);
3759
0
            return -1;
3760
0
        }
3761
3762
        // Find and mark the small file entry as deleted
3763
        // Use tablet_id and rowset_id to match entry instead of path,
3764
        // because path format may vary with path_version (with or without shard prefix)
3765
0
        auto* entries = packed_info.mutable_slices();
3766
0
        bool found = false;
3767
0
        bool already_deleted = false;
3768
0
        for (auto& entry : *entries) {
3769
0
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
3770
0
                if (!entry.deleted()) {
3771
0
                    entry.set_deleted(true);
3772
0
                    if (!entry.corrected()) {
3773
0
                        entry.set_corrected(true);
3774
0
                    }
3775
0
                } else {
3776
0
                    already_deleted = true;
3777
0
                }
3778
0
                found = true;
3779
0
                break;
3780
0
            }
3781
0
        }
3782
3783
0
        if (!found) {
3784
0
            LOG_WARNING("delete bitmap entry not found in packed file")
3785
0
                    .tag("instance_id", instance_id_)
3786
0
                    .tag("tablet_id", tablet_id)
3787
0
                    .tag("rowset_id", rowset_id)
3788
0
                    .tag("packed_file_path", packed_file_path);
3789
0
            return 0;
3790
0
        }
3791
3792
0
        if (already_deleted) {
3793
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
3794
0
                    .tag("instance_id", instance_id_)
3795
0
                    .tag("tablet_id", tablet_id)
3796
0
                    .tag("rowset_id", rowset_id)
3797
0
                    .tag("packed_file_path", packed_file_path);
3798
0
            return 0;
3799
0
        }
3800
3801
        // Calculate remaining files
3802
0
        int64_t left_file_count = 0;
3803
0
        int64_t left_file_bytes = 0;
3804
0
        for (const auto& entry : packed_info.slices()) {
3805
0
            if (!entry.deleted()) {
3806
0
                ++left_file_count;
3807
0
                left_file_bytes += entry.size();
3808
0
            }
3809
0
        }
3810
0
        packed_info.set_remaining_slice_bytes(left_file_bytes);
3811
0
        packed_info.set_ref_cnt(left_file_count);
3812
3813
0
        if (left_file_count == 0) {
3814
0
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3815
0
        }
3816
3817
0
        std::string updated_val;
3818
0
        if (!packed_info.SerializeToString(&updated_val)) {
3819
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
3820
0
                    .tag("instance_id", instance_id_)
3821
0
                    .tag("tablet_id", tablet_id)
3822
0
                    .tag("rowset_id", rowset_id)
3823
0
                    .tag("packed_file_path", packed_file_path);
3824
0
            return -1;
3825
0
        }
3826
3827
0
        update_txn->put(packed_key, updated_val);
3828
0
        err = update_txn->commit();
3829
0
        if (err == TxnErrorCode::TXN_OK) {
3830
0
            LOG_INFO("delete bitmap packed file ref count decremented")
3831
0
                    .tag("instance_id", instance_id_)
3832
0
                    .tag("tablet_id", tablet_id)
3833
0
                    .tag("rowset_id", rowset_id)
3834
0
                    .tag("packed_file_path", packed_file_path)
3835
0
                    .tag("left_file_count", left_file_count);
3836
0
            if (left_file_count == 0) {
3837
0
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3838
0
                    return -1;
3839
0
                }
3840
0
            }
3841
0
            return 0;
3842
0
        }
3843
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3844
0
            if (attempt >= max_retry_times) {
3845
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
3846
0
                        .tag("instance_id", instance_id_)
3847
0
                        .tag("tablet_id", tablet_id)
3848
0
                        .tag("rowset_id", rowset_id)
3849
0
                        .tag("packed_file_path", packed_file_path)
3850
0
                        .tag("attempt", attempt);
3851
0
                return -1;
3852
0
            }
3853
0
            sleep_for_packed_file_retry();
3854
0
            continue;
3855
0
        }
3856
3857
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
3858
0
                .tag("instance_id", instance_id_)
3859
0
                .tag("tablet_id", tablet_id)
3860
0
                .tag("rowset_id", rowset_id)
3861
0
                .tag("packed_file_path", packed_file_path)
3862
0
                .tag("err", err);
3863
0
        return -1;
3864
0
    }
3865
3866
18.4E
    return -1;
3867
18.4E
}
3868
3869
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
3870
                                                const std::string& packed_key,
3871
7
                                                const cloud::PackedFileInfoPB& packed_info) {
3872
7
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
3873
0
        LOG_WARNING("packed file missing resource id when recycling")
3874
0
                .tag("instance_id", instance_id_)
3875
0
                .tag("packed_file_path", packed_file_path);
3876
0
        return -1;
3877
0
    }
3878
3879
7
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
3880
7
    if (!accessor) {
3881
0
        LOG_WARNING("no accessor available to delete packed file")
3882
0
                .tag("instance_id", instance_id_)
3883
0
                .tag("packed_file_path", packed_file_path)
3884
0
                .tag("resource_id", packed_info.resource_id());
3885
0
        return -1;
3886
0
    }
3887
3888
7
    int del_ret = accessor->delete_file(packed_file_path);
3889
7
    if (del_ret != 0 && del_ret != 1) {
3890
0
        LOG_WARNING("failed to delete packed file")
3891
0
                .tag("instance_id", instance_id_)
3892
0
                .tag("packed_file_path", packed_file_path)
3893
0
                .tag("resource_id", resource_id)
3894
0
                .tag("ret", del_ret);
3895
0
        return -1;
3896
0
    }
3897
7
    if (del_ret == 1) {
3898
0
        LOG_INFO("packed file already removed")
3899
0
                .tag("instance_id", instance_id_)
3900
0
                .tag("packed_file_path", packed_file_path)
3901
0
                .tag("resource_id", resource_id);
3902
7
    } else {
3903
7
        LOG_INFO("deleted packed file")
3904
7
                .tag("instance_id", instance_id_)
3905
7
                .tag("packed_file_path", packed_file_path)
3906
7
                .tag("resource_id", resource_id);
3907
7
    }
3908
3909
7
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
3910
7
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3911
7
        std::unique_ptr<Transaction> del_txn;
3912
7
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
3913
7
        if (err != TxnErrorCode::TXN_OK) {
3914
0
            LOG_WARNING("failed to create txn when removing packed file kv")
3915
0
                    .tag("instance_id", instance_id_)
3916
0
                    .tag("packed_file_path", packed_file_path)
3917
0
                    .tag("attempt", attempt)
3918
0
                    .tag("err", err);
3919
0
            return -1;
3920
0
        }
3921
3922
7
        std::string latest_val;
3923
7
        err = del_txn->get(packed_key, &latest_val);
3924
7
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3925
0
            return 0;
3926
0
        }
3927
7
        if (err != TxnErrorCode::TXN_OK) {
3928
0
            LOG_WARNING("failed to re-read packed file kv before removal")
3929
0
                    .tag("instance_id", instance_id_)
3930
0
                    .tag("packed_file_path", packed_file_path)
3931
0
                    .tag("attempt", attempt)
3932
0
                    .tag("err", err);
3933
0
            return -1;
3934
0
        }
3935
3936
7
        cloud::PackedFileInfoPB latest_info;
3937
7
        if (!latest_info.ParseFromString(latest_val)) {
3938
0
            LOG_WARNING("failed to parse packed file info before removal")
3939
0
                    .tag("instance_id", instance_id_)
3940
0
                    .tag("packed_file_path", packed_file_path)
3941
0
                    .tag("attempt", attempt);
3942
0
            return -1;
3943
0
        }
3944
3945
7
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
3946
7
              latest_info.ref_cnt() == 0)) {
3947
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
3948
0
                    .tag("instance_id", instance_id_)
3949
0
                    .tag("packed_file_path", packed_file_path)
3950
0
                    .tag("attempt", attempt);
3951
0
            return 0;
3952
0
        }
3953
3954
7
        del_txn->remove(packed_key);
3955
7
        err = del_txn->commit();
3956
7
        if (err == TxnErrorCode::TXN_OK) {
3957
7
            LOG_INFO("removed packed file metadata")
3958
7
                    .tag("instance_id", instance_id_)
3959
7
                    .tag("packed_file_path", packed_file_path);
3960
7
            return 0;
3961
7
        }
3962
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
3963
0
            if (attempt >= max_retry_times) {
3964
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
3965
0
                        .tag("instance_id", instance_id_)
3966
0
                        .tag("packed_file_path", packed_file_path)
3967
0
                        .tag("attempt", attempt);
3968
0
                return -1;
3969
0
            }
3970
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
3971
0
                    .tag("instance_id", instance_id_)
3972
0
                    .tag("packed_file_path", packed_file_path)
3973
0
                    .tag("attempt", attempt);
3974
0
            sleep_for_packed_file_retry();
3975
0
            continue;
3976
0
        }
3977
0
        LOG_WARNING("failed to remove packed file kv")
3978
0
                .tag("instance_id", instance_id_)
3979
0
                .tag("packed_file_path", packed_file_path)
3980
0
                .tag("attempt", attempt)
3981
0
                .tag("err", err);
3982
0
        return -1;
3983
0
    }
3984
0
    return -1;
3985
7
}
3986
3987
int InstanceRecycler::delete_rowset_data(
3988
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
3989
67
        RecyclerMetricsContext& metrics_context) {
3990
67
    int ret = 0;
3991
    // resource_id -> file_paths
3992
67
    std::map<std::string, std::vector<std::string>> resource_file_paths;
3993
    // (resource_id, tablet_id, rowset_id)
3994
67
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
3995
67
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
3996
3997
56.1k
    for (const auto& [_, rs] : rowsets) {
3998
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
3999
        // due to aborted schema change.
4000
56.1k
        if (is_formal_rowset) {
4001
3.15k
            std::lock_guard lock(recycled_tablets_mtx_);
4002
3.15k
            if (recycled_tablets_.count(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4003
                // Tablet has been recycled and this rowset has no packed slices, so file data
4004
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4005
                // slice info must still run to decrement packed file ref counts.
4006
0
                continue;
4007
0
            }
4008
3.15k
        }
4009
4010
56.1k
        int64_t num_segments = rs.num_segments();
4011
        // Check num_segments before accessor lookup, because empty rowsets
4012
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4013
        // set. Skipping them early avoids a spurious "no such resource id" error
4014
        // that marks the entire batch as failed and prevents txn_remove from
4015
        // cleaning up recycle KV keys.
4016
56.1k
        if (num_segments <= 0) {
4017
0
            metrics_context.total_recycled_num++;
4018
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4019
0
            continue;
4020
0
        }
4021
4022
56.1k
        auto it = accessor_map_.find(rs.resource_id());
4023
        // possible if the accessor is not initilized correctly
4024
56.1k
        if (it == accessor_map_.end()) [[unlikely]] {
4025
2.00k
            LOG_WARNING("instance has no such resource id")
4026
2.00k
                    .tag("instance_id", instance_id_)
4027
2.00k
                    .tag("resource_id", rs.resource_id());
4028
2.00k
            ret = -1;
4029
2.00k
            continue;
4030
2.00k
        }
4031
4032
54.1k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4033
54.1k
        const auto& rowset_id = rs.rowset_id_v2();
4034
54.1k
        int64_t tablet_id = rs.tablet_id();
4035
54.1k
        LOG_INFO("recycle rowset merge index size")
4036
54.1k
                .tag("instance_id", instance_id_)
4037
54.1k
                .tag("tablet_id", tablet_id)
4038
54.1k
                .tag("rowset_id", rowset_id)
4039
54.1k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4040
54.1k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4041
0
            ret = -1;
4042
0
            continue;
4043
0
        }
4044
4045
        // Process delete bitmap - check where it's stored.
4046
54.1k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4047
54.1k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4048
54.1k
                                                           &delete_bitmap_storage_type) != 0) {
4049
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4050
0
                    .tag("instance_id", instance_id_)
4051
0
                    .tag("tablet_id", tablet_id)
4052
0
                    .tag("rowset_id", rowset_id);
4053
0
            ret = -1;
4054
0
            continue;
4055
0
        }
4056
54.1k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4057
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4058
51.5k
        }
4059
4060
        // Process inverted indexes
4061
54.1k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4062
        // default format as v1.
4063
54.1k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4064
54.1k
        int inverted_index_get_ret = 0;
4065
54.1k
        if (rs.has_tablet_schema()) {
4066
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4067
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4068
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4069
53.5k
                }
4070
53.5k
            }
4071
26.6k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4072
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4073
26.5k
            }
4074
27.5k
        } else {
4075
27.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4076
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4077
0
                                "instance_id="
4078
0
                             << instance_id_ << " tablet_id=" << tablet_id
4079
0
                             << " rowset_id=" << rowset_id;
4080
0
                ret = -1;
4081
0
                continue;
4082
0
            }
4083
27.5k
            InvertedIndexInfo index_info;
4084
27.5k
            inverted_index_get_ret =
4085
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4086
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4087
27.5k
                                     &inverted_index_get_ret);
4088
27.5k
            if (inverted_index_get_ret == 0) {
4089
27.0k
                index_format = index_info.first;
4090
27.0k
                index_ids = index_info.second;
4091
27.0k
            } else if (inverted_index_get_ret == 1) {
4092
                // 1. Schema kv not found means tablet has been recycled
4093
                // Maybe some tablet recycle failed by some bugs
4094
                // We need to delete again to double check
4095
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4096
                // because we are uncertain about the inverted index information.
4097
                // If there are inverted indexes, some data might not be deleted,
4098
                // but this is acceptable as we have made our best effort to delete the data.
4099
507
                LOG_INFO(
4100
507
                        "delete rowset data schema kv not found, need to delete again to "
4101
507
                        "double "
4102
507
                        "check")
4103
507
                        .tag("instance_id", instance_id_)
4104
507
                        .tag("tablet_id", tablet_id)
4105
507
                        .tag("rowset", rs.ShortDebugString());
4106
                // Currently index_ids is guaranteed to be empty,
4107
                // but we clear it again here as a safeguard against future code changes
4108
                // that might cause index_ids to no longer be empty
4109
507
                index_format = InvertedIndexStorageFormatPB::V2;
4110
507
                index_ids.clear();
4111
18.4E
            } else {
4112
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4113
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4114
18.4E
                ret = -1;
4115
18.4E
                continue;
4116
18.4E
            }
4117
27.5k
        }
4118
54.2k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4119
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4120
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4121
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4122
5
            continue;
4123
5
        }
4124
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4125
269k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4126
269k
                                             &file_paths);
4127
269k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4128
536k
                for (const auto& index_id : index_ids) {
4129
536k
                    add_file_to_delete_if_not_packed(
4130
536k
                            rs,
4131
536k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4132
536k
                                                   index_id.second),
4133
536k
                            &file_paths);
4134
536k
                }
4135
267k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4136
                // try to recycle inverted index v2 when get_ret == 1
4137
                // we treat schema not found as if it has a v2 format inverted index
4138
                // to reduce chance of data leakage
4139
2.50k
                if (inverted_index_get_ret == 1) {
4140
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4141
2.50k
                            .tag("instance_id", instance_id_)
4142
2.50k
                            .tag("inverted index v2 path",
4143
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4144
2.50k
                }
4145
2.50k
                add_file_to_delete_if_not_packed(
4146
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4147
2.50k
            }
4148
269k
        }
4149
54.1k
    }
4150
4151
67
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4152
67
                                                 "delete_rowset_data",
4153
67
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clERKi
Line
Count
Source
4153
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
4153
51
                                                 [](const int& ret) { return ret != 0; });
4154
67
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4155
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4156
51
            DCHECK(accessor_map_.count(*rid))
4157
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4158
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4159
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4160
51
                                     &accessor_map_);
4161
51
            if (!accessor_map_.contains(*rid)) {
4162
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4163
0
                        .tag("resource_id", resource_id)
4164
0
                        .tag("instance_id", instance_id_);
4165
0
                return -1;
4166
0
            }
4167
51
            auto& accessor = accessor_map_[*rid];
4168
51
            int ret = accessor->delete_files(*paths);
4169
51
            if (!ret) {
4170
                // deduplication of different files with the same rowset id
4171
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4172
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4173
51
                std::set<std::string> deleted_rowset_id;
4174
4175
51
                std::for_each(paths->begin(), paths->end(),
4176
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4177
856k
                               this](const std::string& path) {
4178
856k
                                  std::vector<std::string> str;
4179
856k
                                  butil::SplitString(path, '/', &str);
4180
856k
                                  std::string rowset_id;
4181
856k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4182
851k
                                      rowset_id = str.back().substr(0, pos);
4183
851k
                                  } else {
4184
4.61k
                                      if (path.find("packed_file/") != std::string::npos) {
4185
0
                                          return; // packed files do not have rowset_id encoded
4186
0
                                      }
4187
4.61k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4188
4.61k
                                      return;
4189
4.61k
                                  }
4190
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4191
851k
                                  if (rs_meta != rowsets.end() &&
4192
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4193
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4194
54.1k
                                      metrics_context.total_recycled_data_size +=
4195
54.1k
                                              rs_meta->second.total_disk_size();
4196
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4197
54.1k
                                              rs_meta->second.num_segments();
4198
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4199
54.1k
                                              rs_meta->second.total_disk_size();
4200
54.1k
                                      metrics_context.total_recycled_num++;
4201
54.1k
                                  }
4202
851k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4177
7
                               this](const std::string& path) {
4178
7
                                  std::vector<std::string> str;
4179
7
                                  butil::SplitString(path, '/', &str);
4180
7
                                  std::string rowset_id;
4181
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4182
7
                                      rowset_id = str.back().substr(0, pos);
4183
7
                                  } else {
4184
0
                                      if (path.find("packed_file/") != std::string::npos) {
4185
0
                                          return; // packed files do not have rowset_id encoded
4186
0
                                      }
4187
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4188
0
                                      return;
4189
0
                                  }
4190
7
                                  auto rs_meta = rowsets.find(rowset_id);
4191
7
                                  if (rs_meta != rowsets.end() &&
4192
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4193
7
                                      deleted_rowset_id.emplace(rowset_id);
4194
7
                                      metrics_context.total_recycled_data_size +=
4195
7
                                              rs_meta->second.total_disk_size();
4196
7
                                      segment_metrics_context_.total_recycled_num +=
4197
7
                                              rs_meta->second.num_segments();
4198
7
                                      segment_metrics_context_.total_recycled_data_size +=
4199
7
                                              rs_meta->second.total_disk_size();
4200
7
                                      metrics_context.total_recycled_num++;
4201
7
                                  }
4202
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlRSD_E_clESN_
Line
Count
Source
4177
856k
                               this](const std::string& path) {
4178
856k
                                  std::vector<std::string> str;
4179
856k
                                  butil::SplitString(path, '/', &str);
4180
856k
                                  std::string rowset_id;
4181
856k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4182
851k
                                      rowset_id = str.back().substr(0, pos);
4183
851k
                                  } else {
4184
4.61k
                                      if (path.find("packed_file/") != std::string::npos) {
4185
0
                                          return; // packed files do not have rowset_id encoded
4186
0
                                      }
4187
4.61k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4188
4.61k
                                      return;
4189
4.61k
                                  }
4190
851k
                                  auto rs_meta = rowsets.find(rowset_id);
4191
851k
                                  if (rs_meta != rowsets.end() &&
4192
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4193
54.1k
                                      deleted_rowset_id.emplace(rowset_id);
4194
54.1k
                                      metrics_context.total_recycled_data_size +=
4195
54.1k
                                              rs_meta->second.total_disk_size();
4196
54.1k
                                      segment_metrics_context_.total_recycled_num +=
4197
54.1k
                                              rs_meta->second.num_segments();
4198
54.1k
                                      segment_metrics_context_.total_recycled_data_size +=
4199
54.1k
                                              rs_meta->second.total_disk_size();
4200
54.1k
                                      metrics_context.total_recycled_num++;
4201
54.1k
                                  }
4202
851k
                              });
4203
51
            }
4204
51
            return ret;
4205
51
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4155
5
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4156
5
            DCHECK(accessor_map_.count(*rid))
4157
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4158
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4159
5
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4160
5
                                     &accessor_map_);
4161
5
            if (!accessor_map_.contains(*rid)) {
4162
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4163
0
                        .tag("resource_id", resource_id)
4164
0
                        .tag("instance_id", instance_id_);
4165
0
                return -1;
4166
0
            }
4167
5
            auto& accessor = accessor_map_[*rid];
4168
5
            int ret = accessor->delete_files(*paths);
4169
5
            if (!ret) {
4170
                // deduplication of different files with the same rowset id
4171
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4172
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4173
5
                std::set<std::string> deleted_rowset_id;
4174
4175
5
                std::for_each(paths->begin(), paths->end(),
4176
5
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4177
5
                               this](const std::string& path) {
4178
5
                                  std::vector<std::string> str;
4179
5
                                  butil::SplitString(path, '/', &str);
4180
5
                                  std::string rowset_id;
4181
5
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4182
5
                                      rowset_id = str.back().substr(0, pos);
4183
5
                                  } else {
4184
5
                                      if (path.find("packed_file/") != std::string::npos) {
4185
5
                                          return; // packed files do not have rowset_id encoded
4186
5
                                      }
4187
5
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4188
5
                                      return;
4189
5
                                  }
4190
5
                                  auto rs_meta = rowsets.find(rowset_id);
4191
5
                                  if (rs_meta != rowsets.end() &&
4192
5
                                      !deleted_rowset_id.contains(rowset_id)) {
4193
5
                                      deleted_rowset_id.emplace(rowset_id);
4194
5
                                      metrics_context.total_recycled_data_size +=
4195
5
                                              rs_meta->second.total_disk_size();
4196
5
                                      segment_metrics_context_.total_recycled_num +=
4197
5
                                              rs_meta->second.num_segments();
4198
5
                                      segment_metrics_context_.total_recycled_data_size +=
4199
5
                                              rs_meta->second.total_disk_size();
4200
5
                                      metrics_context.total_recycled_num++;
4201
5
                                  }
4202
5
                              });
4203
5
            }
4204
5
            return ret;
4205
5
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4155
46
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4156
46
            DCHECK(accessor_map_.count(*rid))
4157
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4158
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4159
46
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4160
46
                                     &accessor_map_);
4161
46
            if (!accessor_map_.contains(*rid)) {
4162
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4163
0
                        .tag("resource_id", resource_id)
4164
0
                        .tag("instance_id", instance_id_);
4165
0
                return -1;
4166
0
            }
4167
46
            auto& accessor = accessor_map_[*rid];
4168
46
            int ret = accessor->delete_files(*paths);
4169
46
            if (!ret) {
4170
                // deduplication of different files with the same rowset id
4171
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4172
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4173
46
                std::set<std::string> deleted_rowset_id;
4174
4175
46
                std::for_each(paths->begin(), paths->end(),
4176
46
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4177
46
                               this](const std::string& path) {
4178
46
                                  std::vector<std::string> str;
4179
46
                                  butil::SplitString(path, '/', &str);
4180
46
                                  std::string rowset_id;
4181
46
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4182
46
                                      rowset_id = str.back().substr(0, pos);
4183
46
                                  } else {
4184
46
                                      if (path.find("packed_file/") != std::string::npos) {
4185
46
                                          return; // packed files do not have rowset_id encoded
4186
46
                                      }
4187
46
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4188
46
                                      return;
4189
46
                                  }
4190
46
                                  auto rs_meta = rowsets.find(rowset_id);
4191
46
                                  if (rs_meta != rowsets.end() &&
4192
46
                                      !deleted_rowset_id.contains(rowset_id)) {
4193
46
                                      deleted_rowset_id.emplace(rowset_id);
4194
46
                                      metrics_context.total_recycled_data_size +=
4195
46
                                              rs_meta->second.total_disk_size();
4196
46
                                      segment_metrics_context_.total_recycled_num +=
4197
46
                                              rs_meta->second.num_segments();
4198
46
                                      segment_metrics_context_.total_recycled_data_size +=
4199
46
                                              rs_meta->second.total_disk_size();
4200
46
                                      metrics_context.total_recycled_num++;
4201
46
                                  }
4202
46
                              });
4203
46
            }
4204
46
            return ret;
4205
46
        });
4206
51
    }
4207
67
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4208
5
        LOG_INFO(
4209
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4210
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4211
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4212
5
        concurrent_delete_executor.add([&]() -> int {
4213
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4214
5
            if (!ret) {
4215
5
                auto rs = rowsets.at(rowset_id);
4216
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4217
5
                metrics_context.total_recycled_num++;
4218
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4219
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4220
5
            }
4221
5
            return ret;
4222
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
4212
5
        concurrent_delete_executor.add([&]() -> int {
4213
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4214
5
            if (!ret) {
4215
5
                auto rs = rowsets.at(rowset_id);
4216
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4217
5
                metrics_context.total_recycled_num++;
4218
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4219
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4220
5
            }
4221
5
            return ret;
4222
5
        });
4223
5
    }
4224
4225
67
    bool finished = true;
4226
67
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4227
67
    for (int r : rets) {
4228
56
        if (r != 0) {
4229
0
            ret = -1;
4230
0
            break;
4231
0
        }
4232
56
    }
4233
67
    ret = finished ? ret : -1;
4234
67
    return ret;
4235
67
}
4236
4237
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4238
3.30k
                                         const std::string& rowset_id) {
4239
3.30k
    auto it = accessor_map_.find(resource_id);
4240
3.30k
    if (it == accessor_map_.end()) {
4241
400
        LOG_WARNING("instance has no such resource id")
4242
400
                .tag("instance_id", instance_id_)
4243
400
                .tag("resource_id", resource_id)
4244
400
                .tag("tablet_id", tablet_id)
4245
400
                .tag("rowset_id", rowset_id);
4246
400
        return -1;
4247
400
    }
4248
2.90k
    auto& accessor = it->second;
4249
2.90k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4250
3.30k
}
4251
4252
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4253
4
    if (key.empty()) {
4254
0
        return false;
4255
0
    }
4256
4
    std::string_view key_view = key;
4257
4
    key_view.remove_prefix(1); // remove keyspace prefix
4258
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4259
4
    if (decode_key(&key_view, &decoded) != 0) {
4260
0
        return false;
4261
0
    }
4262
4
    if (decoded.size() < 4) {
4263
0
        return false;
4264
0
    }
4265
4
    try {
4266
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4267
4
    } catch (const std::bad_variant_access&) {
4268
0
        return false;
4269
0
    }
4270
4
    return true;
4271
4
}
4272
4273
14
int InstanceRecycler::recycle_packed_files() {
4274
14
    const std::string task_name = "recycle_packed_files";
4275
14
    auto start_tp = steady_clock::now();
4276
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4277
14
    int ret = 0;
4278
14
    PackedFileRecycleStats stats;
4279
4280
14
    register_recycle_task(task_name, start_time);
4281
14
    DORIS_CLOUD_DEFER {
4282
14
        unregister_recycle_task(task_name);
4283
14
        int64_t cost =
4284
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4285
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4286
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4287
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4288
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4289
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4290
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4291
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4292
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4293
14
                                                             stats.bytes_object_deleted);
4294
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4295
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4296
14
                .tag("instance_id", instance_id_)
4297
14
                .tag("num_scanned", stats.num_scanned)
4298
14
                .tag("num_corrected", stats.num_corrected)
4299
14
                .tag("num_deleted", stats.num_deleted)
4300
14
                .tag("num_failed", stats.num_failed)
4301
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4302
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4303
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4304
14
                .tag("bytes_deleted", stats.bytes_deleted)
4305
14
                .tag("ret", ret);
4306
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4281
14
    DORIS_CLOUD_DEFER {
4282
14
        unregister_recycle_task(task_name);
4283
14
        int64_t cost =
4284
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4285
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4286
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4287
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4288
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4289
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4290
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4291
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4292
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4293
14
                                                             stats.bytes_object_deleted);
4294
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4295
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4296
14
                .tag("instance_id", instance_id_)
4297
14
                .tag("num_scanned", stats.num_scanned)
4298
14
                .tag("num_corrected", stats.num_corrected)
4299
14
                .tag("num_deleted", stats.num_deleted)
4300
14
                .tag("num_failed", stats.num_failed)
4301
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4302
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4303
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4304
14
                .tag("bytes_deleted", stats.bytes_deleted)
4305
14
                .tag("ret", ret);
4306
14
    };
4307
4308
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4309
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4310
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4311
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
4308
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4309
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4310
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4311
4
    };
4312
4313
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4314
4315
14
    std::string begin = packed_file_key({instance_id_, ""});
4316
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4317
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4318
0
        ret = -1;
4319
0
    }
4320
4321
14
    return ret;
4322
14
}
4323
4324
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4325
                                                  RecyclerMetricsContext& metrics_context,
4326
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4327
0
    std::string tablet_key_begin, tablet_key_end;
4328
4329
0
    if (partition_id > 0) {
4330
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4331
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4332
0
    } else {
4333
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4334
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4335
0
    }
4336
    // for calculate the total num or bytes of recyled objects
4337
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4338
0
                                                          std::string_view v) -> int {
4339
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4340
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4341
0
            return 0;
4342
0
        }
4343
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4344
4345
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4346
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4347
0
            return 0;
4348
0
        }
4349
4350
0
        if (!is_empty_tablet) {
4351
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4352
0
                return 0;
4353
0
            }
4354
0
            tablet_metrics_context_.total_need_recycle_num++;
4355
0
        }
4356
0
        return 0;
4357
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_
4358
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4359
0
    metrics_context.report(true);
4360
0
    tablet_metrics_context_.report(true);
4361
0
    segment_metrics_context_.report(true);
4362
0
    return ret;
4363
0
}
4364
4365
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4366
0
                                                 RecyclerMetricsContext& metrics_context) {
4367
0
    int ret = 0;
4368
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4369
0
    std::unique_ptr<Transaction> txn;
4370
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4371
0
        LOG_WARNING("failed to recycle tablet ")
4372
0
                .tag("tablet id", tablet_id)
4373
0
                .tag("instance_id", instance_id_)
4374
0
                .tag("reason", "failed to create txn");
4375
0
        ret = -1;
4376
0
    }
4377
0
    GetRowsetResponse resp;
4378
0
    std::string msg;
4379
0
    MetaServiceCode code = MetaServiceCode::OK;
4380
    // get rowsets in tablet
4381
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4382
0
                        tablet_id, code, msg, &resp);
4383
0
    if (code != MetaServiceCode::OK) {
4384
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4385
0
                .tag("tablet id", tablet_id)
4386
0
                .tag("msg", msg)
4387
0
                .tag("code", code)
4388
0
                .tag("instance id", instance_id_);
4389
0
        ret = -1;
4390
0
    }
4391
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4392
        /*
4393
        * For compatibility, we skip the loop for [0-1] here.
4394
        * The purpose of this loop is to delete object files,
4395
        * and since [0-1] only has meta and doesn't have object files,
4396
        * skipping it doesn't affect system correctness.
4397
        *
4398
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4399
        * would return error -1 directly, causing the recycle operation to fail.
4400
        *
4401
        * [0-1] doesn't have resource id is a bug.
4402
        * In the future, we will fix this problem, after that,
4403
        * we can remove this if statement.
4404
        *
4405
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4406
        */
4407
4408
0
        if (rs_meta.end_version() == 1) {
4409
            // Assert that [0-1] has no resource_id to make sure
4410
            // this if statement will not be forgetted to remove
4411
            // when the resource id bug is fixed
4412
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4413
0
            continue;
4414
0
        }
4415
0
        if (!rs_meta.has_resource_id()) {
4416
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4417
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4418
0
                    .tag("instance_id", instance_id_)
4419
0
                    .tag("tablet_id", tablet_id);
4420
0
            continue;
4421
0
        }
4422
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4423
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4424
        // possible if the accessor is not initilized correctly
4425
0
        if (it == accessor_map_.end()) [[unlikely]] {
4426
0
            LOG_WARNING(
4427
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4428
0
                    "recycle process")
4429
0
                    .tag("tablet id", tablet_id)
4430
0
                    .tag("instance_id", instance_id_)
4431
0
                    .tag("resource_id", rs_meta.resource_id())
4432
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4433
0
            continue;
4434
0
        }
4435
4436
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4437
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4438
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4439
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4440
0
    }
4441
0
    return ret;
4442
0
}
4443
4444
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4445
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4446
4.26k
            .tag("instance_id", instance_id_)
4447
4.26k
            .tag("tablet_id", tablet_id);
4448
4449
4.26k
    if (should_recycle_versioned_keys()) {
4450
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4451
14
        if (ret != 0) {
4452
0
            return ret;
4453
0
        }
4454
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4455
        // during the recycle_versioned_tablet process.
4456
        //
4457
        // .. And remove restore job rowsets of this tablet too
4458
14
    }
4459
4460
4.26k
    int ret = 0;
4461
4.26k
    auto start_time = steady_clock::now();
4462
4463
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4464
4465
    // collect resource ids
4466
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4467
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4468
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4469
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4470
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4471
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4472
4473
260
    std::set<std::string> resource_ids;
4474
260
    int64_t recycle_rowsets_number = 0;
4475
260
    int64_t recycle_segments_number = 0;
4476
260
    int64_t recycle_rowsets_data_size = 0;
4477
260
    int64_t recycle_rowsets_index_size = 0;
4478
260
    int64_t recycle_restore_job_rowsets_number = 0;
4479
260
    int64_t recycle_restore_job_segments_number = 0;
4480
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4481
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4482
260
    int64_t max_rowset_version = 0;
4483
260
    int64_t min_rowset_creation_time = INT64_MAX;
4484
260
    int64_t max_rowset_creation_time = 0;
4485
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4486
260
    int64_t max_rowset_expiration_time = 0;
4487
4488
260
    DORIS_CLOUD_DEFER {
4489
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4490
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4491
260
                .tag("instance_id", instance_id_)
4492
260
                .tag("tablet_id", tablet_id)
4493
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4494
260
                .tag("recycle segments number", recycle_segments_number)
4495
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4496
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4497
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4498
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4499
260
                .tag("all restore job rowsets recycle data size",
4500
260
                     recycle_restore_job_rowsets_data_size)
4501
260
                .tag("all restore job rowsets recycle index size",
4502
260
                     recycle_restore_job_rowsets_index_size)
4503
260
                .tag("max rowset version", max_rowset_version)
4504
260
                .tag("min rowset creation time", min_rowset_creation_time)
4505
260
                .tag("max rowset creation time", max_rowset_creation_time)
4506
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4507
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4508
260
                .tag("task type", metrics_context.operation_type)
4509
260
                .tag("ret", ret);
4510
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4488
260
    DORIS_CLOUD_DEFER {
4489
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4490
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4491
260
                .tag("instance_id", instance_id_)
4492
260
                .tag("tablet_id", tablet_id)
4493
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4494
260
                .tag("recycle segments number", recycle_segments_number)
4495
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4496
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4497
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4498
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4499
260
                .tag("all restore job rowsets recycle data size",
4500
260
                     recycle_restore_job_rowsets_data_size)
4501
260
                .tag("all restore job rowsets recycle index size",
4502
260
                     recycle_restore_job_rowsets_index_size)
4503
260
                .tag("max rowset version", max_rowset_version)
4504
260
                .tag("min rowset creation time", min_rowset_creation_time)
4505
260
                .tag("max rowset creation time", max_rowset_creation_time)
4506
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4507
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4508
260
                .tag("task type", metrics_context.operation_type)
4509
260
                .tag("ret", ret);
4510
260
    };
4511
4512
260
    std::unique_ptr<Transaction> txn;
4513
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4514
0
        LOG_WARNING("failed to recycle tablet ")
4515
0
                .tag("tablet id", tablet_id)
4516
0
                .tag("instance_id", instance_id_)
4517
0
                .tag("reason", "failed to create txn");
4518
0
        ret = -1;
4519
0
    }
4520
260
    GetRowsetResponse resp;
4521
260
    std::string msg;
4522
260
    MetaServiceCode code = MetaServiceCode::OK;
4523
    // get rowsets in tablet
4524
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4525
260
                        tablet_id, code, msg, &resp);
4526
260
    if (code != MetaServiceCode::OK) {
4527
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4528
0
                .tag("tablet id", tablet_id)
4529
0
                .tag("msg", msg)
4530
0
                .tag("code", code)
4531
0
                .tag("instance id", instance_id_);
4532
0
        ret = -1;
4533
0
    }
4534
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4535
4536
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4537
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4538
3
            if (rs_meta.num_segments() <= 0) {
4539
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4540
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4541
2
                        .tag("instance_id", instance_id_)
4542
2
                        .tag("tablet_id", tablet_id);
4543
2
                recycle_rowsets_number += 1;
4544
2
                continue;
4545
2
            }
4546
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4547
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4548
1
                    .tag("instance_id", instance_id_)
4549
1
                    .tag("tablet_id", tablet_id);
4550
1
            return -1;
4551
3
        }
4552
2.54k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4553
1
                << "rs_meta" << rs_meta.ShortDebugString();
4554
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4555
        // possible if the accessor is not initilized correctly
4556
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4557
1
            LOG_WARNING(
4558
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4559
1
                    "recycle process")
4560
1
                    .tag("tablet id", tablet_id)
4561
1
                    .tag("instance_id", instance_id_)
4562
1
                    .tag("resource_id", rs_meta.resource_id())
4563
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4564
1
            return -1;
4565
1
        }
4566
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4567
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4568
0
                    .tag("instance_id", instance_id_)
4569
0
                    .tag("tablet_id", tablet_id)
4570
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4571
0
            return -1;
4572
0
        }
4573
2.54k
        recycle_rowsets_number += 1;
4574
2.54k
        recycle_segments_number += rs_meta.num_segments();
4575
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4576
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4577
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4578
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4579
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4580
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4581
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4582
2.54k
        resource_ids.emplace(rs_meta.resource_id());
4583
2.54k
    }
4584
4585
    // get restore job rowset in tablet
4586
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
4587
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
4588
258
    if (code != MetaServiceCode::OK) {
4589
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
4590
0
                .tag("tablet id", tablet_id)
4591
0
                .tag("msg", msg)
4592
0
                .tag("code", code)
4593
0
                .tag("instance id", instance_id_);
4594
0
        return -1;
4595
0
    }
4596
4597
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
4598
0
        if (!rs_meta.has_resource_id()) {
4599
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4600
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4601
0
                    .tag("instance_id", instance_id_)
4602
0
                    .tag("tablet_id", tablet_id);
4603
0
            return -1;
4604
0
        }
4605
4606
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4607
        // possible if the accessor is not initilized correctly
4608
0
        if (it == accessor_map_.end()) [[unlikely]] {
4609
0
            LOG_WARNING(
4610
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4611
0
                    "recycle process")
4612
0
                    .tag("tablet id", tablet_id)
4613
0
                    .tag("instance_id", instance_id_)
4614
0
                    .tag("resource_id", rs_meta.resource_id())
4615
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4616
0
            return -1;
4617
0
        }
4618
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4619
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
4620
0
                    .tag("instance_id", instance_id_)
4621
0
                    .tag("tablet_id", tablet_id)
4622
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4623
0
            return -1;
4624
0
        }
4625
0
        recycle_restore_job_rowsets_number += 1;
4626
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
4627
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
4628
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
4629
0
        resource_ids.emplace(rs_meta.resource_id());
4630
0
    }
4631
4632
258
    LOG_INFO("recycle tablet start to delete object")
4633
258
            .tag("instance id", instance_id_)
4634
258
            .tag("tablet id", tablet_id)
4635
258
            .tag("recycle tablet resource ids are",
4636
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
4637
258
                                 [](std::string rs_id, const auto& it) {
4638
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4639
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
4637
217
                                 [](std::string rs_id, const auto& it) {
4638
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
4639
217
                                 }));
4640
4641
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
4642
258
            _thread_pool_group.s3_producer_pool,
4643
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4644
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
4644
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
4645
4646
    // delete all rowset data in this tablet
4647
    // ATTN: there may be data leak if not all accessor initilized successfully
4648
    //       partial data deleted if the tablet is stored cross-storage vault
4649
    //       vault id is not attached to TabletMeta...
4650
258
    for (const auto& resource_id : resource_ids) {
4651
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
4652
217
        concurrent_delete_executor.add(
4653
217
                [&, rs_id = resource_id,
4654
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4655
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4656
217
                    if (res != 0) {
4657
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4658
3
                                     << " path=" << accessor_ptr->uri()
4659
3
                                     << " task type=" << metrics_context.operation_type;
4660
3
                        return std::make_pair(-1, rs_id);
4661
3
                    }
4662
214
                    return std::make_pair(0, rs_id);
4663
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
4654
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
4655
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
4656
217
                    if (res != 0) {
4657
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
4658
3
                                     << " path=" << accessor_ptr->uri()
4659
3
                                     << " task type=" << metrics_context.operation_type;
4660
3
                        return std::make_pair(-1, rs_id);
4661
3
                    }
4662
214
                    return std::make_pair(0, rs_id);
4663
217
                });
4664
217
    }
4665
4666
258
    bool finished = true;
4667
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
4668
258
    for (auto& r : rets) {
4669
217
        if (r.first != 0) {
4670
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
4671
3
            ret = -1;
4672
3
        }
4673
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
4674
217
    }
4675
258
    ret = finished ? ret : -1;
4676
4677
258
    if (ret != 0) { // failed recycle tablet data
4678
3
        LOG_WARNING("ret!=0")
4679
3
                .tag("finished", finished)
4680
3
                .tag("ret", ret)
4681
3
                .tag("instance_id", instance_id_)
4682
3
                .tag("tablet_id", tablet_id);
4683
3
        return ret;
4684
3
    }
4685
4686
255
    tablet_metrics_context_.total_recycled_data_size +=
4687
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4688
255
    tablet_metrics_context_.total_recycled_num += 1;
4689
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
4690
255
    segment_metrics_context_.total_recycled_data_size +=
4691
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4692
255
    metrics_context.total_recycled_data_size +=
4693
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
4694
255
    tablet_metrics_context_.report();
4695
255
    segment_metrics_context_.report();
4696
255
    metrics_context.report();
4697
4698
255
    txn.reset();
4699
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4700
0
        LOG_WARNING("failed to recycle tablet ")
4701
0
                .tag("tablet id", tablet_id)
4702
0
                .tag("instance_id", instance_id_)
4703
0
                .tag("reason", "failed to create txn");
4704
0
        ret = -1;
4705
0
    }
4706
    // delete all rowset kv in this tablet
4707
255
    txn->remove(rs_key0, rs_key1);
4708
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
4709
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
4710
4711
    // remove delete bitmap for MoW table
4712
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
4713
255
    txn->remove(pending_key);
4714
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
4715
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
4716
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
4717
4718
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
4719
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
4720
255
    txn->remove(dbm_start_key, dbm_end_key);
4721
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
4722
255
              << " end=" << hex(dbm_end_key);
4723
4724
255
    TxnErrorCode err = txn->commit();
4725
255
    if (err != TxnErrorCode::TXN_OK) {
4726
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
4727
0
        ret = -1;
4728
0
    }
4729
4730
255
    if (ret == 0) {
4731
        // All object files under tablet have been deleted
4732
255
        std::lock_guard lock(recycled_tablets_mtx_);
4733
255
        recycled_tablets_.insert(tablet_id);
4734
255
    }
4735
4736
255
    return ret;
4737
258
}
4738
4739
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
4740
14
                                               RecyclerMetricsContext& metrics_context) {
4741
14
    int ret = 0;
4742
14
    auto start_time = steady_clock::now();
4743
4744
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4745
4746
    // collect resource ids
4747
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4748
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4749
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4750
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4751
4752
11
    int64_t recycle_rowsets_number = 0;
4753
11
    int64_t recycle_segments_number = 0;
4754
11
    int64_t recycle_rowsets_data_size = 0;
4755
11
    int64_t recycle_rowsets_index_size = 0;
4756
11
    int64_t max_rowset_version = 0;
4757
11
    int64_t min_rowset_creation_time = INT64_MAX;
4758
11
    int64_t max_rowset_creation_time = 0;
4759
11
    int64_t min_rowset_expiration_time = INT64_MAX;
4760
11
    int64_t max_rowset_expiration_time = 0;
4761
4762
11
    DORIS_CLOUD_DEFER {
4763
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4764
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4765
11
                .tag("instance_id", instance_id_)
4766
11
                .tag("tablet_id", tablet_id)
4767
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4768
11
                .tag("recycle segments number", recycle_segments_number)
4769
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4770
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4771
11
                .tag("max rowset version", max_rowset_version)
4772
11
                .tag("min rowset creation time", min_rowset_creation_time)
4773
11
                .tag("max rowset creation time", max_rowset_creation_time)
4774
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4775
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4776
11
                .tag("ret", ret);
4777
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4762
11
    DORIS_CLOUD_DEFER {
4763
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4764
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4765
11
                .tag("instance_id", instance_id_)
4766
11
                .tag("tablet_id", tablet_id)
4767
11
                .tag("recycle rowsets number", recycle_rowsets_number)
4768
11
                .tag("recycle segments number", recycle_segments_number)
4769
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4770
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4771
11
                .tag("max rowset version", max_rowset_version)
4772
11
                .tag("min rowset creation time", min_rowset_creation_time)
4773
11
                .tag("max rowset creation time", max_rowset_creation_time)
4774
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
4775
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
4776
11
                .tag("ret", ret);
4777
11
    };
4778
4779
11
    std::unique_ptr<Transaction> txn;
4780
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4781
0
        LOG_WARNING("failed to recycle tablet ")
4782
0
                .tag("tablet id", tablet_id)
4783
0
                .tag("instance_id", instance_id_)
4784
0
                .tag("reason", "failed to create txn");
4785
0
        ret = -1;
4786
0
    }
4787
4788
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
4789
    // by the related operation logs.
4790
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
4791
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
4792
11
    MetaReader meta_reader(instance_id_);
4793
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
4794
11
    if (err == TxnErrorCode::TXN_OK) {
4795
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
4796
11
    }
4797
11
    if (err != TxnErrorCode::TXN_OK) {
4798
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4799
0
                .tag("tablet id", tablet_id)
4800
0
                .tag("err", err)
4801
0
                .tag("instance id", instance_id_);
4802
0
        ret = -1;
4803
0
    }
4804
4805
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
4806
11
             load_rowset_metas.size(), compact_rowset_metas.size())
4807
11
            .tag("instance_id", instance_id_)
4808
11
            .tag("tablet_id", tablet_id);
4809
4810
11
    SyncExecutor<int> concurrent_delete_executor(
4811
11
            _thread_pool_group.s3_producer_pool,
4812
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
4813
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
4814
4815
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4816
60
        recycle_rowsets_number += 1;
4817
60
        recycle_segments_number += rs_meta.num_segments();
4818
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4819
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4820
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4821
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4822
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4823
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4824
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4825
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
4815
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
4816
60
        recycle_rowsets_number += 1;
4817
60
        recycle_segments_number += rs_meta.num_segments();
4818
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
4819
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
4820
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
4821
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
4822
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
4823
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
4824
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
4825
60
    };
4826
4827
11
    std::vector<RowsetDeleteTask> all_tasks;
4828
4829
11
    auto create_delete_task = [this](const RowsetMetaCloudPB& rs_meta, std::string_view recycle_key,
4830
11
                                     std::string_view non_versioned_rowset_key =
4831
60
                                             "") -> RowsetDeleteTask {
4832
60
        RowsetDeleteTask task;
4833
60
        task.rowset_meta = rs_meta;
4834
60
        task.recycle_rowset_key = std::string(recycle_key);
4835
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4836
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4837
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4838
60
        return task;
4839
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
4831
60
                                             "") -> RowsetDeleteTask {
4832
60
        RowsetDeleteTask task;
4833
60
        task.rowset_meta = rs_meta;
4834
60
        task.recycle_rowset_key = std::string(recycle_key);
4835
60
        task.non_versioned_rowset_key = std::string(non_versioned_rowset_key);
4836
60
        task.versioned_rowset_key = versioned::meta_rowset_key(
4837
60
                {instance_id_, rs_meta.tablet_id(), rs_meta.rowset_id_v2()});
4838
60
        return task;
4839
60
    };
4840
4841
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
4842
60
        update_rowset_stats(rs_meta);
4843
        // Version 0-1 rowset has no resource_id and no actual data files,
4844
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4845
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4846
60
        std::string rowset_load_key =
4847
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
4848
60
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4849
60
        RowsetDeleteTask task = create_delete_task(
4850
60
                rs_meta, encode_versioned_key(rowset_load_key, versionstamp), rowset_key);
4851
60
        all_tasks.push_back(std::move(task));
4852
60
    }
4853
4854
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
4855
0
        update_rowset_stats(rs_meta);
4856
        // Version 0-1 rowset has no resource_id and no actual data files,
4857
        // but still needs ref_count key cleanup, so we add it to all_tasks.
4858
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
4859
0
        std::string rowset_compact_key = versioned::meta_rowset_compact_key(
4860
0
                {instance_id_, tablet_id, rs_meta.end_version()});
4861
0
        std::string rowset_key = meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
4862
0
        RowsetDeleteTask task = create_delete_task(
4863
0
                rs_meta, encode_versioned_key(rowset_compact_key, versionstamp), rowset_key);
4864
0
        all_tasks.push_back(std::move(task));
4865
0
    }
4866
4867
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
4868
0
        RecycleRowsetPB recycle_rowset;
4869
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
4870
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
4871
0
            return -1;
4872
0
        }
4873
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
4874
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
4875
                // in old version, keep this key-value pair and it needs to be checked manually
4876
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
4877
0
                return -1;
4878
0
            }
4879
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
4880
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
4881
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
4882
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
4883
0
                return -1;
4884
0
            }
4885
            // decode rowset_id
4886
0
            auto k1 = k;
4887
0
            k1.remove_prefix(1);
4888
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
4889
0
            decode_key(&k1, &out);
4890
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
4891
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
4892
0
            LOG_INFO("delete old-version rowset data")
4893
0
                    .tag("instance_id", instance_id_)
4894
0
                    .tag("tablet_id", tablet_id)
4895
0
                    .tag("rowset_id", rowset_id);
4896
4897
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
4898
            // so we must use prefix deletion directly instead of batch delete.
4899
0
            concurrent_delete_executor.add(
4900
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
4901
                        // delete by prefix, the recycle rowset key will be deleted by range later.
4902
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
4903
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
4904
0
        } else {
4905
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
4906
            // Version 0-1 rowset has no resource_id and no actual data files,
4907
            // but still needs ref_count key cleanup, so we add it to all_tasks.
4908
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
4909
0
            RowsetDeleteTask task = create_delete_task(rowset_meta, k);
4910
0
            all_tasks.push_back(std::move(task));
4911
0
        }
4912
0
        return 0;
4913
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES8_
4914
4915
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
4916
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
4917
0
                .tag("tablet id", tablet_id)
4918
0
                .tag("instance_id", instance_id_)
4919
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
4920
0
        ret = -1;
4921
0
    }
4922
4923
    // Phase 1: Classify tasks by ref_count
4924
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
4925
60
    for (auto& task : all_tasks) {
4926
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
4927
60
        if (classify_ret < 0) {
4928
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
4929
0
                    .tag("instance_id", instance_id_)
4930
0
                    .tag("tablet_id", tablet_id)
4931
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4932
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
4933
0
                return recycle_rowset_meta_and_data(t.recycle_rowset_key, t.rowset_meta,
4934
0
                                                    t.non_versioned_rowset_key);
4935
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_5clEv
4936
0
        }
4937
60
    }
4938
4939
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
4940
4941
11
    LOG_INFO("batch delete plan created")
4942
11
            .tag("instance_id", instance_id_)
4943
11
            .tag("tablet_id", tablet_id)
4944
11
            .tag("plan_count", batch_delete_tasks.size());
4945
4946
    // Phase 2: Execute batch delete using existing delete_rowset_data
4947
11
    if (!batch_delete_tasks.empty()) {
4948
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
4949
49
        for (const auto& task : batch_delete_tasks) {
4950
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
4951
49
            if (task.rowset_meta.resource_id().empty()) {
4952
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
4953
10
                        .tag("instance_id", instance_id_)
4954
10
                        .tag("tablet_id", tablet_id)
4955
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
4956
10
                continue;
4957
10
            }
4958
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
4959
39
        }
4960
4961
        // Only call delete_rowset_data if there are rowsets with actual data to delete
4962
10
        bool delete_success = true;
4963
10
        if (!rowsets_to_delete.empty()) {
4964
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
4965
9
                                                         "batch_delete_versioned_tablet");
4966
9
            int delete_ret = delete_rowset_data(
4967
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
4968
9
            if (delete_ret != 0) {
4969
0
                LOG_WARNING("batch delete execution failed")
4970
0
                        .tag("instance_id", instance_id_)
4971
0
                        .tag("tablet_id", tablet_id);
4972
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
4973
0
                ret = -1;
4974
0
                delete_success = false;
4975
0
            }
4976
9
        }
4977
4978
        // Phase 3: Only cleanup metadata if data deletion succeeded.
4979
        // If deletion failed, keep recycle_rowset_key so next round will retry.
4980
10
        if (delete_success) {
4981
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
4982
10
            if (cleanup_ret != 0) {
4983
0
                LOG_WARNING("batch delete cleanup failed")
4984
0
                        .tag("instance_id", instance_id_)
4985
0
                        .tag("tablet_id", tablet_id);
4986
0
                ret = -1;
4987
0
            }
4988
10
        }
4989
10
    }
4990
4991
    // Always wait for fallback tasks to complete before returning
4992
11
    bool finished = true;
4993
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4994
11
    for (int r : rets) {
4995
0
        if (r != 0) {
4996
0
            ret = -1;
4997
0
        }
4998
0
    }
4999
5000
11
    ret = finished ? ret : -1;
5001
5002
11
    if (ret != 0) { // failed recycle tablet data
5003
0
        LOG_WARNING("recycle versioned tablet failed")
5004
0
                .tag("finished", finished)
5005
0
                .tag("ret", ret)
5006
0
                .tag("instance_id", instance_id_)
5007
0
                .tag("tablet_id", tablet_id);
5008
0
        return ret;
5009
0
    }
5010
5011
11
    tablet_metrics_context_.total_recycled_data_size +=
5012
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5013
11
    tablet_metrics_context_.total_recycled_num += 1;
5014
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5015
11
    segment_metrics_context_.total_recycled_data_size +=
5016
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5017
11
    metrics_context.total_recycled_data_size +=
5018
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5019
11
    tablet_metrics_context_.report();
5020
11
    segment_metrics_context_.report();
5021
11
    metrics_context.report();
5022
5023
11
    txn.reset();
5024
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5025
0
        LOG_WARNING("failed to recycle tablet ")
5026
0
                .tag("tablet id", tablet_id)
5027
0
                .tag("instance_id", instance_id_)
5028
0
                .tag("reason", "failed to create txn");
5029
0
        ret = -1;
5030
0
    }
5031
    // delete all rowset kv in this tablet
5032
11
    txn->remove(rs_key0, rs_key1);
5033
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5034
5035
    // remove delete bitmap for MoW table
5036
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5037
11
    txn->remove(pending_key);
5038
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5039
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5040
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5041
5042
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5043
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5044
11
    txn->remove(dbm_start_key, dbm_end_key);
5045
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5046
11
              << " end=" << hex(dbm_end_key);
5047
5048
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5049
11
    std::string tablet_index_val;
5050
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5051
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5052
0
        LOG_WARNING("failed to get tablet index kv")
5053
0
                .tag("instance_id", instance_id_)
5054
0
                .tag("tablet_id", tablet_id)
5055
0
                .tag("err", err);
5056
0
        ret = -1;
5057
11
    } else if (err == TxnErrorCode::TXN_OK) {
5058
        // If the tablet index kv exists, we need to delete it
5059
10
        TabletIndexPB tablet_index_pb;
5060
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5061
0
            LOG_WARNING("failed to parse tablet index pb")
5062
0
                    .tag("instance_id", instance_id_)
5063
0
                    .tag("tablet_id", tablet_id);
5064
0
            ret = -1;
5065
10
        } else {
5066
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5067
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5068
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5069
10
            txn->remove(versioned_inverted_idx_key);
5070
10
            txn->remove(versioned_idx_key);
5071
10
        }
5072
10
    }
5073
5074
11
    err = txn->commit();
5075
11
    if (err != TxnErrorCode::TXN_OK) {
5076
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5077
0
        ret = -1;
5078
0
    }
5079
5080
11
    if (ret == 0) {
5081
        // All object files under tablet have been deleted
5082
11
        std::lock_guard lock(recycled_tablets_mtx_);
5083
11
        recycled_tablets_.insert(tablet_id);
5084
11
    }
5085
5086
11
    return ret;
5087
11
}
5088
5089
27
int InstanceRecycler::recycle_rowsets() {
5090
27
    if (should_recycle_versioned_keys()) {
5091
5
        return recycle_versioned_rowsets();
5092
5
    }
5093
5094
22
    const std::string task_name = "recycle_rowsets";
5095
22
    int64_t num_scanned = 0;
5096
22
    int64_t num_expired = 0;
5097
22
    int64_t num_prepare = 0;
5098
22
    int64_t num_compacted = 0;
5099
22
    int64_t num_empty_rowset = 0;
5100
22
    size_t total_rowset_key_size = 0;
5101
22
    size_t total_rowset_value_size = 0;
5102
22
    size_t expired_rowset_size = 0;
5103
22
    std::atomic_long num_recycled = 0;
5104
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5105
5106
22
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5107
22
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5108
22
    std::string recyc_rs_key0;
5109
22
    std::string recyc_rs_key1;
5110
22
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5111
22
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5112
5113
22
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5114
5115
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5116
22
    register_recycle_task(task_name, start_time);
5117
5118
22
    DORIS_CLOUD_DEFER {
5119
22
        unregister_recycle_task(task_name);
5120
22
        int64_t cost =
5121
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5122
22
        metrics_context.finish_report();
5123
22
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5124
22
                .tag("instance_id", instance_id_)
5125
22
                .tag("num_scanned", num_scanned)
5126
22
                .tag("num_expired", num_expired)
5127
22
                .tag("num_recycled", num_recycled)
5128
22
                .tag("num_recycled.prepare", num_prepare)
5129
22
                .tag("num_recycled.compacted", num_compacted)
5130
22
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5131
22
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5132
22
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5133
22
                .tag("expired_rowset_meta_size", expired_rowset_size);
5134
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5118
7
    DORIS_CLOUD_DEFER {
5119
7
        unregister_recycle_task(task_name);
5120
7
        int64_t cost =
5121
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5122
7
        metrics_context.finish_report();
5123
7
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5124
7
                .tag("instance_id", instance_id_)
5125
7
                .tag("num_scanned", num_scanned)
5126
7
                .tag("num_expired", num_expired)
5127
7
                .tag("num_recycled", num_recycled)
5128
7
                .tag("num_recycled.prepare", num_prepare)
5129
7
                .tag("num_recycled.compacted", num_compacted)
5130
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5131
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5132
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5133
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5134
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5118
15
    DORIS_CLOUD_DEFER {
5119
15
        unregister_recycle_task(task_name);
5120
15
        int64_t cost =
5121
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5122
15
        metrics_context.finish_report();
5123
15
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5124
15
                .tag("instance_id", instance_id_)
5125
15
                .tag("num_scanned", num_scanned)
5126
15
                .tag("num_expired", num_expired)
5127
15
                .tag("num_recycled", num_recycled)
5128
15
                .tag("num_recycled.prepare", num_prepare)
5129
15
                .tag("num_recycled.compacted", num_compacted)
5130
15
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5131
15
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5132
15
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5133
15
                .tag("expired_rowset_meta_size", expired_rowset_size);
5134
15
    };
5135
5136
22
    std::vector<std::string> rowset_keys;
5137
22
    std::vector<std::string> rowset_keys_to_mark_recycled;
5138
22
    std::vector<std::string> rowset_keys_to_abort;
5139
22
    std::vector<std::string> prepare_rowset_keys_to_delete;
5140
    // rowset_id -> rowset_meta
5141
    // store rowset id and meta for statistics rs size when delete
5142
22
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5143
5144
    // Store keys of rowset recycled by background workers
5145
22
    std::mutex async_recycled_rowset_keys_mutex;
5146
22
    std::vector<std::string> async_recycled_rowset_keys;
5147
22
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5148
22
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5149
22
    worker_pool->start();
5150
    // TODO bacth delete
5151
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5152
4.00k
        std::string dbm_start_key =
5153
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5154
4.00k
        std::string dbm_end_key = dbm_start_key;
5155
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
5156
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5157
4.00k
        if (ret != 0) {
5158
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5159
0
                         << instance_id_;
5160
0
        }
5161
4.00k
        return ret;
5162
4.00k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5151
3
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5152
3
        std::string dbm_start_key =
5153
3
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5154
3
        std::string dbm_end_key = dbm_start_key;
5155
3
        encode_int64(INT64_MAX, &dbm_end_key);
5156
3
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5157
3
        if (ret != 0) {
5158
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5159
0
                         << instance_id_;
5160
0
        }
5161
3
        return ret;
5162
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5151
4.00k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
5152
4.00k
        std::string dbm_start_key =
5153
4.00k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
5154
4.00k
        std::string dbm_end_key = dbm_start_key;
5155
4.00k
        encode_int64(INT64_MAX, &dbm_end_key);
5156
4.00k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
5157
4.00k
        if (ret != 0) {
5158
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5159
0
                         << instance_id_;
5160
0
        }
5161
4.00k
        return ret;
5162
4.00k
    };
5163
22
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5164
250
                                            int64_t tablet_id, const std::string& rowset_id) {
5165
        // Try to delete rowset data in background thread
5166
250
        int ret = worker_pool->submit_with_timeout(
5167
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5168
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5169
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5170
0
                        return;
5171
0
                    }
5172
246
                    std::vector<std::string> keys;
5173
246
                    {
5174
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5175
246
                        async_recycled_rowset_keys.push_back(std::move(key));
5176
246
                        if (async_recycled_rowset_keys.size() > 100) {
5177
2
                            keys.swap(async_recycled_rowset_keys);
5178
2
                        }
5179
246
                    }
5180
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5181
246
                    if (keys.empty()) return;
5182
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5183
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5184
0
                                     << instance_id_;
5185
2
                    } else {
5186
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5187
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5188
2
                                           num_recycled, start_time);
5189
2
                    }
5190
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
5167
246
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5168
246
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5169
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5170
0
                        return;
5171
0
                    }
5172
246
                    std::vector<std::string> keys;
5173
246
                    {
5174
246
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5175
246
                        async_recycled_rowset_keys.push_back(std::move(key));
5176
246
                        if (async_recycled_rowset_keys.size() > 100) {
5177
2
                            keys.swap(async_recycled_rowset_keys);
5178
2
                        }
5179
246
                    }
5180
246
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5181
246
                    if (keys.empty()) return;
5182
2
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5183
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5184
0
                                     << instance_id_;
5185
2
                    } else {
5186
2
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5187
2
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5188
2
                                           num_recycled, start_time);
5189
2
                    }
5190
2
                },
5191
250
                0);
5192
250
        if (ret == 0) return 0;
5193
        // Submit task failed, delete rowset data in current thread
5194
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5195
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5196
0
            return -1;
5197
0
        }
5198
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5199
0
            return -1;
5200
0
        }
5201
4
        rowset_keys.push_back(std::move(key));
5202
4
        return 0;
5203
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
5164
250
                                            int64_t tablet_id, const std::string& rowset_id) {
5165
        // Try to delete rowset data in background thread
5166
250
        int ret = worker_pool->submit_with_timeout(
5167
250
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5168
250
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5169
250
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5170
250
                        return;
5171
250
                    }
5172
250
                    std::vector<std::string> keys;
5173
250
                    {
5174
250
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5175
250
                        async_recycled_rowset_keys.push_back(std::move(key));
5176
250
                        if (async_recycled_rowset_keys.size() > 100) {
5177
250
                            keys.swap(async_recycled_rowset_keys);
5178
250
                        }
5179
250
                    }
5180
250
                    delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id);
5181
250
                    if (keys.empty()) return;
5182
250
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5183
250
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5184
250
                                     << instance_id_;
5185
250
                    } else {
5186
250
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5187
250
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5188
250
                                           num_recycled, start_time);
5189
250
                    }
5190
250
                },
5191
250
                0);
5192
250
        if (ret == 0) return 0;
5193
        // Submit task failed, delete rowset data in current thread
5194
4
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5195
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5196
0
            return -1;
5197
0
        }
5198
4
        if (delete_versioned_delete_bitmap_kvs(tablet_id, rowset_id) != 0) {
5199
0
            return -1;
5200
0
        }
5201
4
        rowset_keys.push_back(std::move(key));
5202
4
        return 0;
5203
4
    };
5204
5205
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5206
5207
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5208
4.00k
        ++num_scanned;
5209
4.00k
        total_rowset_key_size += k.size();
5210
4.00k
        total_rowset_value_size += v.size();
5211
4.00k
        RecycleRowsetPB rowset;
5212
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5213
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5214
0
            return -1;
5215
0
        }
5216
5217
4.00k
        int64_t current_time = ::time(nullptr);
5218
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5219
5220
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5221
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5222
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5223
4.00k
        if (current_time < expiration) { // not expired
5224
0
            return 0;
5225
0
        }
5226
4.00k
        ++num_expired;
5227
4.00k
        expired_rowset_size += v.size();
5228
5229
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5230
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5231
                // in old version, keep this key-value pair and it needs to be checked manually
5232
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5233
0
                return -1;
5234
0
            }
5235
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5236
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5237
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5238
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5239
0
                rowset_keys.emplace_back(k);
5240
0
                return -1;
5241
0
            }
5242
            // decode rowset_id
5243
250
            auto k1 = k;
5244
250
            k1.remove_prefix(1);
5245
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5246
250
            decode_key(&k1, &out);
5247
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5248
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5249
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5250
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5251
250
                      << " task_type=" << metrics_context.operation_type;
5252
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5253
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5254
0
                return -1;
5255
0
            }
5256
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5257
250
            metrics_context.total_recycled_num++;
5258
250
            segment_metrics_context_.total_recycled_data_size +=
5259
250
                    rowset.rowset_meta().total_disk_size();
5260
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5261
250
            return 0;
5262
250
        }
5263
5264
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5265
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5266
6
            if (need_mark_rowset_as_recycled(rowset)) {
5267
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5268
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5269
4
                             "at next turn, instance_id="
5270
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5271
4
                          << " version=[" << rowset_meta->start_version() << '-'
5272
4
                          << rowset_meta->end_version() << "]";
5273
4
                return 0;
5274
4
            }
5275
6
        }
5276
5277
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5278
3.75k
            rowset_meta->end_version() != 1) {
5279
2
            if (make_deferred_abort_task(rowset).has_value()) {
5280
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5281
2
                             "instance_id="
5282
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5283
2
                          << " version=[" << rowset_meta->start_version() << '-'
5284
2
                          << rowset_meta->end_version() << "]";
5285
2
                rowset_keys_to_abort.emplace_back(k);
5286
2
            }
5287
2
        }
5288
5289
        // TODO(plat1ko): check rowset not referenced
5290
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5291
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5292
0
                LOG_INFO("recycle rowset that has empty resource id");
5293
0
            } else {
5294
                // other situations, keep this key-value pair and it needs to be checked manually
5295
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5296
0
                return -1;
5297
0
            }
5298
0
        }
5299
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5300
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5301
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5302
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5303
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5304
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5305
3.75k
                  << " rowset_meta_size=" << v.size()
5306
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5307
3.75k
                  << " task_type=" << metrics_context.operation_type;
5308
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5309
            // unable to calculate file path, can only be deleted by rowset id prefix
5310
653
            num_prepare += 1;
5311
653
            prepare_rowset_keys_to_delete.emplace_back(k);
5312
3.10k
        } else {
5313
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5314
3.10k
            rowset_keys.emplace_back(k);
5315
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5316
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5317
3.10k
                ++num_empty_rowset;
5318
3.10k
            }
5319
3.10k
        }
5320
3.75k
        return 0;
5321
3.75k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5207
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5208
7
        ++num_scanned;
5209
7
        total_rowset_key_size += k.size();
5210
7
        total_rowset_value_size += v.size();
5211
7
        RecycleRowsetPB rowset;
5212
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5213
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5214
0
            return -1;
5215
0
        }
5216
5217
7
        int64_t current_time = ::time(nullptr);
5218
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5219
5220
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5221
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5222
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5223
7
        if (current_time < expiration) { // not expired
5224
0
            return 0;
5225
0
        }
5226
7
        ++num_expired;
5227
7
        expired_rowset_size += v.size();
5228
5229
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5230
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5231
                // in old version, keep this key-value pair and it needs to be checked manually
5232
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5233
0
                return -1;
5234
0
            }
5235
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5236
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5237
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5238
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5239
0
                rowset_keys.emplace_back(k);
5240
0
                return -1;
5241
0
            }
5242
            // decode rowset_id
5243
0
            auto k1 = k;
5244
0
            k1.remove_prefix(1);
5245
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5246
0
            decode_key(&k1, &out);
5247
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5248
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5249
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5250
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5251
0
                      << " task_type=" << metrics_context.operation_type;
5252
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5253
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5254
0
                return -1;
5255
0
            }
5256
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5257
0
            metrics_context.total_recycled_num++;
5258
0
            segment_metrics_context_.total_recycled_data_size +=
5259
0
                    rowset.rowset_meta().total_disk_size();
5260
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5261
0
            return 0;
5262
0
        }
5263
5264
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5265
7
        if (config::enable_mark_delete_rowset_before_recycle) {
5266
6
            if (need_mark_rowset_as_recycled(rowset)) {
5267
4
                rowset_keys_to_mark_recycled.emplace_back(k);
5268
4
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5269
4
                             "at next turn, instance_id="
5270
4
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5271
4
                          << " version=[" << rowset_meta->start_version() << '-'
5272
4
                          << rowset_meta->end_version() << "]";
5273
4
                return 0;
5274
4
            }
5275
6
        }
5276
5277
3
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5278
3
            rowset_meta->end_version() != 1) {
5279
2
            if (make_deferred_abort_task(rowset).has_value()) {
5280
2
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5281
2
                             "instance_id="
5282
2
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5283
2
                          << " version=[" << rowset_meta->start_version() << '-'
5284
2
                          << rowset_meta->end_version() << "]";
5285
2
                rowset_keys_to_abort.emplace_back(k);
5286
2
            }
5287
2
        }
5288
5289
        // TODO(plat1ko): check rowset not referenced
5290
3
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5291
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5292
0
                LOG_INFO("recycle rowset that has empty resource id");
5293
0
            } else {
5294
                // other situations, keep this key-value pair and it needs to be checked manually
5295
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5296
0
                return -1;
5297
0
            }
5298
0
        }
5299
3
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5300
3
                  << " tablet_id=" << rowset_meta->tablet_id()
5301
3
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5302
3
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5303
3
                  << "] txn_id=" << rowset_meta->txn_id()
5304
3
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5305
3
                  << " rowset_meta_size=" << v.size()
5306
3
                  << " creation_time=" << rowset_meta->creation_time()
5307
3
                  << " task_type=" << metrics_context.operation_type;
5308
3
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5309
            // unable to calculate file path, can only be deleted by rowset id prefix
5310
3
            num_prepare += 1;
5311
3
            prepare_rowset_keys_to_delete.emplace_back(k);
5312
3
        } else {
5313
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5314
0
            rowset_keys.emplace_back(k);
5315
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5316
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5317
0
                ++num_empty_rowset;
5318
0
            }
5319
0
        }
5320
3
        return 0;
5321
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5207
4.00k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5208
4.00k
        ++num_scanned;
5209
4.00k
        total_rowset_key_size += k.size();
5210
4.00k
        total_rowset_value_size += v.size();
5211
4.00k
        RecycleRowsetPB rowset;
5212
4.00k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5213
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5214
0
            return -1;
5215
0
        }
5216
5217
4.00k
        int64_t current_time = ::time(nullptr);
5218
4.00k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5219
5220
4.00k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5221
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5222
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5223
4.00k
        if (current_time < expiration) { // not expired
5224
0
            return 0;
5225
0
        }
5226
4.00k
        ++num_expired;
5227
4.00k
        expired_rowset_size += v.size();
5228
5229
4.00k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5230
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5231
                // in old version, keep this key-value pair and it needs to be checked manually
5232
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5233
0
                return -1;
5234
0
            }
5235
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5236
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5237
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5238
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5239
0
                rowset_keys.emplace_back(k);
5240
0
                return -1;
5241
0
            }
5242
            // decode rowset_id
5243
250
            auto k1 = k;
5244
250
            k1.remove_prefix(1);
5245
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5246
250
            decode_key(&k1, &out);
5247
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5248
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5249
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5250
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5251
250
                      << " task_type=" << metrics_context.operation_type;
5252
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5253
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5254
0
                return -1;
5255
0
            }
5256
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5257
250
            metrics_context.total_recycled_num++;
5258
250
            segment_metrics_context_.total_recycled_data_size +=
5259
250
                    rowset.rowset_meta().total_disk_size();
5260
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5261
250
            return 0;
5262
250
        }
5263
5264
3.75k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5265
3.75k
        if (config::enable_mark_delete_rowset_before_recycle) {
5266
0
            if (need_mark_rowset_as_recycled(rowset)) {
5267
0
                rowset_keys_to_mark_recycled.emplace_back(k);
5268
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
5269
0
                             "at next turn, instance_id="
5270
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5271
0
                          << " version=[" << rowset_meta->start_version() << '-'
5272
0
                          << rowset_meta->end_version() << "]";
5273
0
                return 0;
5274
0
            }
5275
0
        }
5276
5277
3.75k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5278
3.75k
            rowset_meta->end_version() != 1) {
5279
0
            if (make_deferred_abort_task(rowset).has_value()) {
5280
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
5281
0
                             "instance_id="
5282
0
                          << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5283
0
                          << " version=[" << rowset_meta->start_version() << '-'
5284
0
                          << rowset_meta->end_version() << "]";
5285
0
                rowset_keys_to_abort.emplace_back(k);
5286
0
            }
5287
0
        }
5288
5289
        // TODO(plat1ko): check rowset not referenced
5290
3.75k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5291
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5292
0
                LOG_INFO("recycle rowset that has empty resource id");
5293
0
            } else {
5294
                // other situations, keep this key-value pair and it needs to be checked manually
5295
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5296
0
                return -1;
5297
0
            }
5298
0
        }
5299
3.75k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5300
3.75k
                  << " tablet_id=" << rowset_meta->tablet_id()
5301
3.75k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5302
3.75k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5303
3.75k
                  << "] txn_id=" << rowset_meta->txn_id()
5304
3.75k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5305
3.75k
                  << " rowset_meta_size=" << v.size()
5306
3.75k
                  << " creation_time=" << rowset_meta->creation_time()
5307
3.75k
                  << " task_type=" << metrics_context.operation_type;
5308
3.75k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5309
            // unable to calculate file path, can only be deleted by rowset id prefix
5310
650
            num_prepare += 1;
5311
650
            prepare_rowset_keys_to_delete.emplace_back(k);
5312
3.10k
        } else {
5313
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5314
3.10k
            rowset_keys.emplace_back(k);
5315
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5316
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5317
3.10k
                ++num_empty_rowset;
5318
3.10k
            }
5319
3.10k
        }
5320
3.75k
        return 0;
5321
3.75k
    };
5322
5323
28
    auto loop_done = [&]() -> int {
5324
28
        std::vector<std::string> rowset_keys_to_delete;
5325
28
        std::vector<std::string> mark_keys_to_process;
5326
28
        std::vector<std::string> abort_keys_to_process;
5327
28
        std::vector<std::string> prepare_keys_to_process;
5328
        // rowset_id -> rowset_meta
5329
        // store rowset id and meta for statistics rs size when delete
5330
28
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5331
28
        rowset_keys_to_delete.swap(rowset_keys);
5332
28
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5333
28
        abort_keys_to_process.swap(rowset_keys_to_abort);
5334
28
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5335
28
        rowsets_to_delete.swap(rowsets);
5336
28
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5337
28
                             rowsets_to_delete = std::move(rowsets_to_delete),
5338
28
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5339
28
                             mark_keys_to_process = std::move(mark_keys_to_process),
5340
28
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5341
28
            if (!mark_keys_to_process.empty() &&
5342
28
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5343
4
                                                                mark_keys_to_process) != 0) {
5344
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5345
0
                             << instance_id_;
5346
0
                return;
5347
0
            }
5348
28
            if (!abort_keys_to_process.empty() &&
5349
28
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5350
2
                        0) {
5351
0
                return;
5352
0
            }
5353
28
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5354
28
            if (!prepare_keys_to_process.empty() &&
5355
28
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5356
24
                                             &prepare_delete_tasks) != 0) {
5357
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5358
0
                             << instance_id_;
5359
0
                return;
5360
0
            }
5361
28
            if (!prepare_delete_tasks.empty()) {
5362
24
                std::vector<std::string> prepare_rowset_keys_to_delete;
5363
24
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5364
653
                for (const auto& task : prepare_delete_tasks) {
5365
653
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5366
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5367
0
                        return;
5368
0
                    }
5369
653
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5370
0
                        return;
5371
0
                    }
5372
653
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5373
653
                }
5374
24
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5375
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5376
0
                                 << instance_id_;
5377
0
                    return;
5378
0
                }
5379
24
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5380
24
                                       std::memory_order_relaxed);
5381
24
            }
5382
28
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5383
28
                                   metrics_context) != 0) {
5384
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5385
0
                return;
5386
0
            }
5387
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5388
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5389
0
                    return;
5390
0
                }
5391
3.10k
            }
5392
28
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5393
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5394
0
                return;
5395
0
            }
5396
28
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5397
28
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5340
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5341
7
            if (!mark_keys_to_process.empty() &&
5342
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5343
4
                                                                mark_keys_to_process) != 0) {
5344
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5345
0
                             << instance_id_;
5346
0
                return;
5347
0
            }
5348
7
            if (!abort_keys_to_process.empty() &&
5349
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5350
2
                        0) {
5351
0
                return;
5352
0
            }
5353
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5354
7
            if (!prepare_keys_to_process.empty() &&
5355
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5356
3
                                             &prepare_delete_tasks) != 0) {
5357
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5358
0
                             << instance_id_;
5359
0
                return;
5360
0
            }
5361
7
            if (!prepare_delete_tasks.empty()) {
5362
3
                std::vector<std::string> prepare_rowset_keys_to_delete;
5363
3
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5364
3
                for (const auto& task : prepare_delete_tasks) {
5365
3
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5366
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5367
0
                        return;
5368
0
                    }
5369
3
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5370
0
                        return;
5371
0
                    }
5372
3
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5373
3
                }
5374
3
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5375
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5376
0
                                 << instance_id_;
5377
0
                    return;
5378
0
                }
5379
3
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5380
3
                                       std::memory_order_relaxed);
5381
3
            }
5382
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5383
7
                                   metrics_context) != 0) {
5384
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5385
0
                return;
5386
0
            }
5387
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5388
0
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5389
0
                    return;
5390
0
                }
5391
0
            }
5392
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5393
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5394
0
                return;
5395
0
            }
5396
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5397
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5340
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5341
21
            if (!mark_keys_to_process.empty() &&
5342
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5343
0
                                                                mark_keys_to_process) != 0) {
5344
0
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5345
0
                             << instance_id_;
5346
0
                return;
5347
0
            }
5348
21
            if (!abort_keys_to_process.empty() &&
5349
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5350
0
                        0) {
5351
0
                return;
5352
0
            }
5353
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5354
21
            if (!prepare_keys_to_process.empty() &&
5355
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5356
21
                                             &prepare_delete_tasks) != 0) {
5357
0
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5358
0
                             << instance_id_;
5359
0
                return;
5360
0
            }
5361
21
            if (!prepare_delete_tasks.empty()) {
5362
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5363
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5364
650
                for (const auto& task : prepare_delete_tasks) {
5365
650
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5366
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5367
0
                        return;
5368
0
                    }
5369
650
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5370
0
                        return;
5371
0
                    }
5372
650
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5373
650
                }
5374
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5375
0
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5376
0
                                 << instance_id_;
5377
0
                    return;
5378
0
                }
5379
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5380
21
                                       std::memory_order_relaxed);
5381
21
            }
5382
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5383
21
                                   metrics_context) != 0) {
5384
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5385
0
                return;
5386
0
            }
5387
3.10k
            for (const auto& [_, rs] : rowsets_to_delete) {
5388
3.10k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5389
0
                    return;
5390
0
                }
5391
3.10k
            }
5392
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5393
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5394
0
                return;
5395
0
            }
5396
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5397
21
        });
5398
28
        return 0;
5399
28
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5323
7
    auto loop_done = [&]() -> int {
5324
7
        std::vector<std::string> rowset_keys_to_delete;
5325
7
        std::vector<std::string> mark_keys_to_process;
5326
7
        std::vector<std::string> abort_keys_to_process;
5327
7
        std::vector<std::string> prepare_keys_to_process;
5328
        // rowset_id -> rowset_meta
5329
        // store rowset id and meta for statistics rs size when delete
5330
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5331
7
        rowset_keys_to_delete.swap(rowset_keys);
5332
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5333
7
        abort_keys_to_process.swap(rowset_keys_to_abort);
5334
7
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5335
7
        rowsets_to_delete.swap(rowsets);
5336
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5337
7
                             rowsets_to_delete = std::move(rowsets_to_delete),
5338
7
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5339
7
                             mark_keys_to_process = std::move(mark_keys_to_process),
5340
7
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5341
7
            if (!mark_keys_to_process.empty() &&
5342
7
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5343
7
                                                                mark_keys_to_process) != 0) {
5344
7
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5345
7
                             << instance_id_;
5346
7
                return;
5347
7
            }
5348
7
            if (!abort_keys_to_process.empty() &&
5349
7
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5350
7
                        0) {
5351
7
                return;
5352
7
            }
5353
7
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5354
7
            if (!prepare_keys_to_process.empty() &&
5355
7
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5356
7
                                             &prepare_delete_tasks) != 0) {
5357
7
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5358
7
                             << instance_id_;
5359
7
                return;
5360
7
            }
5361
7
            if (!prepare_delete_tasks.empty()) {
5362
7
                std::vector<std::string> prepare_rowset_keys_to_delete;
5363
7
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5364
7
                for (const auto& task : prepare_delete_tasks) {
5365
7
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5366
7
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5367
7
                        return;
5368
7
                    }
5369
7
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5370
7
                        return;
5371
7
                    }
5372
7
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5373
7
                }
5374
7
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5375
7
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5376
7
                                 << instance_id_;
5377
7
                    return;
5378
7
                }
5379
7
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5380
7
                                       std::memory_order_relaxed);
5381
7
            }
5382
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5383
7
                                   metrics_context) != 0) {
5384
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5385
7
                return;
5386
7
            }
5387
7
            for (const auto& [_, rs] : rowsets_to_delete) {
5388
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5389
7
                    return;
5390
7
                }
5391
7
            }
5392
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5393
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5394
7
                return;
5395
7
            }
5396
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5397
7
        });
5398
7
        return 0;
5399
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5323
21
    auto loop_done = [&]() -> int {
5324
21
        std::vector<std::string> rowset_keys_to_delete;
5325
21
        std::vector<std::string> mark_keys_to_process;
5326
21
        std::vector<std::string> abort_keys_to_process;
5327
21
        std::vector<std::string> prepare_keys_to_process;
5328
        // rowset_id -> rowset_meta
5329
        // store rowset id and meta for statistics rs size when delete
5330
21
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5331
21
        rowset_keys_to_delete.swap(rowset_keys);
5332
21
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5333
21
        abort_keys_to_process.swap(rowset_keys_to_abort);
5334
21
        prepare_keys_to_process.swap(prepare_rowset_keys_to_delete);
5335
21
        rowsets_to_delete.swap(rowsets);
5336
21
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5337
21
                             rowsets_to_delete = std::move(rowsets_to_delete),
5338
21
                             prepare_keys_to_process = std::move(prepare_keys_to_process),
5339
21
                             mark_keys_to_process = std::move(mark_keys_to_process),
5340
21
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
5341
21
            if (!mark_keys_to_process.empty() &&
5342
21
                batch_mark_rowsets_as_recycled<RecycleRowsetPB>(txn_kv_.get(), instance_id_,
5343
21
                                                                mark_keys_to_process) != 0) {
5344
21
                LOG(WARNING) << "failed to batch mark recycle rowsets as recycled, instance_id="
5345
21
                             << instance_id_;
5346
21
                return;
5347
21
            }
5348
21
            if (!abort_keys_to_process.empty() &&
5349
21
                batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(abort_keys_to_process, true) !=
5350
21
                        0) {
5351
21
                return;
5352
21
            }
5353
21
            std::vector<DeferredRecyclePrepareDeleteTask> prepare_delete_tasks;
5354
21
            if (!prepare_keys_to_process.empty() &&
5355
21
                collect_prepare_delete_tasks(txn_kv_.get(), instance_id_, prepare_keys_to_process,
5356
21
                                             &prepare_delete_tasks) != 0) {
5357
21
                LOG(WARNING) << "failed to collect prepare rowset delete tasks, instance_id="
5358
21
                             << instance_id_;
5359
21
                return;
5360
21
            }
5361
21
            if (!prepare_delete_tasks.empty()) {
5362
21
                std::vector<std::string> prepare_rowset_keys_to_delete;
5363
21
                prepare_rowset_keys_to_delete.reserve(prepare_delete_tasks.size());
5364
21
                for (const auto& task : prepare_delete_tasks) {
5365
21
                    if (delete_rowset_data(task.resource_id, task.tablet_id, task.rowset_id) != 0) {
5366
21
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(task.key);
5367
21
                        return;
5368
21
                    }
5369
21
                    if (delete_versioned_delete_bitmap_kvs(task.tablet_id, task.rowset_id) != 0) {
5370
21
                        return;
5371
21
                    }
5372
21
                    prepare_rowset_keys_to_delete.emplace_back(task.key);
5373
21
                }
5374
21
                if (txn_remove(txn_kv_.get(), prepare_rowset_keys_to_delete) != 0) {
5375
21
                    LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5376
21
                                 << instance_id_;
5377
21
                    return;
5378
21
                }
5379
21
                num_recycled.fetch_add(prepare_rowset_keys_to_delete.size(),
5380
21
                                       std::memory_order_relaxed);
5381
21
            }
5382
21
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5383
21
                                   metrics_context) != 0) {
5384
21
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5385
21
                return;
5386
21
            }
5387
21
            for (const auto& [_, rs] : rowsets_to_delete) {
5388
21
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
5389
21
                    return;
5390
21
                }
5391
21
            }
5392
21
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5393
21
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5394
21
                return;
5395
21
            }
5396
21
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5397
21
        });
5398
21
        return 0;
5399
21
    };
5400
5401
22
    if (config::enable_recycler_stats_metrics) {
5402
0
        scan_and_statistics_rowsets();
5403
0
    }
5404
    // recycle_func and loop_done for scan and recycle
5405
22
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5406
22
                               std::move(loop_done));
5407
5408
22
    worker_pool->stop();
5409
5410
22
    if (!async_recycled_rowset_keys.empty()) {
5411
1
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5412
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5413
0
            return -1;
5414
1
        } else {
5415
1
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5416
1
        }
5417
1
    }
5418
5419
    // Report final metrics after all concurrent tasks completed
5420
22
    segment_metrics_context_.report();
5421
22
    metrics_context.report();
5422
5423
22
    return ret;
5424
22
}
5425
5426
13
int InstanceRecycler::recycle_restore_jobs() {
5427
13
    const std::string task_name = "recycle_restore_jobs";
5428
13
    int64_t num_scanned = 0;
5429
13
    int64_t num_expired = 0;
5430
13
    int64_t num_recycled = 0;
5431
13
    int64_t num_aborted = 0;
5432
5433
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5434
5435
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5436
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5437
13
    std::string restore_job_key0;
5438
13
    std::string restore_job_key1;
5439
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5440
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5441
5442
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5443
5444
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5445
13
    register_recycle_task(task_name, start_time);
5446
5447
13
    DORIS_CLOUD_DEFER {
5448
13
        unregister_recycle_task(task_name);
5449
13
        int64_t cost =
5450
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5451
13
        metrics_context.finish_report();
5452
5453
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5454
13
                .tag("instance_id", instance_id_)
5455
13
                .tag("num_scanned", num_scanned)
5456
13
                .tag("num_expired", num_expired)
5457
13
                .tag("num_recycled", num_recycled)
5458
13
                .tag("num_aborted", num_aborted);
5459
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5447
13
    DORIS_CLOUD_DEFER {
5448
13
        unregister_recycle_task(task_name);
5449
13
        int64_t cost =
5450
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5451
13
        metrics_context.finish_report();
5452
5453
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5454
13
                .tag("instance_id", instance_id_)
5455
13
                .tag("num_scanned", num_scanned)
5456
13
                .tag("num_expired", num_expired)
5457
13
                .tag("num_recycled", num_recycled)
5458
13
                .tag("num_aborted", num_aborted);
5459
13
    };
5460
5461
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5462
5463
13
    std::vector<std::string_view> restore_job_keys;
5464
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5465
41
        ++num_scanned;
5466
41
        RestoreJobCloudPB restore_job_pb;
5467
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5468
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5469
0
            return -1;
5470
0
        }
5471
41
        int64_t expiration =
5472
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5473
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5474
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5475
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5476
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5477
0
                   << " state=" << restore_job_pb.state();
5478
41
        int64_t current_time = ::time(nullptr);
5479
41
        if (current_time < expiration) { // not expired
5480
0
            return 0;
5481
0
        }
5482
41
        ++num_expired;
5483
5484
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5485
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5486
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5487
5488
41
        std::unique_ptr<Transaction> txn;
5489
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5490
41
        if (err != TxnErrorCode::TXN_OK) {
5491
0
            LOG_WARNING("failed to recycle restore job")
5492
0
                    .tag("err", err)
5493
0
                    .tag("tablet id", tablet_id)
5494
0
                    .tag("instance_id", instance_id_)
5495
0
                    .tag("reason", "failed to create txn");
5496
0
            return -1;
5497
0
        }
5498
5499
41
        std::string val;
5500
41
        err = txn->get(k, &val);
5501
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5502
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5503
0
            return 0;
5504
0
        }
5505
41
        if (err != TxnErrorCode::TXN_OK) {
5506
0
            LOG_WARNING("failed to get kv");
5507
0
            return -1;
5508
0
        }
5509
41
        restore_job_pb.Clear();
5510
41
        if (!restore_job_pb.ParseFromString(val)) {
5511
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5512
0
            return -1;
5513
0
        }
5514
5515
        // PREPARED or COMMITTED, change state to DROPPED and return
5516
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5517
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5518
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5519
0
            restore_job_pb.set_need_recycle_data(true);
5520
0
            txn->put(k, restore_job_pb.SerializeAsString());
5521
0
            err = txn->commit();
5522
0
            if (err != TxnErrorCode::TXN_OK) {
5523
0
                LOG_WARNING("failed to commit txn: {}", err);
5524
0
                return -1;
5525
0
            }
5526
0
            num_aborted++;
5527
0
            return 0;
5528
0
        }
5529
5530
        // Change state to RECYCLING
5531
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5532
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5533
21
            txn->put(k, restore_job_pb.SerializeAsString());
5534
21
            err = txn->commit();
5535
21
            if (err != TxnErrorCode::TXN_OK) {
5536
0
                LOG_WARNING("failed to commit txn: {}", err);
5537
0
                return -1;
5538
0
            }
5539
21
            return 0;
5540
21
        }
5541
5542
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5543
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5544
5545
        // Recycle all data associated with the restore job.
5546
        // This includes rowsets, segments, and related resources.
5547
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5548
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5549
0
            LOG_WARNING("failed to recycle tablet")
5550
0
                    .tag("tablet_id", tablet_id)
5551
0
                    .tag("instance_id", instance_id_);
5552
0
            return -1;
5553
0
        }
5554
5555
        // delete all restore job rowset kv
5556
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5557
5558
20
        err = txn->commit();
5559
20
        if (err != TxnErrorCode::TXN_OK) {
5560
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5561
0
                    .tag("err", err)
5562
0
                    .tag("tablet id", tablet_id)
5563
0
                    .tag("instance_id", instance_id_)
5564
0
                    .tag("reason", "failed to commit txn");
5565
0
            return -1;
5566
0
        }
5567
5568
20
        metrics_context.total_recycled_num = ++num_recycled;
5569
20
        metrics_context.report();
5570
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5571
20
        restore_job_keys.push_back(k);
5572
5573
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5574
20
                  << " tablet_id=" << tablet_id;
5575
20
        return 0;
5576
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
5464
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5465
41
        ++num_scanned;
5466
41
        RestoreJobCloudPB restore_job_pb;
5467
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5468
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5469
0
            return -1;
5470
0
        }
5471
41
        int64_t expiration =
5472
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5473
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5474
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5475
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5476
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5477
0
                   << " state=" << restore_job_pb.state();
5478
41
        int64_t current_time = ::time(nullptr);
5479
41
        if (current_time < expiration) { // not expired
5480
0
            return 0;
5481
0
        }
5482
41
        ++num_expired;
5483
5484
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5485
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5486
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5487
5488
41
        std::unique_ptr<Transaction> txn;
5489
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5490
41
        if (err != TxnErrorCode::TXN_OK) {
5491
0
            LOG_WARNING("failed to recycle restore job")
5492
0
                    .tag("err", err)
5493
0
                    .tag("tablet id", tablet_id)
5494
0
                    .tag("instance_id", instance_id_)
5495
0
                    .tag("reason", "failed to create txn");
5496
0
            return -1;
5497
0
        }
5498
5499
41
        std::string val;
5500
41
        err = txn->get(k, &val);
5501
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5502
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5503
0
            return 0;
5504
0
        }
5505
41
        if (err != TxnErrorCode::TXN_OK) {
5506
0
            LOG_WARNING("failed to get kv");
5507
0
            return -1;
5508
0
        }
5509
41
        restore_job_pb.Clear();
5510
41
        if (!restore_job_pb.ParseFromString(val)) {
5511
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5512
0
            return -1;
5513
0
        }
5514
5515
        // PREPARED or COMMITTED, change state to DROPPED and return
5516
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5517
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5518
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5519
0
            restore_job_pb.set_need_recycle_data(true);
5520
0
            txn->put(k, restore_job_pb.SerializeAsString());
5521
0
            err = txn->commit();
5522
0
            if (err != TxnErrorCode::TXN_OK) {
5523
0
                LOG_WARNING("failed to commit txn: {}", err);
5524
0
                return -1;
5525
0
            }
5526
0
            num_aborted++;
5527
0
            return 0;
5528
0
        }
5529
5530
        // Change state to RECYCLING
5531
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5532
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5533
21
            txn->put(k, restore_job_pb.SerializeAsString());
5534
21
            err = txn->commit();
5535
21
            if (err != TxnErrorCode::TXN_OK) {
5536
0
                LOG_WARNING("failed to commit txn: {}", err);
5537
0
                return -1;
5538
0
            }
5539
21
            return 0;
5540
21
        }
5541
5542
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5543
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5544
5545
        // Recycle all data associated with the restore job.
5546
        // This includes rowsets, segments, and related resources.
5547
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5548
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5549
0
            LOG_WARNING("failed to recycle tablet")
5550
0
                    .tag("tablet_id", tablet_id)
5551
0
                    .tag("instance_id", instance_id_);
5552
0
            return -1;
5553
0
        }
5554
5555
        // delete all restore job rowset kv
5556
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5557
5558
20
        err = txn->commit();
5559
20
        if (err != TxnErrorCode::TXN_OK) {
5560
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5561
0
                    .tag("err", err)
5562
0
                    .tag("tablet id", tablet_id)
5563
0
                    .tag("instance_id", instance_id_)
5564
0
                    .tag("reason", "failed to commit txn");
5565
0
            return -1;
5566
0
        }
5567
5568
20
        metrics_context.total_recycled_num = ++num_recycled;
5569
20
        metrics_context.report();
5570
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5571
20
        restore_job_keys.push_back(k);
5572
5573
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5574
20
                  << " tablet_id=" << tablet_id;
5575
20
        return 0;
5576
20
    };
5577
5578
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5579
3
        if (restore_job_keys.empty()) return 0;
5580
1
        DORIS_CLOUD_DEFER {
5581
1
            restore_job_keys.clear();
5582
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5580
1
        DORIS_CLOUD_DEFER {
5581
1
            restore_job_keys.clear();
5582
1
        };
5583
5584
1
        std::unique_ptr<Transaction> txn;
5585
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5586
1
        if (err != TxnErrorCode::TXN_OK) {
5587
0
            LOG_WARNING("failed to recycle restore job")
5588
0
                    .tag("err", err)
5589
0
                    .tag("instance_id", instance_id_)
5590
0
                    .tag("reason", "failed to create txn");
5591
0
            return -1;
5592
0
        }
5593
20
        for (auto& k : restore_job_keys) {
5594
20
            txn->remove(k);
5595
20
        }
5596
1
        err = txn->commit();
5597
1
        if (err != TxnErrorCode::TXN_OK) {
5598
0
            LOG_WARNING("failed to recycle restore job")
5599
0
                    .tag("err", err)
5600
0
                    .tag("instance_id", instance_id_)
5601
0
                    .tag("reason", "failed to commit txn");
5602
0
            return -1;
5603
0
        }
5604
1
        return 0;
5605
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5578
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5579
3
        if (restore_job_keys.empty()) return 0;
5580
1
        DORIS_CLOUD_DEFER {
5581
1
            restore_job_keys.clear();
5582
1
        };
5583
5584
1
        std::unique_ptr<Transaction> txn;
5585
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5586
1
        if (err != TxnErrorCode::TXN_OK) {
5587
0
            LOG_WARNING("failed to recycle restore job")
5588
0
                    .tag("err", err)
5589
0
                    .tag("instance_id", instance_id_)
5590
0
                    .tag("reason", "failed to create txn");
5591
0
            return -1;
5592
0
        }
5593
20
        for (auto& k : restore_job_keys) {
5594
20
            txn->remove(k);
5595
20
        }
5596
1
        err = txn->commit();
5597
1
        if (err != TxnErrorCode::TXN_OK) {
5598
0
            LOG_WARNING("failed to recycle restore job")
5599
0
                    .tag("err", err)
5600
0
                    .tag("instance_id", instance_id_)
5601
0
                    .tag("reason", "failed to commit txn");
5602
0
            return -1;
5603
0
        }
5604
1
        return 0;
5605
1
    };
5606
5607
13
    if (config::enable_recycler_stats_metrics) {
5608
0
        scan_and_statistics_restore_jobs();
5609
0
    }
5610
5611
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5612
13
                            std::move(loop_done));
5613
13
}
5614
5615
11
int InstanceRecycler::recycle_versioned_rowsets() {
5616
11
    const std::string task_name = "recycle_rowsets";
5617
11
    int64_t num_scanned = 0;
5618
11
    int64_t num_expired = 0;
5619
11
    int64_t num_prepare = 0;
5620
11
    int64_t num_compacted = 0;
5621
11
    int64_t num_empty_rowset = 0;
5622
11
    size_t total_rowset_key_size = 0;
5623
11
    size_t total_rowset_value_size = 0;
5624
11
    size_t expired_rowset_size = 0;
5625
11
    std::atomic_long num_recycled = 0;
5626
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5627
5628
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5629
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5630
11
    std::string recyc_rs_key0;
5631
11
    std::string recyc_rs_key1;
5632
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5633
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5634
5635
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5636
5637
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5638
11
    register_recycle_task(task_name, start_time);
5639
5640
11
    DORIS_CLOUD_DEFER {
5641
11
        unregister_recycle_task(task_name);
5642
11
        int64_t cost =
5643
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5644
11
        metrics_context.finish_report();
5645
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5646
11
                .tag("instance_id", instance_id_)
5647
11
                .tag("num_scanned", num_scanned)
5648
11
                .tag("num_expired", num_expired)
5649
11
                .tag("num_recycled", num_recycled)
5650
11
                .tag("num_recycled.prepare", num_prepare)
5651
11
                .tag("num_recycled.compacted", num_compacted)
5652
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5653
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5654
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5655
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5656
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
5640
11
    DORIS_CLOUD_DEFER {
5641
11
        unregister_recycle_task(task_name);
5642
11
        int64_t cost =
5643
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5644
11
        metrics_context.finish_report();
5645
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5646
11
                .tag("instance_id", instance_id_)
5647
11
                .tag("num_scanned", num_scanned)
5648
11
                .tag("num_expired", num_expired)
5649
11
                .tag("num_recycled", num_recycled)
5650
11
                .tag("num_recycled.prepare", num_prepare)
5651
11
                .tag("num_recycled.compacted", num_compacted)
5652
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5653
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5654
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5655
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
5656
11
    };
5657
5658
11
    std::vector<std::string> orphan_rowset_keys;
5659
5660
    // Store keys of rowset recycled by background workers
5661
11
    std::mutex async_recycled_rowset_keys_mutex;
5662
11
    std::vector<std::string> async_recycled_rowset_keys;
5663
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5664
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5665
11
    worker_pool->start();
5666
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5667
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5668
        // Try to delete rowset data in background thread
5669
400
        int ret = worker_pool->submit_with_timeout(
5670
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5671
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5672
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5673
400
                        return;
5674
400
                    }
5675
                    // The async recycled rowsets are staled format or has not been used,
5676
                    // so we don't need to check the rowset ref count key.
5677
0
                    std::vector<std::string> keys;
5678
0
                    {
5679
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5680
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5681
0
                        if (async_recycled_rowset_keys.size() > 100) {
5682
0
                            keys.swap(async_recycled_rowset_keys);
5683
0
                        }
5684
0
                    }
5685
0
                    if (keys.empty()) return;
5686
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5687
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5688
0
                                     << instance_id_;
5689
0
                    } else {
5690
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5691
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5692
0
                                           num_recycled, start_time);
5693
0
                    }
5694
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
5670
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5671
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5672
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5673
400
                        return;
5674
400
                    }
5675
                    // The async recycled rowsets are staled format or has not been used,
5676
                    // so we don't need to check the rowset ref count key.
5677
0
                    std::vector<std::string> keys;
5678
0
                    {
5679
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5680
0
                        async_recycled_rowset_keys.push_back(std::move(key));
5681
0
                        if (async_recycled_rowset_keys.size() > 100) {
5682
0
                            keys.swap(async_recycled_rowset_keys);
5683
0
                        }
5684
0
                    }
5685
0
                    if (keys.empty()) return;
5686
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5687
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5688
0
                                     << instance_id_;
5689
0
                    } else {
5690
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5691
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5692
0
                                           num_recycled, start_time);
5693
0
                    }
5694
0
                },
5695
400
                0);
5696
400
        if (ret == 0) return 0;
5697
        // Submit task failed, delete rowset data in current thread
5698
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5699
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5700
0
            return -1;
5701
0
        }
5702
0
        orphan_rowset_keys.push_back(std::move(key));
5703
0
        return 0;
5704
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
5667
400
                                            int64_t tablet_id, const std::string& rowset_id) {
5668
        // Try to delete rowset data in background thread
5669
400
        int ret = worker_pool->submit_with_timeout(
5670
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
5671
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5672
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5673
400
                        return;
5674
400
                    }
5675
                    // The async recycled rowsets are staled format or has not been used,
5676
                    // so we don't need to check the rowset ref count key.
5677
400
                    std::vector<std::string> keys;
5678
400
                    {
5679
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5680
400
                        async_recycled_rowset_keys.push_back(std::move(key));
5681
400
                        if (async_recycled_rowset_keys.size() > 100) {
5682
400
                            keys.swap(async_recycled_rowset_keys);
5683
400
                        }
5684
400
                    }
5685
400
                    if (keys.empty()) return;
5686
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5687
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5688
400
                                     << instance_id_;
5689
400
                    } else {
5690
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5691
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5692
400
                                           num_recycled, start_time);
5693
400
                    }
5694
400
                },
5695
400
                0);
5696
400
        if (ret == 0) return 0;
5697
        // Submit task failed, delete rowset data in current thread
5698
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5699
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5700
0
            return -1;
5701
0
        }
5702
0
        orphan_rowset_keys.push_back(std::move(key));
5703
0
        return 0;
5704
0
    };
5705
5706
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5707
5708
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5709
2.01k
        ++num_scanned;
5710
2.01k
        total_rowset_key_size += k.size();
5711
2.01k
        total_rowset_value_size += v.size();
5712
2.01k
        RecycleRowsetPB rowset;
5713
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5714
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5715
0
            return -1;
5716
0
        }
5717
5718
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5719
5720
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5721
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5722
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5723
2.01k
        int64_t current_time = ::time(nullptr);
5724
2.01k
        if (current_time < final_expiration) { // not expired
5725
0
            return 0;
5726
0
        }
5727
2.01k
        ++num_expired;
5728
2.01k
        expired_rowset_size += v.size();
5729
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5730
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5731
                // in old version, keep this key-value pair and it needs to be checked manually
5732
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5733
0
                return -1;
5734
0
            }
5735
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5736
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5737
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5738
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5739
0
                orphan_rowset_keys.emplace_back(k);
5740
0
                return -1;
5741
0
            }
5742
            // decode rowset_id
5743
0
            auto k1 = k;
5744
0
            k1.remove_prefix(1);
5745
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5746
0
            decode_key(&k1, &out);
5747
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5748
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5749
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5750
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5751
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5752
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5753
0
                return -1;
5754
0
            }
5755
0
            return 0;
5756
0
        }
5757
        // TODO(plat1ko): check rowset not referenced
5758
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5759
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5760
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5761
0
                LOG_INFO("recycle rowset that has empty resource id");
5762
0
            } else {
5763
                // other situations, keep this key-value pair and it needs to be checked manually
5764
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5765
0
                return -1;
5766
0
            }
5767
0
        }
5768
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5769
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5770
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5771
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5772
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5773
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5774
2.01k
                  << " rowset_meta_size=" << v.size()
5775
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5776
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5777
            // unable to calculate file path, can only be deleted by rowset id prefix
5778
400
            num_prepare += 1;
5779
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5780
400
                                             rowset_meta->tablet_id(),
5781
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5782
0
                return -1;
5783
0
            }
5784
1.61k
        } else {
5785
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5786
1.61k
            worker_pool->submit(
5787
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5788
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5789
1.60k
                            return;
5790
1.60k
                        }
5791
13
                        num_compacted += is_compacted;
5792
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5793
13
                        if (rowset_meta.num_segments() == 0) {
5794
0
                            ++num_empty_rowset;
5795
0
                        }
5796
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
5787
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5788
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5789
1.60k
                            return;
5790
1.60k
                        }
5791
13
                        num_compacted += is_compacted;
5792
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5793
13
                        if (rowset_meta.num_segments() == 0) {
5794
0
                            ++num_empty_rowset;
5795
0
                        }
5796
13
                    });
5797
1.61k
        }
5798
2.01k
        return 0;
5799
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
5708
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
5709
2.01k
        ++num_scanned;
5710
2.01k
        total_rowset_key_size += k.size();
5711
2.01k
        total_rowset_value_size += v.size();
5712
2.01k
        RecycleRowsetPB rowset;
5713
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5714
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5715
0
            return -1;
5716
0
        }
5717
5718
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5719
5720
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5721
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
5722
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5723
2.01k
        int64_t current_time = ::time(nullptr);
5724
2.01k
        if (current_time < final_expiration) { // not expired
5725
0
            return 0;
5726
0
        }
5727
2.01k
        ++num_expired;
5728
2.01k
        expired_rowset_size += v.size();
5729
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5730
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5731
                // in old version, keep this key-value pair and it needs to be checked manually
5732
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5733
0
                return -1;
5734
0
            }
5735
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5736
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5737
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5738
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5739
0
                orphan_rowset_keys.emplace_back(k);
5740
0
                return -1;
5741
0
            }
5742
            // decode rowset_id
5743
0
            auto k1 = k;
5744
0
            k1.remove_prefix(1);
5745
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5746
0
            decode_key(&k1, &out);
5747
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5748
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5749
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5750
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
5751
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
5752
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5753
0
                return -1;
5754
0
            }
5755
0
            return 0;
5756
0
        }
5757
        // TODO(plat1ko): check rowset not referenced
5758
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
5759
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5760
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5761
0
                LOG_INFO("recycle rowset that has empty resource id");
5762
0
            } else {
5763
                // other situations, keep this key-value pair and it needs to be checked manually
5764
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5765
0
                return -1;
5766
0
            }
5767
0
        }
5768
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5769
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
5770
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5771
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5772
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
5773
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5774
2.01k
                  << " rowset_meta_size=" << v.size()
5775
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
5776
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5777
            // unable to calculate file path, can only be deleted by rowset id prefix
5778
400
            num_prepare += 1;
5779
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5780
400
                                             rowset_meta->tablet_id(),
5781
400
                                             rowset_meta->rowset_id_v2()) != 0) {
5782
0
                return -1;
5783
0
            }
5784
1.61k
        } else {
5785
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
5786
1.61k
            worker_pool->submit(
5787
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
5788
1.61k
                        if (recycle_rowset_meta_and_data(k, rowset_meta) != 0) {
5789
1.61k
                            return;
5790
1.61k
                        }
5791
1.61k
                        num_compacted += is_compacted;
5792
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
5793
1.61k
                        if (rowset_meta.num_segments() == 0) {
5794
1.61k
                            ++num_empty_rowset;
5795
1.61k
                        }
5796
1.61k
                    });
5797
1.61k
        }
5798
2.01k
        return 0;
5799
2.01k
    };
5800
5801
11
    if (config::enable_recycler_stats_metrics) {
5802
0
        scan_and_statistics_rowsets();
5803
0
    }
5804
5805
11
    auto loop_done = [&]() -> int {
5806
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5807
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5808
0
        }
5809
6
        orphan_rowset_keys.clear();
5810
6
        return 0;
5811
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clEv
Line
Count
Source
5805
6
    auto loop_done = [&]() -> int {
5806
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
5807
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5808
0
        }
5809
6
        orphan_rowset_keys.clear();
5810
6
        return 0;
5811
6
    };
5812
5813
    // recycle_func and loop_done for scan and recycle
5814
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5815
11
                               std::move(loop_done));
5816
5817
11
    worker_pool->stop();
5818
5819
11
    if (!async_recycled_rowset_keys.empty()) {
5820
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5821
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5822
0
            return -1;
5823
0
        } else {
5824
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5825
0
        }
5826
0
    }
5827
5828
    // Report final metrics after all concurrent tasks completed
5829
11
    segment_metrics_context_.report();
5830
11
    metrics_context.report();
5831
5832
11
    return ret;
5833
11
}
5834
5835
int InstanceRecycler::recycle_rowset_meta_and_data(std::string_view recycle_rowset_key,
5836
                                                   const RowsetMetaCloudPB& rowset_meta,
5837
1.61k
                                                   std::string_view non_versioned_rowset_key) {
5838
1.61k
    constexpr int MAX_RETRY = 10;
5839
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
5840
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
5841
1.61k
    std::string_view reference_instance_id = instance_id_;
5842
1.61k
    if (rowset_meta.has_reference_instance_id()) {
5843
8
        reference_instance_id = rowset_meta.reference_instance_id();
5844
8
    }
5845
5846
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
5847
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
5848
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(recycle_rowset_key));
5849
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
5850
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
5851
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
5852
1.61k
        std::unique_ptr<Transaction> txn;
5853
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5854
1.61k
        if (err != TxnErrorCode::TXN_OK) {
5855
0
            LOG_WARNING("failed to create txn").tag("err", err);
5856
0
            return -1;
5857
0
        }
5858
5859
1.61k
        std::string rowset_ref_count_key =
5860
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
5861
1.61k
        int64_t ref_count = 0;
5862
1.61k
        {
5863
1.61k
            std::string value;
5864
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
5865
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
5866
                // This is the old version rowset, we could recycle it directly.
5867
1.60k
                ref_count = 1;
5868
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
5869
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
5870
0
                return -1;
5871
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
5872
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
5873
0
                return -1;
5874
0
            }
5875
1.61k
        }
5876
5877
1.61k
        if (ref_count == 1) {
5878
            // It would not be added since it is recycling.
5879
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
5880
1.60k
                LOG_WARNING("failed to delete rowset data");
5881
1.60k
                return -1;
5882
1.60k
            }
5883
5884
            // Reset the transaction to avoid timeout.
5885
10
            err = txn_kv_->create_txn(&txn);
5886
10
            if (err != TxnErrorCode::TXN_OK) {
5887
0
                LOG_WARNING("failed to create txn").tag("err", err);
5888
0
                return -1;
5889
0
            }
5890
10
            txn->remove(rowset_ref_count_key);
5891
10
            LOG_INFO("delete rowset data ref count key")
5892
10
                    .tag("txn_id", rowset_meta.txn_id())
5893
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5894
5895
10
            std::string dbm_start_key =
5896
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
5897
10
            std::string dbm_end_key = meta_delete_bitmap_key(
5898
10
                    {reference_instance_id, tablet_id, rowset_id,
5899
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
5900
10
            txn->remove(dbm_start_key, dbm_end_key);
5901
10
            LOG_INFO("remove delete bitmap kv")
5902
10
                    .tag("begin", hex(dbm_start_key))
5903
10
                    .tag("end", hex(dbm_end_key));
5904
5905
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
5906
10
                    {reference_instance_id, tablet_id, rowset_id});
5907
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
5908
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
5909
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
5910
10
            LOG_INFO("remove versioned delete bitmap kv")
5911
10
                    .tag("begin", hex(versioned_dbm_start_key))
5912
10
                    .tag("end", hex(versioned_dbm_end_key));
5913
5914
10
            std::string meta_rowset_key_begin =
5915
10
                    versioned::meta_rowset_key({reference_instance_id, tablet_id, rowset_id});
5916
10
            std::string meta_rowset_key_end = meta_rowset_key_begin;
5917
10
            encode_int64(INT64_MAX, &meta_rowset_key_end);
5918
10
            txn->remove(meta_rowset_key_begin, meta_rowset_key_end);
5919
10
            LOG_INFO("remove meta rowset key").tag("key", hex(meta_rowset_key_begin));
5920
10
        } else {
5921
            // Decrease the rowset ref count.
5922
            //
5923
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
5924
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
5925
3
            txn->atomic_add(rowset_ref_count_key, -1);
5926
3
            LOG_INFO("decrease rowset data ref count")
5927
3
                    .tag("txn_id", rowset_meta.txn_id())
5928
3
                    .tag("ref_count", ref_count - 1)
5929
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
5930
3
        }
5931
5932
13
        if (!recycle_rowset_key.empty()) { // empty when recycle ref rowsets for deleted instance
5933
13
            txn->remove(recycle_rowset_key);
5934
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(recycle_rowset_key));
5935
13
        }
5936
13
        if (!non_versioned_rowset_key.empty()) {
5937
0
            txn->remove(non_versioned_rowset_key);
5938
0
            LOG_INFO("remove non versioned rowset key").tag("key", hex(non_versioned_rowset_key));
5939
0
        }
5940
5941
13
        err = txn->commit();
5942
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
5943
            // The rowset ref count key has been changed, we need to retry.
5944
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
5945
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
5946
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
5947
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
5948
0
            continue;
5949
13
        } else if (err != TxnErrorCode::TXN_OK) {
5950
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
5951
0
            return -1;
5952
0
        }
5953
13
        LOG_INFO("recycle rowset meta and data success");
5954
13
        return 0;
5955
13
    }
5956
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
5957
0
            .tag("tablet_id", tablet_id)
5958
0
            .tag("rowset_id", rowset_id)
5959
0
            .tag("retry", MAX_RETRY);
5960
0
    return -1;
5961
1.61k
}
5962
5963
35
int InstanceRecycler::recycle_tmp_rowsets() {
5964
35
    const std::string task_name = "recycle_tmp_rowsets";
5965
35
    int64_t num_scanned = 0;
5966
35
    int64_t num_expired = 0;
5967
35
    std::atomic_long num_recycled = 0;
5968
35
    size_t expired_rowset_size = 0;
5969
35
    size_t total_rowset_key_size = 0;
5970
35
    size_t total_rowset_value_size = 0;
5971
35
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5972
5973
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
5974
35
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
5975
35
    std::string tmp_rs_key0;
5976
35
    std::string tmp_rs_key1;
5977
35
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
5978
35
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
5979
5980
35
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
5981
5982
35
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5983
35
    register_recycle_task(task_name, start_time);
5984
5985
35
    DORIS_CLOUD_DEFER {
5986
35
        unregister_recycle_task(task_name);
5987
35
        int64_t cost =
5988
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5989
35
        metrics_context.finish_report();
5990
35
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5991
35
                .tag("instance_id", instance_id_)
5992
35
                .tag("num_scanned", num_scanned)
5993
35
                .tag("num_expired", num_expired)
5994
35
                .tag("num_recycled", num_recycled)
5995
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5996
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5997
35
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5998
35
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5985
12
    DORIS_CLOUD_DEFER {
5986
12
        unregister_recycle_task(task_name);
5987
12
        int64_t cost =
5988
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5989
12
        metrics_context.finish_report();
5990
12
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5991
12
                .tag("instance_id", instance_id_)
5992
12
                .tag("num_scanned", num_scanned)
5993
12
                .tag("num_expired", num_expired)
5994
12
                .tag("num_recycled", num_recycled)
5995
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5996
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5997
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5998
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
5985
23
    DORIS_CLOUD_DEFER {
5986
23
        unregister_recycle_task(task_name);
5987
23
        int64_t cost =
5988
23
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5989
23
        metrics_context.finish_report();
5990
23
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
5991
23
                .tag("instance_id", instance_id_)
5992
23
                .tag("num_scanned", num_scanned)
5993
23
                .tag("num_expired", num_expired)
5994
23
                .tag("num_recycled", num_recycled)
5995
23
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5996
23
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5997
23
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
5998
23
    };
5999
6000
    // Elements in `tmp_rowset_keys` has the same lifetime as `it`
6001
6002
35
    std::vector<std::string> tmp_rowset_keys;
6003
35
    std::vector<std::string> tmp_rowset_ref_count_keys;
6004
35
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6005
35
    std::vector<std::string> tmp_rowset_keys_to_abort;
6006
6007
    // rowset_id -> rowset_meta
6008
    // store tmp_rowset id and meta for statistics rs size when delete
6009
35
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6010
35
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6011
35
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6012
35
    worker_pool->start();
6013
6014
35
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6015
6016
35
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &tmp_rowsets,
6017
35
                             &expired_rowset_size, &total_rowset_key_size, &total_rowset_value_size,
6018
35
                             &earlest_ts, &tmp_rowset_ref_count_keys,
6019
35
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6020
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6021
53.0k
        ++num_scanned;
6022
53.0k
        total_rowset_key_size += k.size();
6023
53.0k
        total_rowset_value_size += v.size();
6024
53.0k
        doris::RowsetMetaCloudPB rowset;
6025
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6026
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6027
0
            return -1;
6028
0
        }
6029
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6030
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6031
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6032
0
                   << " txn_expiration=" << rowset.txn_expiration()
6033
0
                   << " rowset_creation_time=" << rowset.creation_time();
6034
53.0k
        int64_t current_time = ::time(nullptr);
6035
53.0k
        if (current_time < expiration) { // not expired
6036
0
            return 0;
6037
0
        }
6038
6039
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6040
16
            if (need_mark_rowset_as_recycled(rowset)) {
6041
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6042
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6043
9
                             "at next turn, instance_id="
6044
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6045
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6046
9
                return 0;
6047
9
            }
6048
16
        }
6049
6050
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6051
7
            if (make_deferred_abort_task(rowset).has_value()) {
6052
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6053
3
                             "instance_id="
6054
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6055
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6056
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6057
3
            }
6058
7
        }
6059
6060
53.0k
        ++num_expired;
6061
53.0k
        expired_rowset_size += v.size();
6062
53.0k
        if (!rowset.has_resource_id()) {
6063
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6064
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6065
0
                return -1;
6066
0
            }
6067
            // might be a delete pred rowset
6068
0
            tmp_rowset_keys.emplace_back(k);
6069
0
            return 0;
6070
0
        }
6071
        // TODO(plat1ko): check rowset not referenced
6072
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6073
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6074
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6075
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6076
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6077
53.0k
                  << " num_expired=" << num_expired
6078
53.0k
                  << " task_type=" << metrics_context.operation_type;
6079
6080
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6081
        // Remove the rowset ref count key directly since it has not been used.
6082
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6083
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6084
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6085
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6086
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6087
6088
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6089
53.0k
        return 0;
6090
53.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6020
16
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6021
16
        ++num_scanned;
6022
16
        total_rowset_key_size += k.size();
6023
16
        total_rowset_value_size += v.size();
6024
16
        doris::RowsetMetaCloudPB rowset;
6025
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6026
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6027
0
            return -1;
6028
0
        }
6029
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6030
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6031
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6032
0
                   << " txn_expiration=" << rowset.txn_expiration()
6033
0
                   << " rowset_creation_time=" << rowset.creation_time();
6034
16
        int64_t current_time = ::time(nullptr);
6035
16
        if (current_time < expiration) { // not expired
6036
0
            return 0;
6037
0
        }
6038
6039
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6040
16
            if (need_mark_rowset_as_recycled(rowset)) {
6041
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6042
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6043
9
                             "at next turn, instance_id="
6044
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6045
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6046
9
                return 0;
6047
9
            }
6048
16
        }
6049
6050
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6051
7
            if (make_deferred_abort_task(rowset).has_value()) {
6052
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6053
3
                             "instance_id="
6054
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6055
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6056
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6057
3
            }
6058
7
        }
6059
6060
7
        ++num_expired;
6061
7
        expired_rowset_size += v.size();
6062
7
        if (!rowset.has_resource_id()) {
6063
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6064
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6065
0
                return -1;
6066
0
            }
6067
            // might be a delete pred rowset
6068
0
            tmp_rowset_keys.emplace_back(k);
6069
0
            return 0;
6070
0
        }
6071
        // TODO(plat1ko): check rowset not referenced
6072
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6073
7
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6074
7
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6075
7
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6076
7
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6077
7
                  << " num_expired=" << num_expired
6078
7
                  << " task_type=" << metrics_context.operation_type;
6079
6080
7
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6081
        // Remove the rowset ref count key directly since it has not been used.
6082
7
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6083
7
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6084
7
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6085
7
                  << "key=" << hex(rowset_ref_count_key);
6086
7
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6087
6088
7
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6089
7
        return 0;
6090
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6020
53.0k
                             &metrics_context](std::string_view k, std::string_view v) -> int {
6021
53.0k
        ++num_scanned;
6022
53.0k
        total_rowset_key_size += k.size();
6023
53.0k
        total_rowset_value_size += v.size();
6024
53.0k
        doris::RowsetMetaCloudPB rowset;
6025
53.0k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6026
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6027
0
            return -1;
6028
0
        }
6029
53.0k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6030
53.0k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6031
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6032
0
                   << " txn_expiration=" << rowset.txn_expiration()
6033
0
                   << " rowset_creation_time=" << rowset.creation_time();
6034
53.0k
        int64_t current_time = ::time(nullptr);
6035
53.0k
        if (current_time < expiration) { // not expired
6036
0
            return 0;
6037
0
        }
6038
6039
53.0k
        if (config::enable_mark_delete_rowset_before_recycle) {
6040
0
            if (need_mark_rowset_as_recycled(rowset)) {
6041
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6042
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6043
0
                             "at next turn, instance_id="
6044
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6045
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6046
0
                return 0;
6047
0
            }
6048
0
        }
6049
6050
53.0k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6051
0
            if (make_deferred_abort_task(rowset).has_value()) {
6052
0
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6053
0
                             "instance_id="
6054
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6055
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6056
0
                tmp_rowset_keys_to_abort.emplace_back(k);
6057
0
            }
6058
0
        }
6059
6060
53.0k
        ++num_expired;
6061
53.0k
        expired_rowset_size += v.size();
6062
53.0k
        if (!rowset.has_resource_id()) {
6063
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6064
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6065
0
                return -1;
6066
0
            }
6067
            // might be a delete pred rowset
6068
0
            tmp_rowset_keys.emplace_back(k);
6069
0
            return 0;
6070
0
        }
6071
        // TODO(plat1ko): check rowset not referenced
6072
53.0k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6073
53.0k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6074
53.0k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6075
53.0k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6076
53.0k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6077
53.0k
                  << " num_expired=" << num_expired
6078
53.0k
                  << " task_type=" << metrics_context.operation_type;
6079
6080
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6081
        // Remove the rowset ref count key directly since it has not been used.
6082
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6083
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6084
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6085
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6086
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6087
6088
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6089
53.0k
        return 0;
6090
53.0k
    };
6091
6092
    // TODO bacth delete
6093
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6094
51.0k
        std::string dbm_start_key =
6095
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6096
51.0k
        std::string dbm_end_key = dbm_start_key;
6097
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6098
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6099
51.0k
        if (ret != 0) {
6100
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6101
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6102
0
                         << ", rowset_id=" << rowset_id;
6103
0
        }
6104
51.0k
        return ret;
6105
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6093
7
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6094
7
        std::string dbm_start_key =
6095
7
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6096
7
        std::string dbm_end_key = dbm_start_key;
6097
7
        encode_int64(INT64_MAX, &dbm_end_key);
6098
7
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6099
7
        if (ret != 0) {
6100
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6101
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6102
0
                         << ", rowset_id=" << rowset_id;
6103
0
        }
6104
7
        return ret;
6105
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_3clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6093
51.0k
    auto delete_versioned_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6094
51.0k
        std::string dbm_start_key =
6095
51.0k
                versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
6096
51.0k
        std::string dbm_end_key = dbm_start_key;
6097
51.0k
        encode_int64(INT64_MAX, &dbm_end_key);
6098
51.0k
        auto ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
6099
51.0k
        if (ret != 0) {
6100
0
            LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6101
0
                         << instance_id_ << ", tablet_id=" << tablet_id
6102
0
                         << ", rowset_id=" << rowset_id;
6103
0
        }
6104
51.0k
        return ret;
6105
51.0k
    };
6106
6107
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6108
51.0k
        auto delete_bitmap_start =
6109
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6110
51.0k
        auto delete_bitmap_end =
6111
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6112
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6113
51.0k
        if (ret != 0) {
6114
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6115
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6116
0
        }
6117
51.0k
        return ret;
6118
51.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6107
7
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6108
7
        auto delete_bitmap_start =
6109
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6110
7
        auto delete_bitmap_end =
6111
7
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6112
7
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6113
7
        if (ret != 0) {
6114
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6115
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6116
0
        }
6117
7
        return ret;
6118
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_4clElRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6107
51.0k
    auto delete_delete_bitmap_kvs = [&](int64_t tablet_id, const std::string& rowset_id) {
6108
51.0k
        auto delete_bitmap_start =
6109
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
6110
51.0k
        auto delete_bitmap_end =
6111
51.0k
                meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
6112
51.0k
        auto ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
6113
51.0k
        if (ret != 0) {
6114
0
            LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
6115
0
                         << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
6116
0
        }
6117
51.0k
        return ret;
6118
51.0k
    };
6119
6120
35
    auto loop_done = [&]() -> int {
6121
22
        std::vector<std::string> tmp_rowset_keys_to_delete;
6122
22
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6123
22
        std::vector<std::string> mark_keys_to_process;
6124
22
        std::vector<std::string> abort_keys_to_process;
6125
22
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6126
22
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6127
22
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6128
22
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6129
22
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6130
22
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6131
22
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6132
22
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6133
22
                             tmp_rowset_ref_count_keys_to_delete =
6134
22
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6135
22
                             mark_keys_to_process = std::move(mark_keys_to_process),
6136
22
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6137
22
            if (!mark_keys_to_process.empty() &&
6138
22
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6139
7
                                                                  mark_keys_to_process) != 0) {
6140
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6141
0
                             << instance_id_;
6142
0
                return;
6143
0
            }
6144
22
            if (!abort_keys_to_process.empty() &&
6145
22
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6146
3
                                                                      false) != 0) {
6147
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6148
0
                             << instance_id_;
6149
0
                return;
6150
0
            }
6151
22
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6152
22
                                   metrics_context) != 0) {
6153
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6154
2
                return;
6155
2
            }
6156
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6157
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6158
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6159
0
                                 << rs.ShortDebugString();
6160
0
                    return;
6161
0
                }
6162
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6163
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6164
0
                                 << rs.ShortDebugString();
6165
0
                    return;
6166
0
                }
6167
51.0k
            }
6168
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6169
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6170
0
                return;
6171
0
            }
6172
20
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6173
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6174
0
                return;
6175
0
            }
6176
20
            num_recycled += tmp_rowset_keys_to_delete.size();
6177
20
            return;
6178
20
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6136
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6137
12
            if (!mark_keys_to_process.empty() &&
6138
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6139
7
                                                                  mark_keys_to_process) != 0) {
6140
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6141
0
                             << instance_id_;
6142
0
                return;
6143
0
            }
6144
12
            if (!abort_keys_to_process.empty() &&
6145
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6146
3
                                                                      false) != 0) {
6147
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6148
0
                             << instance_id_;
6149
0
                return;
6150
0
            }
6151
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6152
12
                                   metrics_context) != 0) {
6153
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6154
0
                return;
6155
0
            }
6156
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6157
7
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6158
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6159
0
                                 << rs.ShortDebugString();
6160
0
                    return;
6161
0
                }
6162
7
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6163
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6164
0
                                 << rs.ShortDebugString();
6165
0
                    return;
6166
0
                }
6167
7
            }
6168
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6169
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6170
0
                return;
6171
0
            }
6172
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6173
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6174
0
                return;
6175
0
            }
6176
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6177
12
            return;
6178
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6136
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6137
10
            if (!mark_keys_to_process.empty() &&
6138
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6139
0
                                                                  mark_keys_to_process) != 0) {
6140
0
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6141
0
                             << instance_id_;
6142
0
                return;
6143
0
            }
6144
10
            if (!abort_keys_to_process.empty() &&
6145
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6146
0
                                                                      false) != 0) {
6147
0
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6148
0
                             << instance_id_;
6149
0
                return;
6150
0
            }
6151
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6152
10
                                   metrics_context) != 0) {
6153
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6154
2
                return;
6155
2
            }
6156
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6157
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6158
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6159
0
                                 << rs.ShortDebugString();
6160
0
                    return;
6161
0
                }
6162
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6163
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6164
0
                                 << rs.ShortDebugString();
6165
0
                    return;
6166
0
                }
6167
51.0k
            }
6168
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6169
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6170
0
                return;
6171
0
            }
6172
8
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6173
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6174
0
                return;
6175
0
            }
6176
8
            num_recycled += tmp_rowset_keys_to_delete.size();
6177
8
            return;
6178
8
        });
6179
22
        return 0;
6180
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6120
12
    auto loop_done = [&]() -> int {
6121
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6122
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6123
12
        std::vector<std::string> mark_keys_to_process;
6124
12
        std::vector<std::string> abort_keys_to_process;
6125
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6126
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6127
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6128
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6129
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6130
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6131
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6132
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6133
12
                             tmp_rowset_ref_count_keys_to_delete =
6134
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6135
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6136
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6137
12
            if (!mark_keys_to_process.empty() &&
6138
12
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6139
12
                                                                  mark_keys_to_process) != 0) {
6140
12
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6141
12
                             << instance_id_;
6142
12
                return;
6143
12
            }
6144
12
            if (!abort_keys_to_process.empty() &&
6145
12
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6146
12
                                                                      false) != 0) {
6147
12
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6148
12
                             << instance_id_;
6149
12
                return;
6150
12
            }
6151
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6152
12
                                   metrics_context) != 0) {
6153
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6154
12
                return;
6155
12
            }
6156
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6157
12
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6158
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6159
12
                                 << rs.ShortDebugString();
6160
12
                    return;
6161
12
                }
6162
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6163
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6164
12
                                 << rs.ShortDebugString();
6165
12
                    return;
6166
12
                }
6167
12
            }
6168
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6169
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6170
12
                return;
6171
12
            }
6172
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6173
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6174
12
                return;
6175
12
            }
6176
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6177
12
            return;
6178
12
        });
6179
12
        return 0;
6180
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clEv
Line
Count
Source
6120
10
    auto loop_done = [&]() -> int {
6121
10
        std::vector<std::string> tmp_rowset_keys_to_delete;
6122
10
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6123
10
        std::vector<std::string> mark_keys_to_process;
6124
10
        std::vector<std::string> abort_keys_to_process;
6125
10
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6126
10
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6127
10
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6128
10
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6129
10
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6130
10
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6131
10
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6132
10
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6133
10
                             tmp_rowset_ref_count_keys_to_delete =
6134
10
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6135
10
                             mark_keys_to_process = std::move(mark_keys_to_process),
6136
10
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6137
10
            if (!mark_keys_to_process.empty() &&
6138
10
                batch_mark_rowsets_as_recycled<RowsetMetaCloudPB>(txn_kv_.get(), instance_id_,
6139
10
                                                                  mark_keys_to_process) != 0) {
6140
10
                LOG(WARNING) << "failed to batch mark tmp rowsets as recycled, instance_id="
6141
10
                             << instance_id_;
6142
10
                return;
6143
10
            }
6144
10
            if (!abort_keys_to_process.empty() &&
6145
10
                batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(abort_keys_to_process,
6146
10
                                                                      false) != 0) {
6147
10
                LOG(WARNING) << "failed to batch abort txn or job for releated rowset, instance_id="
6148
10
                             << instance_id_;
6149
10
                return;
6150
10
            }
6151
10
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6152
10
                                   metrics_context) != 0) {
6153
10
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6154
10
                return;
6155
10
            }
6156
10
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6157
10
                if (delete_versioned_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6158
10
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6159
10
                                 << rs.ShortDebugString();
6160
10
                    return;
6161
10
                }
6162
10
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6163
10
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6164
10
                                 << rs.ShortDebugString();
6165
10
                    return;
6166
10
                }
6167
10
            }
6168
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6169
10
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6170
10
                return;
6171
10
            }
6172
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6173
10
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6174
10
                return;
6175
10
            }
6176
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6177
10
            return;
6178
10
        });
6179
10
        return 0;
6180
10
    };
6181
6182
35
    if (config::enable_recycler_stats_metrics) {
6183
0
        scan_and_statistics_tmp_rowsets();
6184
0
    }
6185
    // recycle_func and loop_done for scan and recycle
6186
35
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6187
35
                               std::move(loop_done));
6188
6189
35
    worker_pool->stop();
6190
6191
    // Report final metrics after all concurrent tasks completed
6192
35
    segment_metrics_context_.report();
6193
35
    metrics_context.report();
6194
6195
35
    return ret;
6196
35
}
6197
6198
int InstanceRecycler::scan_and_recycle(
6199
        std::string begin, std::string_view end,
6200
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6201
268
        std::function<int()> loop_done) {
6202
268
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6203
268
    int ret = 0;
6204
268
    int64_t cnt = 0;
6205
268
    int get_range_retried = 0;
6206
268
    std::string err;
6207
268
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6208
267
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6209
267
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6210
267
                  << " ret=" << ret << " err=" << err;
6211
267
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6207
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6208
31
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6209
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6210
31
                  << " ret=" << ret << " err=" << err;
6211
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6207
236
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6208
236
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6209
236
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6210
236
                  << " ret=" << ret << " err=" << err;
6211
236
    };
6212
6213
268
    std::unique_ptr<RangeGetIterator> it;
6214
296
    do {
6215
296
        if (get_range_retried > 1000) {
6216
0
            err = "txn_get exceeds max retry, may not scan all keys";
6217
0
            ret = -1;
6218
0
            return -1;
6219
0
        }
6220
296
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6221
296
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6222
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6223
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6224
0
                         << " get_range_retried=" << get_range_retried;
6225
0
            ++get_range_retried;
6226
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6227
0
            continue; // try again
6228
0
        }
6229
296
        if (!it->has_next()) {
6230
143
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6231
143
            break; // scan finished
6232
143
        }
6233
97.5k
        while (it->has_next()) {
6234
97.4k
            ++cnt;
6235
            // recycle corresponding resources
6236
97.4k
            auto [k, v] = it->next();
6237
97.4k
            if (!it->has_next()) {
6238
153
                begin = k;
6239
153
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6240
153
            }
6241
            // if we want to continue scanning, the recycle_func should not return non-zero
6242
97.4k
            if (recycle_func(k, v) != 0) {
6243
4.00k
                err = "recycle_func error";
6244
4.00k
                ret = -1;
6245
4.00k
            }
6246
97.4k
        }
6247
153
        begin.push_back('\x00'); // Update to next smallest key for iteration
6248
        // if we want to continue scanning, the recycle_func should not return non-zero
6249
153
        if (loop_done && loop_done() != 0) {
6250
5
            err = "loop_done error";
6251
5
            ret = -1;
6252
5
        }
6253
153
    } while (it->more() && !stopped());
6254
268
    return ret;
6255
268
}
6256
6257
19
int InstanceRecycler::abort_timeout_txn() {
6258
19
    const std::string task_name = "abort_timeout_txn";
6259
19
    int64_t num_scanned = 0;
6260
19
    int64_t num_timeout = 0;
6261
19
    int64_t num_abort = 0;
6262
19
    int64_t num_advance = 0;
6263
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6264
6265
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6266
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6267
19
    std::string begin_txn_running_key;
6268
19
    std::string end_txn_running_key;
6269
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6270
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6271
6272
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6273
6274
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6275
19
    register_recycle_task(task_name, start_time);
6276
6277
19
    DORIS_CLOUD_DEFER {
6278
19
        unregister_recycle_task(task_name);
6279
19
        int64_t cost =
6280
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6281
19
        metrics_context.finish_report();
6282
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6283
19
                .tag("instance_id", instance_id_)
6284
19
                .tag("num_scanned", num_scanned)
6285
19
                .tag("num_timeout", num_timeout)
6286
19
                .tag("num_abort", num_abort)
6287
19
                .tag("num_advance", num_advance);
6288
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6277
3
    DORIS_CLOUD_DEFER {
6278
3
        unregister_recycle_task(task_name);
6279
3
        int64_t cost =
6280
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6281
3
        metrics_context.finish_report();
6282
3
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6283
3
                .tag("instance_id", instance_id_)
6284
3
                .tag("num_scanned", num_scanned)
6285
3
                .tag("num_timeout", num_timeout)
6286
3
                .tag("num_abort", num_abort)
6287
3
                .tag("num_advance", num_advance);
6288
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6277
16
    DORIS_CLOUD_DEFER {
6278
16
        unregister_recycle_task(task_name);
6279
16
        int64_t cost =
6280
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6281
16
        metrics_context.finish_report();
6282
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6283
16
                .tag("instance_id", instance_id_)
6284
16
                .tag("num_scanned", num_scanned)
6285
16
                .tag("num_timeout", num_timeout)
6286
16
                .tag("num_abort", num_abort)
6287
16
                .tag("num_advance", num_advance);
6288
16
    };
6289
6290
19
    int64_t current_time =
6291
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6292
6293
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6294
19
                                  &current_time, &metrics_context,
6295
19
                                  this](std::string_view k, std::string_view v) -> int {
6296
9
        ++num_scanned;
6297
6298
9
        std::unique_ptr<Transaction> txn;
6299
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6300
9
        if (err != TxnErrorCode::TXN_OK) {
6301
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6302
0
            return -1;
6303
0
        }
6304
9
        std::string_view k1 = k;
6305
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6306
9
        k1.remove_prefix(1); // Remove key space
6307
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6308
9
        if (decode_key(&k1, &out) != 0) {
6309
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6310
0
            return -1;
6311
0
        }
6312
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6313
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6314
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6315
        // Update txn_info
6316
9
        std::string txn_inf_key, txn_inf_val;
6317
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6318
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6319
9
        if (err != TxnErrorCode::TXN_OK) {
6320
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6321
0
            return -1;
6322
0
        }
6323
9
        TxnInfoPB txn_info;
6324
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6325
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6326
0
            return -1;
6327
0
        }
6328
6329
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6330
3
            txn.reset();
6331
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6332
3
            std::shared_ptr<TxnLazyCommitTask> task =
6333
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6334
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6335
3
            if (ret.first != MetaServiceCode::OK) {
6336
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6337
0
                             << "msg=" << ret.second;
6338
0
                return -1;
6339
0
            }
6340
3
            ++num_advance;
6341
3
            return 0;
6342
6
        } else {
6343
6
            TxnRunningPB txn_running_pb;
6344
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6345
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6346
0
                return -1;
6347
0
            }
6348
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6349
4
                return 0;
6350
4
            }
6351
2
            ++num_timeout;
6352
6353
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6354
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6355
2
            txn_info.set_finish_time(current_time);
6356
2
            txn_info.set_reason("timeout");
6357
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6358
2
            txn_inf_val.clear();
6359
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6360
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6361
0
                return -1;
6362
0
            }
6363
2
            txn->put(txn_inf_key, txn_inf_val);
6364
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6365
            // Put recycle txn key
6366
2
            std::string recyc_txn_key, recyc_txn_val;
6367
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6368
2
            RecycleTxnPB recycle_txn_pb;
6369
2
            recycle_txn_pb.set_creation_time(current_time);
6370
2
            recycle_txn_pb.set_label(txn_info.label());
6371
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6372
0
                LOG_WARNING("failed to serialize txn recycle info")
6373
0
                        .tag("key", hex(k))
6374
0
                        .tag("db_id", db_id)
6375
0
                        .tag("txn_id", txn_id);
6376
0
                return -1;
6377
0
            }
6378
2
            txn->put(recyc_txn_key, recyc_txn_val);
6379
            // Remove txn running key
6380
2
            txn->remove(k);
6381
2
            err = txn->commit();
6382
2
            if (err != TxnErrorCode::TXN_OK) {
6383
0
                LOG_WARNING("failed to commit txn err={}", err)
6384
0
                        .tag("key", hex(k))
6385
0
                        .tag("db_id", db_id)
6386
0
                        .tag("txn_id", txn_id);
6387
0
                return -1;
6388
0
            }
6389
2
            metrics_context.total_recycled_num = ++num_abort;
6390
2
            metrics_context.report();
6391
2
        }
6392
6393
2
        return 0;
6394
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6295
3
                                  this](std::string_view k, std::string_view v) -> int {
6296
3
        ++num_scanned;
6297
6298
3
        std::unique_ptr<Transaction> txn;
6299
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6300
3
        if (err != TxnErrorCode::TXN_OK) {
6301
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6302
0
            return -1;
6303
0
        }
6304
3
        std::string_view k1 = k;
6305
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6306
3
        k1.remove_prefix(1); // Remove key space
6307
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6308
3
        if (decode_key(&k1, &out) != 0) {
6309
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6310
0
            return -1;
6311
0
        }
6312
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6313
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6314
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6315
        // Update txn_info
6316
3
        std::string txn_inf_key, txn_inf_val;
6317
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6318
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6319
3
        if (err != TxnErrorCode::TXN_OK) {
6320
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6321
0
            return -1;
6322
0
        }
6323
3
        TxnInfoPB txn_info;
6324
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6325
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6326
0
            return -1;
6327
0
        }
6328
6329
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6330
3
            txn.reset();
6331
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6332
3
            std::shared_ptr<TxnLazyCommitTask> task =
6333
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6334
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6335
3
            if (ret.first != MetaServiceCode::OK) {
6336
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6337
0
                             << "msg=" << ret.second;
6338
0
                return -1;
6339
0
            }
6340
3
            ++num_advance;
6341
3
            return 0;
6342
3
        } else {
6343
0
            TxnRunningPB txn_running_pb;
6344
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6345
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6346
0
                return -1;
6347
0
            }
6348
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6349
0
                return 0;
6350
0
            }
6351
0
            ++num_timeout;
6352
6353
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6354
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6355
0
            txn_info.set_finish_time(current_time);
6356
0
            txn_info.set_reason("timeout");
6357
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6358
0
            txn_inf_val.clear();
6359
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6360
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6361
0
                return -1;
6362
0
            }
6363
0
            txn->put(txn_inf_key, txn_inf_val);
6364
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6365
            // Put recycle txn key
6366
0
            std::string recyc_txn_key, recyc_txn_val;
6367
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6368
0
            RecycleTxnPB recycle_txn_pb;
6369
0
            recycle_txn_pb.set_creation_time(current_time);
6370
0
            recycle_txn_pb.set_label(txn_info.label());
6371
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6372
0
                LOG_WARNING("failed to serialize txn recycle info")
6373
0
                        .tag("key", hex(k))
6374
0
                        .tag("db_id", db_id)
6375
0
                        .tag("txn_id", txn_id);
6376
0
                return -1;
6377
0
            }
6378
0
            txn->put(recyc_txn_key, recyc_txn_val);
6379
            // Remove txn running key
6380
0
            txn->remove(k);
6381
0
            err = txn->commit();
6382
0
            if (err != TxnErrorCode::TXN_OK) {
6383
0
                LOG_WARNING("failed to commit txn err={}", err)
6384
0
                        .tag("key", hex(k))
6385
0
                        .tag("db_id", db_id)
6386
0
                        .tag("txn_id", txn_id);
6387
0
                return -1;
6388
0
            }
6389
0
            metrics_context.total_recycled_num = ++num_abort;
6390
0
            metrics_context.report();
6391
0
        }
6392
6393
0
        return 0;
6394
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6295
6
                                  this](std::string_view k, std::string_view v) -> int {
6296
6
        ++num_scanned;
6297
6298
6
        std::unique_ptr<Transaction> txn;
6299
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6300
6
        if (err != TxnErrorCode::TXN_OK) {
6301
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6302
0
            return -1;
6303
0
        }
6304
6
        std::string_view k1 = k;
6305
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6306
6
        k1.remove_prefix(1); // Remove key space
6307
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6308
6
        if (decode_key(&k1, &out) != 0) {
6309
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6310
0
            return -1;
6311
0
        }
6312
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6313
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6314
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6315
        // Update txn_info
6316
6
        std::string txn_inf_key, txn_inf_val;
6317
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6318
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6319
6
        if (err != TxnErrorCode::TXN_OK) {
6320
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6321
0
            return -1;
6322
0
        }
6323
6
        TxnInfoPB txn_info;
6324
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6325
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6326
0
            return -1;
6327
0
        }
6328
6329
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6330
0
            txn.reset();
6331
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6332
0
            std::shared_ptr<TxnLazyCommitTask> task =
6333
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6334
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6335
0
            if (ret.first != MetaServiceCode::OK) {
6336
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6337
0
                             << "msg=" << ret.second;
6338
0
                return -1;
6339
0
            }
6340
0
            ++num_advance;
6341
0
            return 0;
6342
6
        } else {
6343
6
            TxnRunningPB txn_running_pb;
6344
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6345
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6346
0
                return -1;
6347
0
            }
6348
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6349
4
                return 0;
6350
4
            }
6351
2
            ++num_timeout;
6352
6353
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6354
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6355
2
            txn_info.set_finish_time(current_time);
6356
2
            txn_info.set_reason("timeout");
6357
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6358
2
            txn_inf_val.clear();
6359
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6360
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6361
0
                return -1;
6362
0
            }
6363
2
            txn->put(txn_inf_key, txn_inf_val);
6364
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6365
            // Put recycle txn key
6366
2
            std::string recyc_txn_key, recyc_txn_val;
6367
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6368
2
            RecycleTxnPB recycle_txn_pb;
6369
2
            recycle_txn_pb.set_creation_time(current_time);
6370
2
            recycle_txn_pb.set_label(txn_info.label());
6371
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6372
0
                LOG_WARNING("failed to serialize txn recycle info")
6373
0
                        .tag("key", hex(k))
6374
0
                        .tag("db_id", db_id)
6375
0
                        .tag("txn_id", txn_id);
6376
0
                return -1;
6377
0
            }
6378
2
            txn->put(recyc_txn_key, recyc_txn_val);
6379
            // Remove txn running key
6380
2
            txn->remove(k);
6381
2
            err = txn->commit();
6382
2
            if (err != TxnErrorCode::TXN_OK) {
6383
0
                LOG_WARNING("failed to commit txn err={}", err)
6384
0
                        .tag("key", hex(k))
6385
0
                        .tag("db_id", db_id)
6386
0
                        .tag("txn_id", txn_id);
6387
0
                return -1;
6388
0
            }
6389
2
            metrics_context.total_recycled_num = ++num_abort;
6390
2
            metrics_context.report();
6391
2
        }
6392
6393
2
        return 0;
6394
6
    };
6395
6396
19
    if (config::enable_recycler_stats_metrics) {
6397
0
        scan_and_statistics_abort_timeout_txn();
6398
0
    }
6399
    // recycle_func and loop_done for scan and recycle
6400
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6401
19
                            std::move(handle_txn_running_kv));
6402
19
}
6403
6404
19
int InstanceRecycler::recycle_expired_txn_label() {
6405
19
    const std::string task_name = "recycle_expired_txn_label";
6406
19
    int64_t num_scanned = 0;
6407
19
    int64_t num_expired = 0;
6408
19
    std::atomic_long num_recycled = 0;
6409
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6410
19
    int ret = 0;
6411
6412
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6413
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6414
19
    std::string begin_recycle_txn_key;
6415
19
    std::string end_recycle_txn_key;
6416
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6417
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6418
19
    std::vector<std::string> recycle_txn_info_keys;
6419
6420
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6421
6422
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6423
19
    register_recycle_task(task_name, start_time);
6424
19
    DORIS_CLOUD_DEFER {
6425
19
        unregister_recycle_task(task_name);
6426
19
        int64_t cost =
6427
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6428
19
        metrics_context.finish_report();
6429
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6430
19
                .tag("instance_id", instance_id_)
6431
19
                .tag("num_scanned", num_scanned)
6432
19
                .tag("num_expired", num_expired)
6433
19
                .tag("num_recycled", num_recycled);
6434
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6424
1
    DORIS_CLOUD_DEFER {
6425
1
        unregister_recycle_task(task_name);
6426
1
        int64_t cost =
6427
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6428
1
        metrics_context.finish_report();
6429
1
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6430
1
                .tag("instance_id", instance_id_)
6431
1
                .tag("num_scanned", num_scanned)
6432
1
                .tag("num_expired", num_expired)
6433
1
                .tag("num_recycled", num_recycled);
6434
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6424
18
    DORIS_CLOUD_DEFER {
6425
18
        unregister_recycle_task(task_name);
6426
18
        int64_t cost =
6427
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6428
18
        metrics_context.finish_report();
6429
18
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6430
18
                .tag("instance_id", instance_id_)
6431
18
                .tag("num_scanned", num_scanned)
6432
18
                .tag("num_expired", num_expired)
6433
18
                .tag("num_recycled", num_recycled);
6434
18
    };
6435
6436
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6437
6438
19
    SyncExecutor<int> concurrent_delete_executor(
6439
19
            _thread_pool_group.s3_producer_pool,
6440
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6441
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6441
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clERKi
Line
Count
Source
6441
23.0k
            [](const int& ret) { return ret != 0; });
6442
6443
19
    int64_t current_time_ms =
6444
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6445
6446
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6447
30.0k
        ++num_scanned;
6448
30.0k
        RecycleTxnPB recycle_txn_pb;
6449
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6450
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
30.0k
        if ((config::force_immediate_recycle) ||
6454
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6455
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6456
30.0k
             current_time_ms)) {
6457
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6458
23.0k
            num_expired++;
6459
23.0k
            recycle_txn_info_keys.emplace_back(k);
6460
23.0k
        }
6461
30.0k
        return 0;
6462
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6446
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6447
1
        ++num_scanned;
6448
1
        RecycleTxnPB recycle_txn_pb;
6449
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6450
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
1
        if ((config::force_immediate_recycle) ||
6454
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6455
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6456
1
             current_time_ms)) {
6457
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6458
1
            num_expired++;
6459
1
            recycle_txn_info_keys.emplace_back(k);
6460
1
        }
6461
1
        return 0;
6462
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6446
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6447
30.0k
        ++num_scanned;
6448
30.0k
        RecycleTxnPB recycle_txn_pb;
6449
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6450
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6451
0
            return -1;
6452
0
        }
6453
30.0k
        if ((config::force_immediate_recycle) ||
6454
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6455
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6456
30.0k
             current_time_ms)) {
6457
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6458
23.0k
            num_expired++;
6459
23.0k
            recycle_txn_info_keys.emplace_back(k);
6460
23.0k
        }
6461
30.0k
        return 0;
6462
30.0k
    };
6463
6464
    // int 0 for success, 1 for conflict, -1 for error
6465
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6466
23.0k
        std::string_view k1 = k;
6467
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6468
23.0k
        k1.remove_prefix(1); // Remove key space
6469
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6470
23.0k
        int ret = decode_key(&k1, &out);
6471
23.0k
        if (ret != 0) {
6472
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6473
0
            return -1;
6474
0
        }
6475
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6476
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6477
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6478
23.0k
        std::unique_ptr<Transaction> txn;
6479
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6480
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6481
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6482
0
            return -1;
6483
0
        }
6484
        // Remove txn index kv
6485
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6486
23.0k
        txn->remove(index_key);
6487
        // Remove txn info kv
6488
23.0k
        std::string info_key, info_val;
6489
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6490
23.0k
        err = txn->get(info_key, &info_val);
6491
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6492
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6493
0
            return -1;
6494
0
        }
6495
23.0k
        TxnInfoPB txn_info;
6496
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6497
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6498
0
            return -1;
6499
0
        }
6500
23.0k
        txn->remove(info_key);
6501
        // Remove sub txn index kvs
6502
23.0k
        std::vector<std::string> sub_txn_index_keys;
6503
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6504
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6505
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6506
22.9k
        }
6507
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6508
22.9k
            txn->remove(sub_txn_index_key);
6509
22.9k
        }
6510
        // Update txn label
6511
23.0k
        std::string label_key, label_val;
6512
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6513
23.0k
        err = txn->get(label_key, &label_val);
6514
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6515
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6516
0
                         << " err=" << err;
6517
0
            return -1;
6518
0
        }
6519
23.0k
        TxnLabelPB txn_label;
6520
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6521
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6522
0
            return -1;
6523
0
        }
6524
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6525
23.0k
        if (it != txn_label.txn_ids().end()) {
6526
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6527
23.0k
        }
6528
23.0k
        if (txn_label.txn_ids().empty()) {
6529
23.0k
            txn->remove(label_key);
6530
23.0k
            TEST_SYNC_POINT_CALLBACK(
6531
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6532
23.0k
        } else {
6533
73
            if (!txn_label.SerializeToString(&label_val)) {
6534
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6535
0
                return -1;
6536
0
            }
6537
73
            TEST_SYNC_POINT_CALLBACK(
6538
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6539
73
            txn->atomic_set_ver_value(label_key, label_val);
6540
73
            TEST_SYNC_POINT_CALLBACK(
6541
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6542
73
        }
6543
        // Remove recycle txn kv
6544
23.0k
        txn->remove(k);
6545
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6546
23.0k
        err = txn->commit();
6547
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6548
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6549
62
                TEST_SYNC_POINT_CALLBACK(
6550
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6551
                // log the txn_id and label
6552
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6553
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6554
62
                             << " txn_label=" << txn_info.label();
6555
62
                return 1;
6556
62
            }
6557
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6558
0
            return -1;
6559
62
        }
6560
23.0k
        ++num_recycled;
6561
6562
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6563
23.0k
        return 0;
6564
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6465
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6466
1
        std::string_view k1 = k;
6467
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6468
1
        k1.remove_prefix(1); // Remove key space
6469
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6470
1
        int ret = decode_key(&k1, &out);
6471
1
        if (ret != 0) {
6472
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6473
0
            return -1;
6474
0
        }
6475
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6476
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6477
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6478
1
        std::unique_ptr<Transaction> txn;
6479
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6480
1
        if (err != TxnErrorCode::TXN_OK) {
6481
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6482
0
            return -1;
6483
0
        }
6484
        // Remove txn index kv
6485
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6486
1
        txn->remove(index_key);
6487
        // Remove txn info kv
6488
1
        std::string info_key, info_val;
6489
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6490
1
        err = txn->get(info_key, &info_val);
6491
1
        if (err != TxnErrorCode::TXN_OK) {
6492
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6493
0
            return -1;
6494
0
        }
6495
1
        TxnInfoPB txn_info;
6496
1
        if (!txn_info.ParseFromString(info_val)) {
6497
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6498
0
            return -1;
6499
0
        }
6500
1
        txn->remove(info_key);
6501
        // Remove sub txn index kvs
6502
1
        std::vector<std::string> sub_txn_index_keys;
6503
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6504
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6505
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6506
0
        }
6507
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6508
0
            txn->remove(sub_txn_index_key);
6509
0
        }
6510
        // Update txn label
6511
1
        std::string label_key, label_val;
6512
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6513
1
        err = txn->get(label_key, &label_val);
6514
1
        if (err != TxnErrorCode::TXN_OK) {
6515
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6516
0
                         << " err=" << err;
6517
0
            return -1;
6518
0
        }
6519
1
        TxnLabelPB txn_label;
6520
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6521
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6522
0
            return -1;
6523
0
        }
6524
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6525
1
        if (it != txn_label.txn_ids().end()) {
6526
1
            txn_label.mutable_txn_ids()->erase(it);
6527
1
        }
6528
1
        if (txn_label.txn_ids().empty()) {
6529
1
            txn->remove(label_key);
6530
1
            TEST_SYNC_POINT_CALLBACK(
6531
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6532
1
        } else {
6533
0
            if (!txn_label.SerializeToString(&label_val)) {
6534
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6535
0
                return -1;
6536
0
            }
6537
0
            TEST_SYNC_POINT_CALLBACK(
6538
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6539
0
            txn->atomic_set_ver_value(label_key, label_val);
6540
0
            TEST_SYNC_POINT_CALLBACK(
6541
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6542
0
        }
6543
        // Remove recycle txn kv
6544
1
        txn->remove(k);
6545
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6546
1
        err = txn->commit();
6547
1
        if (err != TxnErrorCode::TXN_OK) {
6548
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6549
0
                TEST_SYNC_POINT_CALLBACK(
6550
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6551
                // log the txn_id and label
6552
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6553
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6554
0
                             << " txn_label=" << txn_info.label();
6555
0
                return 1;
6556
0
            }
6557
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6558
0
            return -1;
6559
0
        }
6560
1
        ++num_recycled;
6561
6562
1
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6563
1
        return 0;
6564
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6465
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6466
23.0k
        std::string_view k1 = k;
6467
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6468
23.0k
        k1.remove_prefix(1); // Remove key space
6469
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6470
23.0k
        int ret = decode_key(&k1, &out);
6471
23.0k
        if (ret != 0) {
6472
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6473
0
            return -1;
6474
0
        }
6475
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6476
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6477
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6478
23.0k
        std::unique_ptr<Transaction> txn;
6479
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6480
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6481
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6482
0
            return -1;
6483
0
        }
6484
        // Remove txn index kv
6485
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6486
23.0k
        txn->remove(index_key);
6487
        // Remove txn info kv
6488
23.0k
        std::string info_key, info_val;
6489
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6490
23.0k
        err = txn->get(info_key, &info_val);
6491
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6492
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6493
0
            return -1;
6494
0
        }
6495
23.0k
        TxnInfoPB txn_info;
6496
23.0k
        if (!txn_info.ParseFromString(info_val)) {
6497
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6498
0
            return -1;
6499
0
        }
6500
23.0k
        txn->remove(info_key);
6501
        // Remove sub txn index kvs
6502
23.0k
        std::vector<std::string> sub_txn_index_keys;
6503
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6504
22.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6505
22.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6506
22.9k
        }
6507
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6508
22.9k
            txn->remove(sub_txn_index_key);
6509
22.9k
        }
6510
        // Update txn label
6511
23.0k
        std::string label_key, label_val;
6512
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6513
23.0k
        err = txn->get(label_key, &label_val);
6514
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6515
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6516
0
                         << " err=" << err;
6517
0
            return -1;
6518
0
        }
6519
23.0k
        TxnLabelPB txn_label;
6520
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6521
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6522
0
            return -1;
6523
0
        }
6524
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6525
23.0k
        if (it != txn_label.txn_ids().end()) {
6526
23.0k
            txn_label.mutable_txn_ids()->erase(it);
6527
23.0k
        }
6528
23.0k
        if (txn_label.txn_ids().empty()) {
6529
23.0k
            txn->remove(label_key);
6530
23.0k
            TEST_SYNC_POINT_CALLBACK(
6531
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6532
23.0k
        } else {
6533
73
            if (!txn_label.SerializeToString(&label_val)) {
6534
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6535
0
                return -1;
6536
0
            }
6537
73
            TEST_SYNC_POINT_CALLBACK(
6538
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6539
73
            txn->atomic_set_ver_value(label_key, label_val);
6540
73
            TEST_SYNC_POINT_CALLBACK(
6541
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6542
73
        }
6543
        // Remove recycle txn kv
6544
23.0k
        txn->remove(k);
6545
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6546
23.0k
        err = txn->commit();
6547
23.0k
        if (err != TxnErrorCode::TXN_OK) {
6548
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
6549
62
                TEST_SYNC_POINT_CALLBACK(
6550
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6551
                // log the txn_id and label
6552
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6553
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6554
62
                             << " txn_label=" << txn_info.label();
6555
62
                return 1;
6556
62
            }
6557
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6558
0
            return -1;
6559
62
        }
6560
23.0k
        ++num_recycled;
6561
6562
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6563
23.0k
        return 0;
6564
23.0k
    };
6565
6566
19
    auto loop_done = [&]() -> int {
6567
10
        DORIS_CLOUD_DEFER {
6568
10
            recycle_txn_info_keys.clear();
6569
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6567
1
        DORIS_CLOUD_DEFER {
6568
1
            recycle_txn_info_keys.clear();
6569
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6567
9
        DORIS_CLOUD_DEFER {
6568
9
            recycle_txn_info_keys.clear();
6569
9
        };
6570
10
        TEST_SYNC_POINT_CALLBACK(
6571
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6572
10
                &recycle_txn_info_keys);
6573
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6574
23.0k
            concurrent_delete_executor.add([&]() {
6575
23.0k
                int ret = delete_recycle_txn_kv(k);
6576
23.0k
                if (ret == 1) {
6577
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6578
54
                    for (int i = 1; i <= max_retry; ++i) {
6579
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6580
54
                        ret = delete_recycle_txn_kv(k);
6581
                        // clang-format off
6582
54
                        TEST_SYNC_POINT_CALLBACK(
6583
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6584
                        // clang-format off
6585
54
                        if (ret != 1) {
6586
18
                            break;
6587
18
                        }
6588
                        // random sleep 0-100 ms to retry
6589
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6590
36
                    }
6591
18
                }
6592
23.0k
                if (ret != 0) {
6593
9
                    LOG_WARNING("failed to delete recycle txn kv")
6594
9
                            .tag("instance id", instance_id_)
6595
9
                            .tag("key", hex(k));
6596
9
                    return -1;
6597
9
                }
6598
23.0k
                return 0;
6599
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6574
1
            concurrent_delete_executor.add([&]() {
6575
1
                int ret = delete_recycle_txn_kv(k);
6576
1
                if (ret == 1) {
6577
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6578
0
                    for (int i = 1; i <= max_retry; ++i) {
6579
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6580
0
                        ret = delete_recycle_txn_kv(k);
6581
                        // clang-format off
6582
0
                        TEST_SYNC_POINT_CALLBACK(
6583
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6584
                        // clang-format off
6585
0
                        if (ret != 1) {
6586
0
                            break;
6587
0
                        }
6588
                        // random sleep 0-100 ms to retry
6589
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6590
0
                    }
6591
0
                }
6592
1
                if (ret != 0) {
6593
0
                    LOG_WARNING("failed to delete recycle txn kv")
6594
0
                            .tag("instance id", instance_id_)
6595
0
                            .tag("key", hex(k));
6596
0
                    return -1;
6597
0
                }
6598
1
                return 0;
6599
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6574
23.0k
            concurrent_delete_executor.add([&]() {
6575
23.0k
                int ret = delete_recycle_txn_kv(k);
6576
23.0k
                if (ret == 1) {
6577
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6578
54
                    for (int i = 1; i <= max_retry; ++i) {
6579
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6580
54
                        ret = delete_recycle_txn_kv(k);
6581
                        // clang-format off
6582
54
                        TEST_SYNC_POINT_CALLBACK(
6583
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6584
                        // clang-format off
6585
54
                        if (ret != 1) {
6586
18
                            break;
6587
18
                        }
6588
                        // random sleep 0-100 ms to retry
6589
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6590
36
                    }
6591
18
                }
6592
23.0k
                if (ret != 0) {
6593
9
                    LOG_WARNING("failed to delete recycle txn kv")
6594
9
                            .tag("instance id", instance_id_)
6595
9
                            .tag("key", hex(k));
6596
9
                    return -1;
6597
9
                }
6598
23.0k
                return 0;
6599
23.0k
            });
6600
23.0k
        }
6601
10
        bool finished = true;
6602
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6603
23.0k
        for (int r : rets) {
6604
23.0k
            if (r != 0) {
6605
9
                ret = -1;
6606
9
            }
6607
23.0k
        }
6608
6609
10
        ret = finished ? ret : -1;
6610
6611
        // Update metrics after all concurrent tasks completed
6612
10
        metrics_context.total_recycled_num = num_recycled.load();
6613
10
        metrics_context.report();
6614
6615
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6616
6617
10
        if (ret != 0) {
6618
3
            LOG_WARNING("recycle txn kv ret!=0")
6619
3
                    .tag("finished", finished)
6620
3
                    .tag("ret", ret)
6621
3
                    .tag("instance_id", instance_id_);
6622
3
            return ret;
6623
3
        }
6624
7
        return ret;
6625
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6566
1
    auto loop_done = [&]() -> int {
6567
1
        DORIS_CLOUD_DEFER {
6568
1
            recycle_txn_info_keys.clear();
6569
1
        };
6570
1
        TEST_SYNC_POINT_CALLBACK(
6571
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6572
1
                &recycle_txn_info_keys);
6573
1
        for (const auto& k : recycle_txn_info_keys) {
6574
1
            concurrent_delete_executor.add([&]() {
6575
1
                int ret = delete_recycle_txn_kv(k);
6576
1
                if (ret == 1) {
6577
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6578
1
                    for (int i = 1; i <= max_retry; ++i) {
6579
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6580
1
                        ret = delete_recycle_txn_kv(k);
6581
                        // clang-format off
6582
1
                        TEST_SYNC_POINT_CALLBACK(
6583
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6584
                        // clang-format off
6585
1
                        if (ret != 1) {
6586
1
                            break;
6587
1
                        }
6588
                        // random sleep 0-100 ms to retry
6589
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6590
1
                    }
6591
1
                }
6592
1
                if (ret != 0) {
6593
1
                    LOG_WARNING("failed to delete recycle txn kv")
6594
1
                            .tag("instance id", instance_id_)
6595
1
                            .tag("key", hex(k));
6596
1
                    return -1;
6597
1
                }
6598
1
                return 0;
6599
1
            });
6600
1
        }
6601
1
        bool finished = true;
6602
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6603
1
        for (int r : rets) {
6604
1
            if (r != 0) {
6605
0
                ret = -1;
6606
0
            }
6607
1
        }
6608
6609
1
        ret = finished ? ret : -1;
6610
6611
        // Update metrics after all concurrent tasks completed
6612
1
        metrics_context.total_recycled_num = num_recycled.load();
6613
1
        metrics_context.report();
6614
6615
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6616
6617
1
        if (ret != 0) {
6618
0
            LOG_WARNING("recycle txn kv ret!=0")
6619
0
                    .tag("finished", finished)
6620
0
                    .tag("ret", ret)
6621
0
                    .tag("instance_id", instance_id_);
6622
0
            return ret;
6623
0
        }
6624
1
        return ret;
6625
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clEv
Line
Count
Source
6566
9
    auto loop_done = [&]() -> int {
6567
9
        DORIS_CLOUD_DEFER {
6568
9
            recycle_txn_info_keys.clear();
6569
9
        };
6570
9
        TEST_SYNC_POINT_CALLBACK(
6571
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
6572
9
                &recycle_txn_info_keys);
6573
23.0k
        for (const auto& k : recycle_txn_info_keys) {
6574
23.0k
            concurrent_delete_executor.add([&]() {
6575
23.0k
                int ret = delete_recycle_txn_kv(k);
6576
23.0k
                if (ret == 1) {
6577
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6578
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
6579
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6580
23.0k
                        ret = delete_recycle_txn_kv(k);
6581
                        // clang-format off
6582
23.0k
                        TEST_SYNC_POINT_CALLBACK(
6583
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
6584
                        // clang-format off
6585
23.0k
                        if (ret != 1) {
6586
23.0k
                            break;
6587
23.0k
                        }
6588
                        // random sleep 0-100 ms to retry
6589
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6590
23.0k
                    }
6591
23.0k
                }
6592
23.0k
                if (ret != 0) {
6593
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
6594
23.0k
                            .tag("instance id", instance_id_)
6595
23.0k
                            .tag("key", hex(k));
6596
23.0k
                    return -1;
6597
23.0k
                }
6598
23.0k
                return 0;
6599
23.0k
            });
6600
23.0k
        }
6601
9
        bool finished = true;
6602
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6603
23.0k
        for (int r : rets) {
6604
23.0k
            if (r != 0) {
6605
9
                ret = -1;
6606
9
            }
6607
23.0k
        }
6608
6609
9
        ret = finished ? ret : -1;
6610
6611
        // Update metrics after all concurrent tasks completed
6612
9
        metrics_context.total_recycled_num = num_recycled.load();
6613
9
        metrics_context.report();
6614
6615
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6616
6617
9
        if (ret != 0) {
6618
3
            LOG_WARNING("recycle txn kv ret!=0")
6619
3
                    .tag("finished", finished)
6620
3
                    .tag("ret", ret)
6621
3
                    .tag("instance_id", instance_id_);
6622
3
            return ret;
6623
3
        }
6624
6
        return ret;
6625
9
    };
6626
6627
19
    if (config::enable_recycler_stats_metrics) {
6628
0
        scan_and_statistics_expired_txn_label();
6629
0
    }
6630
    // recycle_func and loop_done for scan and recycle
6631
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
6632
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
6633
19
}
6634
6635
struct CopyJobIdTuple {
6636
    std::string instance_id;
6637
    std::string stage_id;
6638
    long table_id;
6639
    std::string copy_id;
6640
    std::string stage_path;
6641
};
6642
struct BatchObjStoreAccessor {
6643
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
6644
                          TxnKv* txn_kv)
6645
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
6646
3
    ~BatchObjStoreAccessor() {
6647
3
        if (!paths_.empty()) {
6648
3
            consume();
6649
3
        }
6650
3
    }
6651
6652
    /**
6653
    * To implicitely do batch work and submit the batch delete task to s3
6654
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
6655
    *
6656
    * @param copy_job The protubuf struct consists of the copy job files.
6657
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
6658
    *            it would last until we finish the delete task, here we need pass one string value
6659
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
6660
    */
6661
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
6662
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
6663
5
        auto& file_keys = copy_file_keys_[key];
6664
5
        file_keys.log_trace =
6665
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
6666
5
                            instance_id, stage_id, table_id, copy_id, path);
6667
5
        std::string_view log_trace = file_keys.log_trace;
6668
2.03k
        for (const auto& file : copy_job.object_files()) {
6669
2.03k
            auto relative_path = file.relative_path();
6670
2.03k
            paths_.push_back(relative_path);
6671
2.03k
            file_keys.keys.push_back(copy_file_key(
6672
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
6673
2.03k
            LOG_INFO(log_trace)
6674
2.03k
                    .tag("relative_path", relative_path)
6675
2.03k
                    .tag("batch_count", batch_count_);
6676
2.03k
        }
6677
5
        LOG_INFO(log_trace)
6678
5
                .tag("objects_num", copy_job.object_files().size())
6679
5
                .tag("batch_count", batch_count_);
6680
        // 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
6681
        // recommend using delete objects when objects num is less than 10)
6682
5
        if (paths_.size() < 1000) {
6683
3
            return;
6684
3
        }
6685
2
        consume();
6686
2
    }
6687
6688
private:
6689
5
    void consume() {
6690
5
        DORIS_CLOUD_DEFER {
6691
5
            paths_.clear();
6692
5
            copy_file_keys_.clear();
6693
5
            batch_count_++;
6694
6695
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
6696
5
                        batch_count_);
6697
5
        };
6698
6699
5
        StopWatch sw;
6700
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
6701
5
        if (0 != accessor_->delete_files(paths_)) {
6702
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
6703
2
                        paths_.size(), batch_count_, sw.elapsed_us());
6704
2
            return;
6705
2
        }
6706
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
6707
3
                    paths_.size(), batch_count_, sw.elapsed_us());
6708
        // delete fdb's keys
6709
3
        for (auto& file_keys : copy_file_keys_) {
6710
3
            auto& [log_trace, keys] = file_keys.second;
6711
3
            std::unique_ptr<Transaction> txn;
6712
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
6713
0
                LOG(WARNING) << "failed to create txn";
6714
0
                continue;
6715
0
            }
6716
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6717
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6718
            // limited, should not cause the txn commit failed.
6719
1.02k
            for (const auto& key : keys) {
6720
1.02k
                txn->remove(key);
6721
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
6722
1.02k
            }
6723
3
            txn->remove(file_keys.first);
6724
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
6725
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
6726
0
                continue;
6727
0
            }
6728
3
        }
6729
3
    }
6730
    std::shared_ptr<StorageVaultAccessor> accessor_;
6731
    // the path of the s3 files to be deleted
6732
    std::vector<std::string> paths_;
6733
    struct CopyFiles {
6734
        std::string log_trace;
6735
        std::vector<std::string> keys;
6736
    };
6737
    // pair<std::string, std::vector<std::string>>
6738
    // first: instance_id_ stage_id table_id query_id
6739
    // second: keys to be deleted
6740
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
6741
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
6742
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
6743
    // which can together uniquely identifies different tasks for tracing log
6744
    uint64_t& batch_count_;
6745
    TxnKv* txn_kv_;
6746
};
6747
6748
13
int InstanceRecycler::recycle_copy_jobs() {
6749
13
    int64_t num_scanned = 0;
6750
13
    int64_t num_finished = 0;
6751
13
    int64_t num_expired = 0;
6752
13
    int64_t num_recycled = 0;
6753
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
6754
13
    uint64_t batch_count = 0;
6755
13
    const std::string task_name = "recycle_copy_jobs";
6756
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6757
6758
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
6759
6760
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6761
13
    register_recycle_task(task_name, start_time);
6762
6763
13
    DORIS_CLOUD_DEFER {
6764
13
        unregister_recycle_task(task_name);
6765
13
        int64_t cost =
6766
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6767
13
        metrics_context.finish_report();
6768
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6769
13
                .tag("instance_id", instance_id_)
6770
13
                .tag("num_scanned", num_scanned)
6771
13
                .tag("num_finished", num_finished)
6772
13
                .tag("num_expired", num_expired)
6773
13
                .tag("num_recycled", num_recycled);
6774
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
6763
13
    DORIS_CLOUD_DEFER {
6764
13
        unregister_recycle_task(task_name);
6765
13
        int64_t cost =
6766
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6767
13
        metrics_context.finish_report();
6768
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
6769
13
                .tag("instance_id", instance_id_)
6770
13
                .tag("num_scanned", num_scanned)
6771
13
                .tag("num_finished", num_finished)
6772
13
                .tag("num_expired", num_expired)
6773
13
                .tag("num_recycled", num_recycled);
6774
13
    };
6775
6776
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
6777
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
6778
13
    std::string key0;
6779
13
    std::string key1;
6780
13
    copy_job_key(key_info0, &key0);
6781
13
    copy_job_key(key_info1, &key1);
6782
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
6783
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
6784
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
6785
16
                         this](std::string_view k, std::string_view v) -> int {
6786
16
        ++num_scanned;
6787
16
        CopyJobPB copy_job;
6788
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6789
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6790
0
            return -1;
6791
0
        }
6792
6793
        // decode copy job key
6794
16
        auto k1 = k;
6795
16
        k1.remove_prefix(1);
6796
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6797
16
        decode_key(&k1, &out);
6798
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6799
        // -> CopyJobPB
6800
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6801
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6802
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6803
6804
16
        bool check_storage = true;
6805
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6806
12
            ++num_finished;
6807
6808
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6809
7
                auto it = stage_accessor_map.find(stage_id);
6810
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6811
7
                std::string_view path;
6812
7
                if (it != stage_accessor_map.end()) {
6813
2
                    accessor = it->second;
6814
5
                } else {
6815
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6816
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6817
5
                                                      &inner_accessor);
6818
5
                    if (ret < 0) { // error
6819
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6820
0
                        return -1;
6821
5
                    } else if (ret == 0) {
6822
3
                        path = inner_accessor->uri();
6823
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6824
3
                                inner_accessor, batch_count, txn_kv_.get());
6825
3
                        stage_accessor_map.emplace(stage_id, accessor);
6826
3
                    } else { // stage not found, skip check storage
6827
2
                        check_storage = false;
6828
2
                    }
6829
5
                }
6830
7
                if (check_storage) {
6831
                    // TODO delete objects with key and etag is not supported
6832
5
                    accessor->add(std::move(copy_job), std::string(k),
6833
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6834
5
                    return 0;
6835
5
                }
6836
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6837
5
                int64_t current_time =
6838
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6839
5
                if (copy_job.finish_time_ms() > 0) {
6840
2
                    if (!config::force_immediate_recycle &&
6841
2
                        current_time < copy_job.finish_time_ms() +
6842
2
                                               config::copy_job_max_retention_second * 1000) {
6843
1
                        return 0;
6844
1
                    }
6845
3
                } else {
6846
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6847
3
                    if (!config::force_immediate_recycle &&
6848
3
                        current_time < copy_job.start_time_ms() +
6849
3
                                               config::copy_job_max_retention_second * 1000) {
6850
1
                        return 0;
6851
1
                    }
6852
3
                }
6853
5
            }
6854
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6855
4
            int64_t current_time =
6856
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6857
            // if copy job is timeout: delete all copy file kvs and copy job kv
6858
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6859
2
                return 0;
6860
2
            }
6861
2
            ++num_expired;
6862
2
        }
6863
6864
        // delete all copy files
6865
7
        std::vector<std::string> copy_file_keys;
6866
70
        for (auto& file : copy_job.object_files()) {
6867
70
            copy_file_keys.push_back(copy_file_key(
6868
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6869
70
        }
6870
7
        std::unique_ptr<Transaction> txn;
6871
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6872
0
            LOG(WARNING) << "failed to create txn";
6873
0
            return -1;
6874
0
        }
6875
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6876
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6877
        // limited, should not cause the txn commit failed.
6878
70
        for (const auto& key : copy_file_keys) {
6879
70
            txn->remove(key);
6880
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6881
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6882
70
                      << ", query_id=" << copy_id;
6883
70
        }
6884
7
        txn->remove(k);
6885
7
        TxnErrorCode err = txn->commit();
6886
7
        if (err != TxnErrorCode::TXN_OK) {
6887
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6888
0
            return -1;
6889
0
        }
6890
6891
7
        metrics_context.total_recycled_num = ++num_recycled;
6892
7
        metrics_context.report();
6893
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6894
7
        return 0;
6895
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
6785
16
                         this](std::string_view k, std::string_view v) -> int {
6786
16
        ++num_scanned;
6787
16
        CopyJobPB copy_job;
6788
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
6789
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
6790
0
            return -1;
6791
0
        }
6792
6793
        // decode copy job key
6794
16
        auto k1 = k;
6795
16
        k1.remove_prefix(1);
6796
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6797
16
        decode_key(&k1, &out);
6798
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
6799
        // -> CopyJobPB
6800
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
6801
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
6802
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
6803
6804
16
        bool check_storage = true;
6805
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
6806
12
            ++num_finished;
6807
6808
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
6809
7
                auto it = stage_accessor_map.find(stage_id);
6810
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
6811
7
                std::string_view path;
6812
7
                if (it != stage_accessor_map.end()) {
6813
2
                    accessor = it->second;
6814
5
                } else {
6815
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
6816
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
6817
5
                                                      &inner_accessor);
6818
5
                    if (ret < 0) { // error
6819
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
6820
0
                        return -1;
6821
5
                    } else if (ret == 0) {
6822
3
                        path = inner_accessor->uri();
6823
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
6824
3
                                inner_accessor, batch_count, txn_kv_.get());
6825
3
                        stage_accessor_map.emplace(stage_id, accessor);
6826
3
                    } else { // stage not found, skip check storage
6827
2
                        check_storage = false;
6828
2
                    }
6829
5
                }
6830
7
                if (check_storage) {
6831
                    // TODO delete objects with key and etag is not supported
6832
5
                    accessor->add(std::move(copy_job), std::string(k),
6833
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
6834
5
                    return 0;
6835
5
                }
6836
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
6837
5
                int64_t current_time =
6838
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6839
5
                if (copy_job.finish_time_ms() > 0) {
6840
2
                    if (!config::force_immediate_recycle &&
6841
2
                        current_time < copy_job.finish_time_ms() +
6842
2
                                               config::copy_job_max_retention_second * 1000) {
6843
1
                        return 0;
6844
1
                    }
6845
3
                } else {
6846
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
6847
3
                    if (!config::force_immediate_recycle &&
6848
3
                        current_time < copy_job.start_time_ms() +
6849
3
                                               config::copy_job_max_retention_second * 1000) {
6850
1
                        return 0;
6851
1
                    }
6852
3
                }
6853
5
            }
6854
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
6855
4
            int64_t current_time =
6856
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6857
            // if copy job is timeout: delete all copy file kvs and copy job kv
6858
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
6859
2
                return 0;
6860
2
            }
6861
2
            ++num_expired;
6862
2
        }
6863
6864
        // delete all copy files
6865
7
        std::vector<std::string> copy_file_keys;
6866
70
        for (auto& file : copy_job.object_files()) {
6867
70
            copy_file_keys.push_back(copy_file_key(
6868
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
6869
70
        }
6870
7
        std::unique_ptr<Transaction> txn;
6871
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
6872
0
            LOG(WARNING) << "failed to create txn";
6873
0
            return -1;
6874
0
        }
6875
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
6876
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
6877
        // limited, should not cause the txn commit failed.
6878
70
        for (const auto& key : copy_file_keys) {
6879
70
            txn->remove(key);
6880
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
6881
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
6882
70
                      << ", query_id=" << copy_id;
6883
70
        }
6884
7
        txn->remove(k);
6885
7
        TxnErrorCode err = txn->commit();
6886
7
        if (err != TxnErrorCode::TXN_OK) {
6887
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
6888
0
            return -1;
6889
0
        }
6890
6891
7
        metrics_context.total_recycled_num = ++num_recycled;
6892
7
        metrics_context.report();
6893
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6894
7
        return 0;
6895
7
    };
6896
6897
13
    if (config::enable_recycler_stats_metrics) {
6898
0
        scan_and_statistics_copy_jobs();
6899
0
    }
6900
    // recycle_func and loop_done for scan and recycle
6901
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
6902
13
}
6903
6904
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
6905
                                             const StagePB::StageType& stage_type,
6906
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
6907
5
#ifdef UNIT_TEST
6908
    // In unit test, external use the same accessor as the internal stage
6909
5
    auto it = accessor_map_.find(stage_id);
6910
5
    if (it != accessor_map_.end()) {
6911
3
        *accessor = it->second;
6912
3
    } else {
6913
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
6914
2
        return 1;
6915
2
    }
6916
#else
6917
    // init s3 accessor and add to accessor map
6918
    auto stage_it =
6919
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
6920
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
6921
6922
    if (stage_it == instance_info_.stages().end()) {
6923
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
6924
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
6925
        return 1;
6926
    }
6927
6928
    const auto& object_store_info = stage_it->obj_info();
6929
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
6930
6931
    S3Conf s3_conf;
6932
    if (stage_type == StagePB::EXTERNAL) {
6933
        if (stage_access_type == StagePB::AKSK) {
6934
            auto conf = S3Conf::from_obj_store_info(object_store_info);
6935
            if (!conf) {
6936
                return -1;
6937
            }
6938
6939
            s3_conf = std::move(*conf);
6940
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
6941
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
6942
            if (!conf) {
6943
                return -1;
6944
            }
6945
6946
            s3_conf = std::move(*conf);
6947
            if (instance_info_.ram_user().has_encryption_info()) {
6948
                AkSkPair plain_ak_sk_pair;
6949
                int ret = decrypt_ak_sk_helper(
6950
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
6951
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
6952
                if (ret != 0) {
6953
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
6954
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
6955
                    return -1;
6956
                }
6957
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
6958
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
6959
            } else {
6960
                s3_conf.ak = instance_info_.ram_user().ak();
6961
                s3_conf.sk = instance_info_.ram_user().sk();
6962
            }
6963
        } else {
6964
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
6965
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
6966
            return -1;
6967
        }
6968
    } else if (stage_type == StagePB::INTERNAL) {
6969
        int idx = stoi(object_store_info.id());
6970
        if (idx > instance_info_.obj_info().size() || idx < 1) {
6971
            LOG(WARNING) << "invalid idx: " << idx;
6972
            return -1;
6973
        }
6974
6975
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
6976
        auto conf = S3Conf::from_obj_store_info(old_obj);
6977
        if (!conf) {
6978
            return -1;
6979
        }
6980
6981
        s3_conf = std::move(*conf);
6982
        s3_conf.prefix = object_store_info.prefix();
6983
    } else {
6984
        LOG(WARNING) << "unknown stage type " << stage_type;
6985
        return -1;
6986
    }
6987
6988
    std::shared_ptr<S3Accessor> s3_accessor;
6989
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
6990
    if (ret != 0) {
6991
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
6992
        return -1;
6993
    }
6994
6995
    *accessor = std::move(s3_accessor);
6996
#endif
6997
3
    return 0;
6998
5
}
6999
7000
11
int InstanceRecycler::recycle_stage() {
7001
11
    int64_t num_scanned = 0;
7002
11
    int64_t num_recycled = 0;
7003
11
    const std::string task_name = "recycle_stage";
7004
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7005
7006
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7007
7008
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7009
11
    register_recycle_task(task_name, start_time);
7010
7011
11
    DORIS_CLOUD_DEFER {
7012
11
        unregister_recycle_task(task_name);
7013
11
        int64_t cost =
7014
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7015
11
        metrics_context.finish_report();
7016
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7017
11
                .tag("instance_id", instance_id_)
7018
11
                .tag("num_scanned", num_scanned)
7019
11
                .tag("num_recycled", num_recycled);
7020
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7011
11
    DORIS_CLOUD_DEFER {
7012
11
        unregister_recycle_task(task_name);
7013
11
        int64_t cost =
7014
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7015
11
        metrics_context.finish_report();
7016
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7017
11
                .tag("instance_id", instance_id_)
7018
11
                .tag("num_scanned", num_scanned)
7019
11
                .tag("num_recycled", num_recycled);
7020
11
    };
7021
7022
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7023
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7024
11
    std::string key0 = recycle_stage_key(key_info0);
7025
11
    std::string key1 = recycle_stage_key(key_info1);
7026
7027
11
    std::vector<std::string_view> stage_keys;
7028
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7029
11
                         this](std::string_view k, std::string_view v) -> int {
7030
1
        ++num_scanned;
7031
1
        RecycleStagePB recycle_stage;
7032
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7033
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7034
0
            return -1;
7035
0
        }
7036
7037
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7038
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7039
0
            LOG(WARNING) << "invalid idx: " << idx;
7040
0
            return -1;
7041
0
        }
7042
7043
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7044
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7045
1
                [&] {
7046
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7047
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7048
1
                    if (!s3_conf) {
7049
1
                        return -1;
7050
1
                    }
7051
7052
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7053
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7054
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7055
1
                    if (ret != 0) {
7056
1
                        return -1;
7057
1
                    }
7058
7059
1
                    accessor = std::move(s3_accessor);
7060
1
                    return 0;
7061
1
                }(),
7062
1
                "recycle_stage:get_accessor", &accessor);
7063
7064
1
        if (ret != 0) {
7065
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7066
0
            return ret;
7067
0
        }
7068
7069
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7070
1
                .tag("instance_id", instance_id_)
7071
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7072
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7073
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7074
1
                .tag("obj_info_id", idx)
7075
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7076
1
        ret = accessor->delete_all();
7077
1
        if (ret != 0) {
7078
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7079
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7080
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7081
0
                         << ", ret=" << ret;
7082
0
            return -1;
7083
0
        }
7084
1
        metrics_context.total_recycled_num = ++num_recycled;
7085
1
        metrics_context.report();
7086
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7087
1
        stage_keys.push_back(k);
7088
1
        return 0;
7089
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7029
1
                         this](std::string_view k, std::string_view v) -> int {
7030
1
        ++num_scanned;
7031
1
        RecycleStagePB recycle_stage;
7032
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7033
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7034
0
            return -1;
7035
0
        }
7036
7037
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7038
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7039
0
            LOG(WARNING) << "invalid idx: " << idx;
7040
0
            return -1;
7041
0
        }
7042
7043
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7044
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7045
1
                [&] {
7046
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7047
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7048
1
                    if (!s3_conf) {
7049
1
                        return -1;
7050
1
                    }
7051
7052
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7053
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7054
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7055
1
                    if (ret != 0) {
7056
1
                        return -1;
7057
1
                    }
7058
7059
1
                    accessor = std::move(s3_accessor);
7060
1
                    return 0;
7061
1
                }(),
7062
1
                "recycle_stage:get_accessor", &accessor);
7063
7064
1
        if (ret != 0) {
7065
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7066
0
            return ret;
7067
0
        }
7068
7069
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7070
1
                .tag("instance_id", instance_id_)
7071
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7072
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7073
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7074
1
                .tag("obj_info_id", idx)
7075
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7076
1
        ret = accessor->delete_all();
7077
1
        if (ret != 0) {
7078
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7079
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7080
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7081
0
                         << ", ret=" << ret;
7082
0
            return -1;
7083
0
        }
7084
1
        metrics_context.total_recycled_num = ++num_recycled;
7085
1
        metrics_context.report();
7086
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7087
1
        stage_keys.push_back(k);
7088
1
        return 0;
7089
1
    };
7090
7091
11
    auto loop_done = [&stage_keys, this]() -> int {
7092
1
        if (stage_keys.empty()) return 0;
7093
1
        DORIS_CLOUD_DEFER {
7094
1
            stage_keys.clear();
7095
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7093
1
        DORIS_CLOUD_DEFER {
7094
1
            stage_keys.clear();
7095
1
        };
7096
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7097
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7098
0
            return -1;
7099
0
        }
7100
1
        return 0;
7101
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7091
1
    auto loop_done = [&stage_keys, this]() -> int {
7092
1
        if (stage_keys.empty()) return 0;
7093
1
        DORIS_CLOUD_DEFER {
7094
1
            stage_keys.clear();
7095
1
        };
7096
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7097
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7098
0
            return -1;
7099
0
        }
7100
1
        return 0;
7101
1
    };
7102
11
    if (config::enable_recycler_stats_metrics) {
7103
0
        scan_and_statistics_stage();
7104
0
    }
7105
    // recycle_func and loop_done for scan and recycle
7106
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7107
11
}
7108
7109
10
int InstanceRecycler::recycle_expired_stage_objects() {
7110
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7111
7112
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7113
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7114
7115
10
    DORIS_CLOUD_DEFER {
7116
10
        int64_t cost =
7117
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7118
10
        metrics_context.finish_report();
7119
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7120
10
                .tag("instance_id", instance_id_);
7121
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7115
10
    DORIS_CLOUD_DEFER {
7116
10
        int64_t cost =
7117
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7118
10
        metrics_context.finish_report();
7119
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7120
10
                .tag("instance_id", instance_id_);
7121
10
    };
7122
7123
10
    int ret = 0;
7124
7125
10
    if (config::enable_recycler_stats_metrics) {
7126
0
        scan_and_statistics_expired_stage_objects();
7127
0
    }
7128
7129
10
    for (const auto& stage : instance_info_.stages()) {
7130
0
        std::stringstream ss;
7131
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7132
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7133
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7134
0
           << ", prefix=" << stage.obj_info().prefix();
7135
7136
0
        if (stopped()) {
7137
0
            break;
7138
0
        }
7139
0
        if (stage.type() == StagePB::EXTERNAL) {
7140
0
            continue;
7141
0
        }
7142
0
        int idx = stoi(stage.obj_info().id());
7143
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7144
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7145
0
            continue;
7146
0
        }
7147
7148
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7149
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7150
0
        if (!s3_conf) {
7151
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7152
0
            continue;
7153
0
        }
7154
7155
0
        s3_conf->prefix = stage.obj_info().prefix();
7156
0
        std::shared_ptr<S3Accessor> accessor;
7157
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7158
0
        if (ret1 != 0) {
7159
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7160
0
            ret = -1;
7161
0
            continue;
7162
0
        }
7163
7164
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7165
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7166
0
            ret = -1;
7167
0
            continue;
7168
0
        }
7169
7170
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7171
0
        int64_t expiration_time =
7172
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7173
0
                config::internal_stage_objects_expire_time_second;
7174
0
        if (config::force_immediate_recycle) {
7175
0
            expiration_time = INT64_MAX;
7176
0
        }
7177
0
        ret1 = accessor->delete_all(expiration_time);
7178
0
        if (ret1 != 0) {
7179
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7180
0
                         << ss.str();
7181
0
            ret = -1;
7182
0
            continue;
7183
0
        }
7184
0
        metrics_context.total_recycled_num++;
7185
0
        metrics_context.report();
7186
0
    }
7187
10
    return ret;
7188
10
}
7189
7190
190
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7191
190
    std::lock_guard lock(recycle_tasks_mutex);
7192
190
    running_recycle_tasks[task_name] = start_time;
7193
190
}
7194
7195
190
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7196
190
    std::lock_guard lock(recycle_tasks_mutex);
7197
190
    DCHECK(running_recycle_tasks[task_name] > 0);
7198
190
    running_recycle_tasks.erase(task_name);
7199
190
}
7200
7201
21
bool InstanceRecycler::check_recycle_tasks() {
7202
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7203
21
    {
7204
21
        std::lock_guard lock(recycle_tasks_mutex);
7205
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7206
21
    }
7207
7208
21
    bool found = false;
7209
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7210
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7211
20
        int64_t cost = now - start_time;
7212
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7213
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7214
20
                    .tag("instance_id", instance_id_)
7215
20
                    .tag("task", task_name);
7216
20
            found = true;
7217
20
        }
7218
20
    }
7219
7220
21
    return found;
7221
21
}
7222
7223
// Scan and statistics indexes that need to be recycled
7224
0
int InstanceRecycler::scan_and_statistics_indexes() {
7225
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7226
7227
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7228
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7229
0
    std::string index_key0;
7230
0
    std::string index_key1;
7231
0
    recycle_index_key(index_key_info0, &index_key0);
7232
0
    recycle_index_key(index_key_info1, &index_key1);
7233
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7234
7235
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7236
0
        RecycleIndexPB index_pb;
7237
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7238
0
            return 0;
7239
0
        }
7240
0
        int64_t current_time = ::time(nullptr);
7241
0
        if (current_time <
7242
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7243
0
            return 0;
7244
0
        }
7245
        // decode index_id
7246
0
        auto k1 = k;
7247
0
        k1.remove_prefix(1);
7248
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7249
0
        decode_key(&k1, &out);
7250
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7251
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7252
0
        std::unique_ptr<Transaction> txn;
7253
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7254
0
        if (err != TxnErrorCode::TXN_OK) {
7255
0
            return 0;
7256
0
        }
7257
0
        std::string val;
7258
0
        err = txn->get(k, &val);
7259
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7260
0
            return 0;
7261
0
        }
7262
0
        if (err != TxnErrorCode::TXN_OK) {
7263
0
            return 0;
7264
0
        }
7265
0
        index_pb.Clear();
7266
0
        if (!index_pb.ParseFromString(val)) {
7267
0
            return 0;
7268
0
        }
7269
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7270
0
            return 0;
7271
0
        }
7272
0
        metrics_context.total_need_recycle_num++;
7273
0
        return 0;
7274
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_
7275
7276
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7277
0
    metrics_context.report(true);
7278
0
    segment_metrics_context_.report(true);
7279
0
    tablet_metrics_context_.report(true);
7280
0
    return ret;
7281
0
}
7282
7283
// Scan and statistics partitions that need to be recycled
7284
0
int InstanceRecycler::scan_and_statistics_partitions() {
7285
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7286
7287
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7288
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7289
0
    std::string part_key0;
7290
0
    std::string part_key1;
7291
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7292
7293
0
    recycle_partition_key(part_key_info0, &part_key0);
7294
0
    recycle_partition_key(part_key_info1, &part_key1);
7295
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7296
0
        RecyclePartitionPB part_pb;
7297
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7298
0
            return 0;
7299
0
        }
7300
0
        int64_t current_time = ::time(nullptr);
7301
0
        if (current_time <
7302
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7303
0
            return 0;
7304
0
        }
7305
        // decode partition_id
7306
0
        auto k1 = k;
7307
0
        k1.remove_prefix(1);
7308
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7309
0
        decode_key(&k1, &out);
7310
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7311
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7312
        // Change state to RECYCLING
7313
0
        std::unique_ptr<Transaction> txn;
7314
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7315
0
        if (err != TxnErrorCode::TXN_OK) {
7316
0
            return 0;
7317
0
        }
7318
0
        std::string val;
7319
0
        err = txn->get(k, &val);
7320
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7321
0
            return 0;
7322
0
        }
7323
0
        if (err != TxnErrorCode::TXN_OK) {
7324
0
            return 0;
7325
0
        }
7326
0
        part_pb.Clear();
7327
0
        if (!part_pb.ParseFromString(val)) {
7328
0
            return 0;
7329
0
        }
7330
        // Partitions with PREPARED state MUST have no data
7331
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7332
0
        int ret = 0;
7333
0
        for (int64_t index_id : part_pb.index_id()) {
7334
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7335
0
                                            partition_id, is_empty_tablet) != 0) {
7336
0
                ret = 0;
7337
0
            }
7338
0
        }
7339
0
        metrics_context.total_need_recycle_num++;
7340
0
        return ret;
7341
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_
7342
7343
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7344
0
    metrics_context.report(true);
7345
0
    segment_metrics_context_.report(true);
7346
0
    tablet_metrics_context_.report(true);
7347
0
    return ret;
7348
0
}
7349
7350
// Scan and statistics rowsets that need to be recycled
7351
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7352
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7353
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7354
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7355
0
    std::string recyc_rs_key0;
7356
0
    std::string recyc_rs_key1;
7357
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7358
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7359
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7360
7361
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7362
0
        RecycleRowsetPB rowset;
7363
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7364
0
            return 0;
7365
0
        }
7366
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7367
0
        int64_t current_time = ::time(nullptr);
7368
0
        if (current_time <
7369
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7370
0
            return 0;
7371
0
        }
7372
7373
0
        if (!rowset.has_type()) {
7374
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7375
0
                return 0;
7376
0
            }
7377
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7378
0
                return 0;
7379
0
            }
7380
0
            metrics_context.total_need_recycle_num++;
7381
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7382
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7383
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7384
0
            return 0;
7385
0
        }
7386
7387
0
        if(!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled()) {
7388
0
            return 0;
7389
0
        }
7390
7391
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7392
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7393
0
                return 0;
7394
0
            }
7395
0
        }
7396
0
        metrics_context.total_need_recycle_num++;
7397
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7398
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7399
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7400
0
        return 0;
7401
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_
7402
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7403
0
    metrics_context.report(true);
7404
0
    segment_metrics_context_.report(true);
7405
0
    return ret;
7406
0
}
7407
7408
// Scan and statistics tmp_rowsets that need to be recycled
7409
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7410
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7411
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7412
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7413
0
    std::string tmp_rs_key0;
7414
0
    std::string tmp_rs_key1;
7415
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7416
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7417
7418
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7419
7420
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7421
0
        doris::RowsetMetaCloudPB rowset;
7422
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7423
0
            return 0;
7424
0
        }
7425
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7426
0
        int64_t current_time = ::time(nullptr);
7427
0
        if (current_time < expiration) {
7428
0
            return 0;
7429
0
        }
7430
7431
0
        DCHECK_GT(rowset.txn_id(), 0)
7432
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7433
7434
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
7435
0
            return 0;
7436
0
        }
7437
7438
0
        if (!rowset.has_resource_id()) {
7439
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7440
0
                return 0;
7441
0
            }
7442
0
            return 0;
7443
0
        }
7444
7445
0
        metrics_context.total_need_recycle_num++;
7446
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7447
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7448
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7449
0
        return 0;
7450
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_
7451
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7452
0
    metrics_context.report(true);
7453
0
    segment_metrics_context_.report(true);
7454
0
    return ret;
7455
0
}
7456
7457
// Scan and statistics abort_timeout_txn that need to be recycled
7458
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7459
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7460
7461
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7462
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7463
0
    std::string begin_txn_running_key;
7464
0
    std::string end_txn_running_key;
7465
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7466
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7467
7468
0
    int64_t current_time =
7469
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7470
7471
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7472
0
                                               std::string_view k, std::string_view v) -> int {
7473
0
        std::unique_ptr<Transaction> txn;
7474
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7475
0
        if (err != TxnErrorCode::TXN_OK) {
7476
0
            return 0;
7477
0
        }
7478
0
        std::string_view k1 = k;
7479
0
        k1.remove_prefix(1);
7480
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7481
0
        if (decode_key(&k1, &out) != 0) {
7482
0
            return 0;
7483
0
        }
7484
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7485
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7486
        // Update txn_info
7487
0
        std::string txn_inf_key, txn_inf_val;
7488
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7489
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7490
0
        if (err != TxnErrorCode::TXN_OK) {
7491
0
            return 0;
7492
0
        }
7493
0
        TxnInfoPB txn_info;
7494
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7495
0
            return 0;
7496
0
        }
7497
7498
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7499
0
            TxnRunningPB txn_running_pb;
7500
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7501
0
                return 0;
7502
0
            }
7503
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7504
0
                return 0;
7505
0
            }
7506
0
            metrics_context.total_need_recycle_num++;
7507
0
        }
7508
0
        return 0;
7509
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_
7510
7511
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
7512
0
    metrics_context.report(true);
7513
0
    return ret;
7514
0
}
7515
7516
// Scan and statistics expired_txn_label that need to be recycled
7517
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7518
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7519
7520
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7521
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7522
0
    std::string begin_recycle_txn_key;
7523
0
    std::string end_recycle_txn_key;
7524
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7525
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7526
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7527
0
    int64_t current_time_ms =
7528
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7529
7530
    // for calculate the total num or bytes of recyled objects
7531
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7532
0
        RecycleTxnPB recycle_txn_pb;
7533
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7534
0
            return 0;
7535
0
        }
7536
0
        if ((config::force_immediate_recycle) ||
7537
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7538
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7539
0
             current_time_ms)) {
7540
0
            metrics_context.total_need_recycle_num++;
7541
0
        }
7542
0
        return 0;
7543
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_
7544
7545
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
7546
0
    metrics_context.report(true);
7547
0
    return ret;
7548
0
}
7549
7550
// Scan and statistics copy_jobs that need to be recycled
7551
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7552
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7553
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7554
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7555
0
    std::string key0;
7556
0
    std::string key1;
7557
0
    copy_job_key(key_info0, &key0);
7558
0
    copy_job_key(key_info1, &key1);
7559
7560
    // for calculate the total num or bytes of recyled objects
7561
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7562
0
        CopyJobPB copy_job;
7563
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7564
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7565
0
            return 0;
7566
0
        }
7567
7568
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7569
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7570
0
                int64_t current_time =
7571
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7572
0
                if (copy_job.finish_time_ms() > 0) {
7573
0
                    if (!config::force_immediate_recycle &&
7574
0
                        current_time < copy_job.finish_time_ms() +
7575
0
                                               config::copy_job_max_retention_second * 1000) {
7576
0
                        return 0;
7577
0
                    }
7578
0
                } else {
7579
0
                    if (!config::force_immediate_recycle &&
7580
0
                        current_time < copy_job.start_time_ms() +
7581
0
                                               config::copy_job_max_retention_second * 1000) {
7582
0
                        return 0;
7583
0
                    }
7584
0
                }
7585
0
            }
7586
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7587
0
            int64_t current_time =
7588
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7589
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7590
0
                return 0;
7591
0
            }
7592
0
        }
7593
0
        metrics_context.total_need_recycle_num++;
7594
0
        return 0;
7595
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_
7596
7597
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7598
0
    metrics_context.report(true);
7599
0
    return ret;
7600
0
}
7601
7602
// Scan and statistics stage that need to be recycled
7603
0
int InstanceRecycler::scan_and_statistics_stage() {
7604
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7605
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7606
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7607
0
    std::string key0 = recycle_stage_key(key_info0);
7608
0
    std::string key1 = recycle_stage_key(key_info1);
7609
7610
    // for calculate the total num or bytes of recyled objects
7611
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7612
0
                                                        std::string_view v) -> int {
7613
0
        RecycleStagePB recycle_stage;
7614
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7615
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7616
0
            return 0;
7617
0
        }
7618
7619
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
7620
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7621
0
            LOG(WARNING) << "invalid idx: " << idx;
7622
0
            return 0;
7623
0
        }
7624
7625
0
        std::shared_ptr<StorageVaultAccessor> accessor;
7626
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7627
0
                [&] {
7628
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7629
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7630
0
                    if (!s3_conf) {
7631
0
                        return 0;
7632
0
                    }
7633
7634
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7635
0
                    std::shared_ptr<S3Accessor> s3_accessor;
7636
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7637
0
                    if (ret != 0) {
7638
0
                        return 0;
7639
0
                    }
7640
7641
0
                    accessor = std::move(s3_accessor);
7642
0
                    return 0;
7643
0
                }(),
7644
0
                "recycle_stage:get_accessor", &accessor);
7645
7646
0
        if (ret != 0) {
7647
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7648
0
            return 0;
7649
0
        }
7650
7651
0
        metrics_context.total_need_recycle_num++;
7652
0
        return 0;
7653
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_
7654
7655
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7656
0
    metrics_context.report(true);
7657
0
    return ret;
7658
0
}
7659
7660
// Scan and statistics expired_stage_objects that need to be recycled
7661
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
7662
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7663
7664
    // for calculate the total num or bytes of recyled objects
7665
0
    auto scan_and_statistics = [&metrics_context, this]() {
7666
0
        for (const auto& stage : instance_info_.stages()) {
7667
0
            if (stopped()) {
7668
0
                break;
7669
0
            }
7670
0
            if (stage.type() == StagePB::EXTERNAL) {
7671
0
                continue;
7672
0
            }
7673
0
            int idx = stoi(stage.obj_info().id());
7674
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
7675
0
                continue;
7676
0
            }
7677
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
7678
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7679
0
            if (!s3_conf) {
7680
0
                continue;
7681
0
            }
7682
0
            s3_conf->prefix = stage.obj_info().prefix();
7683
0
            std::shared_ptr<S3Accessor> accessor;
7684
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
7685
0
            if (ret1 != 0) {
7686
0
                continue;
7687
0
            }
7688
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7689
0
                continue;
7690
0
            }
7691
0
            metrics_context.total_need_recycle_num++;
7692
0
        }
7693
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
7694
7695
0
    scan_and_statistics();
7696
0
    metrics_context.report(true);
7697
0
    return 0;
7698
0
}
7699
7700
// Scan and statistics versions that need to be recycled
7701
0
int InstanceRecycler::scan_and_statistics_versions() {
7702
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
7703
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
7704
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
7705
7706
0
    int64_t last_scanned_table_id = 0;
7707
0
    bool is_recycled = false; // Is last scanned kv recycled
7708
    // for calculate the total num or bytes of recyled objects
7709
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
7710
0
                                       std::string_view k, std::string_view) {
7711
0
        auto k1 = k;
7712
0
        k1.remove_prefix(1);
7713
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
7714
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7715
0
        decode_key(&k1, &out);
7716
0
        DCHECK_EQ(out.size(), 6) << k;
7717
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
7718
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
7719
0
            metrics_context.total_need_recycle_num +=
7720
0
                    is_recycled; // Version kv of this table has been recycled
7721
0
            return 0;
7722
0
        }
7723
0
        last_scanned_table_id = table_id;
7724
0
        is_recycled = false;
7725
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
7726
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
7727
0
        std::unique_ptr<Transaction> txn;
7728
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7729
0
        if (err != TxnErrorCode::TXN_OK) {
7730
0
            return 0;
7731
0
        }
7732
0
        std::unique_ptr<RangeGetIterator> iter;
7733
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
7734
0
        if (err != TxnErrorCode::TXN_OK) {
7735
0
            return 0;
7736
0
        }
7737
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
7738
0
            return 0;
7739
0
        }
7740
0
        metrics_context.total_need_recycle_num++;
7741
0
        is_recycled = true;
7742
0
        return 0;
7743
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_
7744
7745
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
7746
0
    metrics_context.report(true);
7747
0
    return ret;
7748
0
}
7749
7750
// Scan and statistics restore jobs that need to be recycled
7751
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
7752
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
7753
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
7754
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
7755
0
    std::string restore_job_key0;
7756
0
    std::string restore_job_key1;
7757
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
7758
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
7759
7760
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7761
7762
    // for calculate the total num or bytes of recyled objects
7763
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
7764
0
        RestoreJobCloudPB restore_job_pb;
7765
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
7766
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
7767
0
            return 0;
7768
0
        }
7769
0
        int64_t expiration =
7770
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
7771
0
        int64_t current_time = ::time(nullptr);
7772
0
        if (current_time < expiration) { // not expired
7773
0
            return 0;
7774
0
        }
7775
0
        metrics_context.total_need_recycle_num++;
7776
0
        if(restore_job_pb.need_recycle_data()) {
7777
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
7778
0
        }
7779
0
        return 0;
7780
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_
7781
7782
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
7783
0
    metrics_context.report(true);
7784
0
    return ret;
7785
0
}
7786
7787
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
7788
3
    if (!should_recycle_versioned_keys()) {
7789
0
        return;
7790
0
    }
7791
7792
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
7793
7794
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
7795
3
    if (recycle_checker.init() != 0) {
7796
0
        return;
7797
0
    }
7798
7799
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
7800
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
7801
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
7802
7803
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
7804
8
    for (; iter->valid(); iter->next()) {
7805
5
        OperationLogPB operation_log;
7806
5
        if (!iter->parse_value(&operation_log)) {
7807
0
            continue;
7808
0
        }
7809
7810
5
        std::string_view key = iter->key();
7811
5
        Versionstamp log_versionstamp;
7812
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
7813
0
            continue;
7814
0
        }
7815
7816
5
        OperationLogReferenceInfo ref_info;
7817
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
7818
5
                                         &ref_info)) {
7819
4
            metrics_context.total_need_recycle_num++;
7820
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
7821
4
        }
7822
5
    }
7823
7824
3
    metrics_context.report(true);
7825
3
}
7826
7827
int InstanceRecycler::classify_rowset_task_by_ref_count(
7828
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7829
60
    constexpr int MAX_RETRY = 10;
7830
60
    const auto& rowset_meta = task.rowset_meta;
7831
60
    int64_t tablet_id = rowset_meta.tablet_id();
7832
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7833
60
    std::string_view reference_instance_id = instance_id_;
7834
60
    if (rowset_meta.has_reference_instance_id()) {
7835
5
        reference_instance_id = rowset_meta.reference_instance_id();
7836
5
    }
7837
7838
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7839
61
        std::unique_ptr<Transaction> txn;
7840
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7841
61
        if (err != TxnErrorCode::TXN_OK) {
7842
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7843
0
                    .tag("instance_id", instance_id_)
7844
0
                    .tag("tablet_id", tablet_id)
7845
0
                    .tag("rowset_id", rowset_id)
7846
0
                    .tag("err", err);
7847
0
            return -1;
7848
0
        }
7849
7850
61
        std::string rowset_ref_count_key =
7851
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7852
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7853
7854
61
        int64_t ref_count = 0;
7855
61
        {
7856
61
            std::string value;
7857
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7858
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7859
0
                ref_count = 1;
7860
61
            } else if (err != TxnErrorCode::TXN_OK) {
7861
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7862
0
                        .tag("instance_id", instance_id_)
7863
0
                        .tag("tablet_id", tablet_id)
7864
0
                        .tag("rowset_id", rowset_id)
7865
0
                        .tag("err", err);
7866
0
                return -1;
7867
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7868
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7869
0
                        .tag("instance_id", instance_id_)
7870
0
                        .tag("tablet_id", tablet_id)
7871
0
                        .tag("rowset_id", rowset_id)
7872
0
                        .tag("value", hex(value));
7873
0
                return -1;
7874
0
            }
7875
61
        }
7876
7877
61
        if (ref_count > 1) {
7878
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7879
12
            txn->atomic_add(rowset_ref_count_key, -1);
7880
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7881
12
                    .tag("instance_id", instance_id_)
7882
12
                    .tag("tablet_id", tablet_id)
7883
12
                    .tag("rowset_id", rowset_id)
7884
12
                    .tag("ref_count", ref_count - 1)
7885
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7886
7887
12
            if (!task.recycle_rowset_key.empty()) {
7888
12
                txn->remove(task.recycle_rowset_key);
7889
12
                LOG_INFO("remove recycle rowset key in classification phase")
7890
12
                        .tag("key", hex(task.recycle_rowset_key));
7891
12
            }
7892
12
            if (!task.non_versioned_rowset_key.empty()) {
7893
12
                txn->remove(task.non_versioned_rowset_key);
7894
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7895
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7896
12
            }
7897
7898
12
            err = txn->commit();
7899
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7900
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7901
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7902
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7903
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7904
1
                continue;
7905
11
            } else if (err != TxnErrorCode::TXN_OK) {
7906
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7907
0
                        .tag("instance_id", instance_id_)
7908
0
                        .tag("tablet_id", tablet_id)
7909
0
                        .tag("rowset_id", rowset_id)
7910
0
                        .tag("err", err);
7911
0
                return -1;
7912
0
            }
7913
11
            return 1; // handled, not added to batch delete
7914
49
        } else {
7915
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7916
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7917
49
            LOG_INFO("add rowset to batch delete plan")
7918
49
                    .tag("instance_id", instance_id_)
7919
49
                    .tag("tablet_id", tablet_id)
7920
49
                    .tag("rowset_id", rowset_id)
7921
49
                    .tag("resource_id", rowset_meta.resource_id())
7922
49
                    .tag("ref_count", ref_count);
7923
7924
49
            batch_delete_tasks.push_back(std::move(task));
7925
49
            return 0; // added to batch delete
7926
49
        }
7927
61
    }
7928
7929
0
    LOG_WARNING("failed to classify rowset task after retry")
7930
0
            .tag("instance_id", instance_id_)
7931
0
            .tag("tablet_id", tablet_id)
7932
0
            .tag("rowset_id", rowset_id)
7933
0
            .tag("retry", MAX_RETRY);
7934
0
    return -1;
7935
60
}
7936
7937
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7938
10
    int ret = 0;
7939
49
    for (const auto& task : tasks) {
7940
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7941
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7942
7943
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7944
        // so we don't need to call it again here.
7945
7946
        // Remove all metadata keys in one transaction
7947
49
        std::unique_ptr<Transaction> txn;
7948
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7949
49
        if (err != TxnErrorCode::TXN_OK) {
7950
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7951
0
                    .tag("instance_id", instance_id_)
7952
0
                    .tag("tablet_id", tablet_id)
7953
0
                    .tag("rowset_id", rowset_id)
7954
0
                    .tag("err", err);
7955
0
            ret = -1;
7956
0
            continue;
7957
0
        }
7958
7959
49
        std::string_view reference_instance_id = instance_id_;
7960
49
        if (task.rowset_meta.has_reference_instance_id()) {
7961
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
7962
5
        }
7963
7964
49
        txn->remove(task.rowset_ref_count_key);
7965
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7966
49
                .tag("instance_id", instance_id_)
7967
49
                .tag("tablet_id", tablet_id)
7968
49
                .tag("rowset_id", rowset_id)
7969
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7970
7971
49
        std::string dbm_start_key =
7972
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7973
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7974
49
                {reference_instance_id, tablet_id, rowset_id,
7975
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
7976
49
        txn->remove(dbm_start_key, dbm_end_key);
7977
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7978
49
                .tag("instance_id", instance_id_)
7979
49
                .tag("tablet_id", tablet_id)
7980
49
                .tag("rowset_id", rowset_id)
7981
49
                .tag("begin", hex(dbm_start_key))
7982
49
                .tag("end", hex(dbm_end_key));
7983
7984
49
        std::string versioned_dbm_start_key =
7985
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7986
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7987
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7988
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7989
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7990
49
                .tag("instance_id", instance_id_)
7991
49
                .tag("tablet_id", tablet_id)
7992
49
                .tag("rowset_id", rowset_id)
7993
49
                .tag("begin", hex(versioned_dbm_start_key))
7994
49
                .tag("end", hex(versioned_dbm_end_key));
7995
7996
        // Remove versioned meta rowset key
7997
49
        if (!task.versioned_rowset_key.empty()) {
7998
49
            std::string versioned_rowset_key_end = task.versioned_rowset_key;
7999
49
            encode_int64(INT64_MAX, &versioned_rowset_key_end);
8000
49
            txn->remove(task.versioned_rowset_key, versioned_rowset_key_end);
8001
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8002
49
                    .tag("instance_id", instance_id_)
8003
49
                    .tag("tablet_id", tablet_id)
8004
49
                    .tag("rowset_id", rowset_id)
8005
49
                    .tag("begin", hex(task.versioned_rowset_key))
8006
49
                    .tag("end", hex(versioned_rowset_key_end));
8007
49
        }
8008
8009
49
        if (!task.non_versioned_rowset_key.empty()) {
8010
49
            txn->remove(task.non_versioned_rowset_key);
8011
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8012
49
                    .tag("instance_id", instance_id_)
8013
49
                    .tag("tablet_id", tablet_id)
8014
49
                    .tag("rowset_id", rowset_id)
8015
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8016
49
        }
8017
8018
        // Remove recycle_rowset_key last to ensure retry safety:
8019
        // if cleanup fails, this key remains and triggers next round retry.
8020
49
        if (!task.recycle_rowset_key.empty()) {
8021
49
            txn->remove(task.recycle_rowset_key);
8022
49
            LOG_INFO("remove recycle rowset key in cleanup phase")
8023
49
                    .tag("instance_id", instance_id_)
8024
49
                    .tag("tablet_id", tablet_id)
8025
49
                    .tag("rowset_id", rowset_id)
8026
49
                    .tag("key", hex(task.recycle_rowset_key));
8027
49
        }
8028
8029
49
        err = txn->commit();
8030
49
        if (err != TxnErrorCode::TXN_OK) {
8031
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8032
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8033
0
                    .tag("instance_id", instance_id_)
8034
0
                    .tag("tablet_id", tablet_id)
8035
0
                    .tag("rowset_id", rowset_id)
8036
0
                    .tag("err", err);
8037
0
            ret = -1;
8038
0
            continue;
8039
0
        }
8040
8041
49
        LOG_INFO("cleanup rowset metadata success")
8042
49
                .tag("instance_id", instance_id_)
8043
49
                .tag("tablet_id", tablet_id)
8044
49
                .tag("rowset_id", rowset_id);
8045
49
    }
8046
10
    return ret;
8047
10
}
8048
8049
} // namespace doris::cloud