Coverage Report

Created: 2026-08-27 12:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/rowset_segment_id.h"
73
#include "common/simple_thread_pool.h"
74
#include "common/util.h"
75
#include "cpp/sync_point.h"
76
#include "meta-store/codec.h"
77
#include "meta-store/document_message.h"
78
#include "meta-store/keys.h"
79
#include "recycler/recycler_service.h"
80
#include "recycler/sync_executor.h"
81
#include "recycler/util.h"
82
#include "snapshot/snapshot_manager_factory.h"
83
84
namespace doris::cloud {
85
86
using namespace std::chrono;
87
88
namespace {
89
90
constexpr size_t kRowsetBatchGetSize = 256;
91
92
0
int64_t packed_file_retry_sleep_ms() {
93
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
94
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
95
0
    thread_local std::mt19937_64 gen(std::random_device {}());
96
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
97
0
    return dist(gen);
98
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
99
100
0
void sleep_for_packed_file_retry() {
101
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
102
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
103
104
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
7
    const auto& locations = rowset.packed_slice_locations();
106
7
    auto it = locations.find(path);
107
7
    return it != locations.end() && it->second.has_packed_file_path() &&
108
7
           !it->second.packed_file_path().empty();
109
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
110
111
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
112
                                      const std::string& path,
113
868k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
868k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
7
                                      std::vector<std::string>* file_paths) {
114
7
    if (!is_packed_slice_path(rowset, path)) {
115
7
        file_paths->push_back(path);
116
7
    }
117
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
868k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
868k
}
118
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
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
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
127
128
} // namespace
129
130
// return 0 for success get a key, 1 for key not found, negative for error
131
18
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
18
    std::unique_ptr<Transaction> txn;
133
18
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
18
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
18
    switch (txn->get(key, &val, true)) {
138
8
    case TxnErrorCode::TXN_OK:
139
8
        return 0;
140
10
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
10
        return 1;
142
0
    default:
143
0
        return -1;
144
18
    };
145
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
10
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
10
    std::unique_ptr<Transaction> txn;
133
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
10
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
10
    switch (txn->get(key, &val, true)) {
138
3
    case TxnErrorCode::TXN_OK:
139
3
        return 0;
140
7
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
7
        return 1;
142
0
    default:
143
0
        return -1;
144
10
    };
145
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
8
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
8
    std::unique_ptr<Transaction> txn;
133
8
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
8
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
8
    switch (txn->get(key, &val, true)) {
138
5
    case TxnErrorCode::TXN_OK:
139
5
        return 0;
140
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
3
        return 1;
142
0
    default:
143
0
        return -1;
144
8
    };
145
0
}
146
147
// 0 for success, negative for error
148
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
149
419
                   std::unique_ptr<RangeGetIterator>& it) {
150
419
    std::unique_ptr<Transaction> txn;
151
419
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
419
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
419
    switch (txn->get(begin, end, &it, true)) {
156
419
    case TxnErrorCode::TXN_OK:
157
419
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
419
    };
163
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
39
                   std::unique_ptr<RangeGetIterator>& it) {
150
39
    std::unique_ptr<Transaction> txn;
151
39
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
39
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
39
    switch (txn->get(begin, end, &it, true)) {
156
39
    case TxnErrorCode::TXN_OK:
157
39
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
39
    };
163
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
380
                   std::unique_ptr<RangeGetIterator>& it) {
150
380
    std::unique_ptr<Transaction> txn;
151
380
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
380
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
380
    switch (txn->get(begin, end, &it, true)) {
156
380
    case TxnErrorCode::TXN_OK:
157
380
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
380
    };
163
0
}
164
165
// return 0 for success otherwise error
166
22
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
22
    std::unique_ptr<Transaction> txn;
168
22
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
22
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
22
    switch (txn->commit()) {
176
22
    case TxnErrorCode::TXN_OK:
177
22
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
22
    }
183
22
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
5
    std::unique_ptr<Transaction> txn;
168
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
5
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
5
    for (auto k : keys) {
173
5
        txn->remove(k);
174
5
    }
175
5
    switch (txn->commit()) {
176
5
    case TxnErrorCode::TXN_OK:
177
5
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
5
    }
183
5
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
17
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
17
    std::unique_ptr<Transaction> txn;
168
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
17
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
17
    switch (txn->commit()) {
176
17
    case TxnErrorCode::TXN_OK:
177
17
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
17
    }
183
17
}
184
185
// return 0 for success otherwise error
186
360
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
360
    std::unique_ptr<Transaction> txn;
188
360
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
360
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
360
    switch (txn->commit()) {
196
360
    case TxnErrorCode::TXN_OK:
197
360
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
360
    }
203
360
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
33
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
33
    std::unique_ptr<Transaction> txn;
188
33
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
33
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
33
    for (auto& k : keys) {
193
17
        txn->remove(k);
194
17
    }
195
33
    switch (txn->commit()) {
196
33
    case TxnErrorCode::TXN_OK:
197
33
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
33
    }
203
33
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
327
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
327
    std::unique_ptr<Transaction> txn;
188
327
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
327
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
327
    switch (txn->commit()) {
196
327
    case TxnErrorCode::TXN_OK:
197
327
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
327
    }
203
327
}
204
205
// return 0 for success otherwise error
206
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
207
105k
                                       std::string_view end) {
208
105k
    std::unique_ptr<Transaction> txn;
209
105k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
105k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
105k
    txn->remove(begin, end);
214
105k
    switch (txn->commit()) {
215
105k
    case TxnErrorCode::TXN_OK:
216
105k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
105k
    }
222
105k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
14
                                       std::string_view end) {
208
14
    std::unique_ptr<Transaction> txn;
209
14
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
14
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
14
    txn->remove(begin, end);
214
14
    switch (txn->commit()) {
215
14
    case TxnErrorCode::TXN_OK:
216
14
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
14
    }
222
14
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
105k
                                       std::string_view end) {
208
105k
    std::unique_ptr<Transaction> txn;
209
105k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
105k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
105k
    txn->remove(begin, end);
214
105k
    switch (txn->commit()) {
215
105k
    case TxnErrorCode::TXN_OK:
216
105k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
105k
    }
222
105k
}
223
224
void scan_restore_job_rowset(
225
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
226
        std::string& msg,
227
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
228
229
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
230
                                      int64_t num_scanned, int64_t num_recycled,
231
62
                                      int64_t start_time) {
232
62
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
62
    return;
244
62
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
231
5
                                      int64_t start_time) {
232
5
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
5
    return;
244
5
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
231
57
                                      int64_t start_time) {
232
57
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
233
0
        int64_t cost =
234
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
235
0
        if (cost > config::recycle_task_threshold_seconds) {
236
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
237
0
                    .tag("instance_id", instance_id)
238
0
                    .tag("task", task_name)
239
0
                    .tag("num_scanned", num_scanned)
240
0
                    .tag("num_recycled", num_recycled);
241
0
        }
242
0
    }
243
57
    return;
244
57
}
245
246
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
247
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
248
249
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
250
6
                                                               "s3_producer_pool");
251
6
    s3_producer_pool->start();
252
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
253
6
                                                                  "recycle_tablet_pool");
254
6
    recycle_tablet_pool->start();
255
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
256
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
257
6
    group_recycle_function_pool->start();
258
6
    _thread_pool_group =
259
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
260
6
                                    std::move(group_recycle_function_pool));
261
262
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
263
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
264
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
265
6
}
266
267
6
Recycler::~Recycler() {
268
6
    if (!stopped()) {
269
0
        stop();
270
0
    }
271
6
}
272
273
5
void Recycler::instance_scanner_callback() {
274
    // sleep 60 seconds before scheduling for the launch procedure to complete:
275
    // some bad hdfs connection may cause some log to stdout stderr
276
    // which may pollute .out file and affect the script to check success
277
5
    std::this_thread::sleep_for(
278
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
279
1.36k
    while (!stopped()) {
280
1.36k
        if (config::enable_recycler) {
281
4
            std::vector<InstanceInfoPB> instances;
282
4
            get_all_instances(txn_kv_.get(), instances);
283
            // TODO(plat1ko): delete job recycle kv of non-existent instances
284
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
285
4
                std::stringstream ss;
286
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
287
4
                return ss.str();
288
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
284
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
285
4
                std::stringstream ss;
286
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
287
4
                return ss.str();
288
4
            }();
289
4
            if (!instances.empty()) {
290
                // enqueue instances
291
3
                std::lock_guard lock(mtx_);
292
30
                for (auto& instance : instances) {
293
30
                    if (filter_out_instance(instance.instance_id())) continue;
294
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
295
                    // skip instance already in pending queue
296
30
                    if (success) {
297
30
                        pending_instance_queue_.push_back(std::move(instance));
298
30
                    }
299
30
                }
300
3
                pending_instance_cond_.notify_all();
301
3
            }
302
1.35k
        } else {
303
1.35k
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
304
1.35k
        }
305
1.36k
        {
306
1.36k
            std::unique_lock lock(mtx_);
307
1.36k
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
308
2.72k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
308
2.72k
                               [&]() { return stopped(); });
309
1.36k
        }
310
1.36k
    }
311
5
}
312
313
9
void Recycler::recycle_callback() {
314
40
    while (!stopped()) {
315
39
        InstanceInfoPB instance;
316
39
        {
317
39
            std::unique_lock lock(mtx_);
318
39
            pending_instance_cond_.wait(
319
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
319
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
320
39
            if (stopped()) {
321
8
                return;
322
8
            }
323
31
            instance = std::move(pending_instance_queue_.front());
324
31
            pending_instance_queue_.pop_front();
325
31
            pending_instance_set_.erase(instance.instance_id());
326
31
        }
327
0
        auto& instance_id = instance.instance_id();
328
31
        {
329
31
            std::lock_guard lock(mtx_);
330
            // skip instance in recycling
331
31
            if (recycling_instance_map_.count(instance_id)) continue;
332
31
        }
333
31
        if (!config::enable_recycler) {
334
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
335
1
                         << " since enable_recycler is false";
336
1
            continue;
337
1
        }
338
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
339
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
340
341
30
        if (int r = instance_recycler->init(); r != 0) {
342
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
343
0
                         << " ret=" << r;
344
0
            continue;
345
0
        }
346
30
        std::string recycle_job_key;
347
30
        job_recycle_key({instance_id}, &recycle_job_key);
348
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
349
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
350
30
        if (ret != 0) { // Prepare failed
351
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
352
20
                         << " ret=" << ret;
353
20
            continue;
354
20
        } else {
355
10
            std::lock_guard lock(mtx_);
356
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
357
10
        }
358
10
        if (stopped()) return;
359
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
360
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
361
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
362
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
363
10
        ret = instance_recycler->do_recycle();
364
        // If instance recycler has been aborted, don't finish this job
365
366
10
        if (!instance_recycler->stopped()) {
367
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
368
10
                                        ret == 0, ctime_ms);
369
10
        }
370
10
        if (instance_recycler->stopped() || ret != 0) {
371
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
372
0
        }
373
10
        {
374
10
            std::lock_guard lock(mtx_);
375
10
            recycling_instance_map_.erase(instance_id);
376
10
        }
377
378
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
379
10
        auto elpased_ms = now - ctime_ms;
380
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
381
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
382
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
383
10
                                             now + config::recycle_interval_seconds * 1000);
384
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
385
10
        LOG(INFO) << "recycle instance done, "
386
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
387
10
                  << " now: " << now;
388
389
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
390
391
10
        LOG_WARNING("finish recycle instance")
392
10
                .tag("instance_id", instance_id)
393
10
                .tag("cost_ms", elpased_ms);
394
10
    }
395
9
}
396
397
4
void Recycler::lease_recycle_jobs() {
398
54
    while (!stopped()) {
399
50
        std::vector<std::string> instances;
400
50
        instances.reserve(recycling_instance_map_.size());
401
50
        {
402
50
            std::lock_guard lock(mtx_);
403
50
            for (auto& [id, _] : recycling_instance_map_) {
404
30
                instances.push_back(id);
405
30
            }
406
50
        }
407
50
        for (auto& i : instances) {
408
30
            std::string recycle_job_key;
409
30
            job_recycle_key({i}, &recycle_job_key);
410
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
411
30
            if (ret == 1) {
412
0
                std::lock_guard lock(mtx_);
413
0
                if (auto it = recycling_instance_map_.find(i);
414
0
                    it != recycling_instance_map_.end()) {
415
0
                    it->second->stop();
416
0
                }
417
0
            }
418
30
        }
419
50
        {
420
50
            std::unique_lock lock(mtx_);
421
50
            notifier_.wait_for(lock,
422
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
423
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
423
100
                               [&]() { return stopped(); });
424
50
        }
425
50
    }
426
4
}
427
428
4
void Recycler::check_recycle_tasks() {
429
7
    while (!stopped()) {
430
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
431
3
        {
432
3
            std::lock_guard lock(mtx_);
433
3
            recycling_instance_map = recycling_instance_map_;
434
3
        }
435
3
        for (auto& entry : recycling_instance_map) {
436
0
            entry.second->check_recycle_tasks();
437
0
        }
438
439
3
        std::unique_lock lock(mtx_);
440
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
441
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
441
6
                           [&]() { return stopped(); });
442
3
    }
443
4
}
444
445
4
int Recycler::start(brpc::Server* server) {
446
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
447
4
    S3Environment::getInstance();
448
449
4
    if (config::enable_checker) {
450
0
        checker_ = std::make_unique<Checker>(txn_kv_);
451
0
        int ret = checker_->start();
452
0
        std::string msg;
453
0
        if (ret != 0) {
454
0
            msg = "failed to start checker";
455
0
            LOG(ERROR) << msg;
456
0
            std::cerr << msg << std::endl;
457
0
            return ret;
458
0
        }
459
0
        msg = "checker started";
460
0
        LOG(INFO) << msg;
461
0
        std::cout << msg << std::endl;
462
0
    }
463
464
4
    if (server) {
465
        // Add service
466
1
        auto recycler_service =
467
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
468
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
469
1
    }
470
471
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
471
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
472
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
473
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
473
8
        workers_.emplace_back([this] { recycle_callback(); });
474
8
    }
475
476
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
477
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
478
479
4
    if (config::enable_snapshot_data_migrator) {
480
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
481
0
        int ret = snapshot_data_migrator_->start();
482
0
        if (ret != 0) {
483
0
            LOG(ERROR) << "failed to start snapshot data migrator";
484
0
            return ret;
485
0
        }
486
0
        LOG(INFO) << "snapshot data migrator started";
487
0
    }
488
489
4
    if (config::enable_snapshot_chain_compactor) {
490
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
491
0
        int ret = snapshot_chain_compactor_->start();
492
0
        if (ret != 0) {
493
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
494
0
            return ret;
495
0
        }
496
0
        LOG(INFO) << "snapshot chain compactor started";
497
0
    }
498
499
4
    return 0;
500
4
}
501
502
4
void Recycler::stop() {
503
4
    stopped_ = true;
504
4
    notifier_.notify_all();
505
4
    pending_instance_cond_.notify_all();
506
4
    {
507
4
        std::lock_guard lock(mtx_);
508
4
        for (auto& [_, recycler] : recycling_instance_map_) {
509
0
            recycler->stop();
510
0
        }
511
4
    }
512
20
    for (auto& w : workers_) {
513
20
        if (w.joinable()) w.join();
514
20
    }
515
4
    if (checker_) {
516
0
        checker_->stop();
517
0
    }
518
4
    if (snapshot_data_migrator_) {
519
0
        snapshot_data_migrator_->stop();
520
0
    }
521
4
    if (snapshot_chain_compactor_) {
522
0
        snapshot_chain_compactor_->stop();
523
0
    }
524
4
}
525
526
class InstanceRecycler::InvertedIndexIdCache {
527
public:
528
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
529
187
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
530
531
    // Return 0 if success, 1 if schema kv not found, negative for error
532
    // For the same index_id, schema_version, res, since `get` is not completely atomic
533
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
534
    // resulting in repeated addition and inaccuracy.
535
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
536
    // repeated addition does not affect correctness.
537
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
538
28.4k
        {
539
28.4k
            std::lock_guard lock(mtx_);
540
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
541
4.70k
                return 0;
542
4.70k
            }
543
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
544
23.7k
                it != inverted_index_id_map_.end()) {
545
18.1k
                res = it->second;
546
18.1k
                return 0;
547
18.1k
            }
548
23.7k
        }
549
        // Get schema from kv
550
        // TODO(plat1ko): Single flight
551
5.54k
        std::unique_ptr<Transaction> txn;
552
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
553
5.54k
        if (err != TxnErrorCode::TXN_OK) {
554
0
            LOG(WARNING) << "failed to create txn, err=" << err;
555
0
            return -1;
556
0
        }
557
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
558
5.54k
        ValueBuf val_buf;
559
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
560
5.54k
        if (err != TxnErrorCode::TXN_OK) {
561
500
            LOG(WARNING) << "failed to get schema, err=" << err;
562
500
            return static_cast<int>(err);
563
500
        }
564
5.04k
        doris::TabletSchemaCloudPB schema;
565
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
566
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
567
0
            return -1;
568
0
        }
569
5.04k
        if (schema.index_size() > 0) {
570
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
571
4.01k
            if (schema.has_inverted_index_storage_format()) {
572
4.00k
                index_format = schema.inverted_index_storage_format();
573
4.00k
            }
574
4.01k
            res.first = index_format;
575
4.01k
            res.second.reserve(schema.index_size());
576
10.0k
            for (auto& i : schema.index()) {
577
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
578
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
579
10.0k
                }
580
10.0k
            }
581
4.01k
        }
582
5.04k
        insert(index_id, schema_version, res);
583
5.04k
        return 0;
584
5.04k
    }
585
586
    // Empty `ids` means this schema has no inverted index
587
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
588
5.04k
        if (index_info.second.empty()) {
589
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
590
1.03k
            std::lock_guard lock(mtx_);
591
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
592
4.01k
        } else {
593
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
594
4.01k
            std::lock_guard lock(mtx_);
595
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
596
4.01k
        }
597
5.04k
    }
598
599
private:
600
    std::string instance_id_;
601
    std::shared_ptr<TxnKv> txn_kv_;
602
603
    std::mutex mtx_;
604
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
605
    struct HashOfKey {
606
57.2k
        size_t operator()(const Key& key) const {
607
57.2k
            size_t seed = 0;
608
57.2k
            seed = std::hash<int64_t> {}(key.first);
609
57.2k
            seed = std::hash<int32_t> {}(key.second);
610
57.2k
            return seed;
611
57.2k
        }
612
    };
613
    // <index_id, schema_version> -> inverted_index_ids
614
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
615
    // Store <index_id, schema_version> of schema which doesn't have inverted index
616
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
617
};
618
619
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
620
                                   RecyclerThreadPoolGroup thread_pool_group,
621
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
622
187
        : txn_kv_(std::move(txn_kv)),
623
187
          instance_id_(instance.instance_id()),
624
187
          instance_info_(instance),
625
187
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
626
187
          _thread_pool_group(std::move(thread_pool_group)),
627
187
          txn_lazy_committer_(std::move(txn_lazy_committer)),
628
187
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
629
187
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
630
187
    delete_bitmap_lock_white_list_->init();
631
187
    resource_mgr_->init();
632
633
187
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
634
635
    // Since the recycler's resource manager could not be notified when instance info changes,
636
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
637
187
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
638
187
};
639
640
187
InstanceRecycler::~InstanceRecycler() = default;
641
642
155
int InstanceRecycler::init_obj_store_accessors() {
643
155
    for (const auto& obj_info : instance_info_.obj_info()) {
644
109
#ifdef UNIT_TEST
645
109
        auto accessor = std::make_shared<MockAccessor>();
646
#else
647
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
648
        if (!s3_conf) {
649
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
650
            return -1;
651
        }
652
653
        std::shared_ptr<S3Accessor> accessor;
654
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
655
        if (ret != 0) {
656
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
657
                         << " resource_id=" << obj_info.id();
658
            return ret;
659
        }
660
#endif
661
109
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
662
109
    }
663
664
155
    return 0;
665
155
}
666
667
155
int InstanceRecycler::init_storage_vault_accessors() {
668
155
    if (instance_info_.resource_ids().empty()) {
669
148
        return 0;
670
148
    }
671
672
7
    FullRangeGetOptions opts(txn_kv_);
673
7
    opts.prefetch = true;
674
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
675
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
676
677
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
678
18
        auto [k, v] = *kv;
679
18
        StorageVaultPB vault;
680
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
681
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
682
0
            return -1;
683
0
        }
684
18
        std::string recycler_storage_vault_white_list = accumulate(
685
18
                config::recycler_storage_vault_white_list.begin(),
686
18
                config::recycler_storage_vault_white_list.end(), std::string(),
687
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
687
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
688
18
        LOG_INFO("config::recycler_storage_vault_white_list")
689
18
                .tag("", recycler_storage_vault_white_list);
690
18
        if (!config::recycler_storage_vault_white_list.empty()) {
691
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
692
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
693
8
                it == config::recycler_storage_vault_white_list.end()) {
694
2
                LOG_WARNING(
695
2
                        "failed to init accessor for vault because this vault is not in "
696
2
                        "config::recycler_storage_vault_white_list. ")
697
2
                        .tag(" vault name:", vault.name())
698
2
                        .tag(" config::recycler_storage_vault_white_list:",
699
2
                             recycler_storage_vault_white_list);
700
2
                continue;
701
2
            }
702
8
        }
703
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
704
16
                                 &accessor_map_, &vault);
705
16
        if (vault.has_hdfs_info()) {
706
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
707
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
708
9
            int ret = accessor->init();
709
9
            if (ret != 0) {
710
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
711
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
712
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
713
4
                continue;
714
4
            }
715
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
716
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
717
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
718
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
719
#else
720
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
721
                       << "but HDFS storage vaults were detected";
722
#endif
723
7
        } else if (vault.has_obj_info()) {
724
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
725
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
726
7
            if (!s3_conf) {
727
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
728
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
729
1
                continue;
730
1
            }
731
732
6
            std::shared_ptr<S3Accessor> accessor;
733
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
734
6
            if (ret != 0) {
735
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
736
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
737
0
                             << " ret=" << ret
738
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
739
0
                continue;
740
0
            }
741
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
742
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
743
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
744
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
745
6
        }
746
16
    }
747
748
7
    if (!it->is_valid()) {
749
0
        LOG_WARNING("failed to get storage vault kv");
750
0
        return -1;
751
0
    }
752
753
7
    if (accessor_map_.empty()) {
754
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
755
1
        return -2;
756
1
    }
757
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
758
6
             instance_id_);
759
760
6
    return 0;
761
7
}
762
763
156
int InstanceRecycler::init() {
764
156
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
765
156
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
766
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
767
1
        return 0;
768
1
    }
769
770
155
    int ret = init_obj_store_accessors();
771
155
    if (ret != 0) {
772
0
        return ret;
773
0
    }
774
775
155
    return init_storage_vault_accessors();
776
155
}
777
778
template <typename... Func>
779
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
120
    return [funcs...]() {
781
120
        return [](std::initializer_list<int> ret_vals) {
782
120
            int i = 0;
783
140
            for (int ret : ret_vals) {
784
140
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
140
            }
788
120
            return i;
789
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
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
20
            for (int ret : ret_vals) {
784
20
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
20
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
20
            for (int ret : ret_vals) {
784
20
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
20
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
0
                    i = ret;
786
0
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
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
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
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
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
779
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
780
10
    return [funcs...]() {
781
10
        return [](std::initializer_list<int> ret_vals) {
782
10
            int i = 0;
783
10
            for (int ret : ret_vals) {
784
10
                if (ret != 0) {
785
10
                    i = ret;
786
10
                }
787
10
            }
788
10
            return i;
789
10
        }({funcs()...});
790
10
    };
791
10
}
792
793
11
int InstanceRecycler::do_recycle() {
794
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
795
11
    tablet_metrics_context_.reset();
796
11
    segment_metrics_context_.reset();
797
11
    DORIS_CLOUD_DEFER {
798
11
        tablet_metrics_context_.finish_report();
799
11
        segment_metrics_context_.finish_report();
800
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
797
11
    DORIS_CLOUD_DEFER {
798
11
        tablet_metrics_context_.finish_report();
799
11
        segment_metrics_context_.finish_report();
800
11
    };
801
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
802
1
        int res = recycle_cluster_snapshots();
803
1
        if (res != 0) {
804
0
            return -1;
805
0
        }
806
1
        return recycle_deleted_instance();
807
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
808
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
809
10
                                        fmt::format("instance id {}", instance_id_),
810
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
810
120
                                        [](int r) { return r != 0; });
811
10
        sync_executor
812
10
                .add(task_wrapper(
813
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
813
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
814
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
814
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
815
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
816
                                   // becase they may both recycle the same set of tablets
817
                        // recycle dropped table or idexes(mv, rollup)
818
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
818
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
819
                        // recycle dropped partitions
820
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
820
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
821
10
                .add(task_wrapper(
822
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
822
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
823
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
823
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
824
10
                .add(task_wrapper(
825
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
825
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
826
10
                .add(task_wrapper(
827
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
827
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
828
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
828
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
829
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
829
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
830
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
830
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
831
10
                .add(task_wrapper(
832
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
832
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
833
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
833
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
834
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
834
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
835
10
        bool finished = true;
836
10
        std::vector<int> rets = sync_executor.when_all(&finished);
837
120
        for (int ret : rets) {
838
120
            if (ret != 0) {
839
0
                return ret;
840
0
            }
841
120
        }
842
10
        return finished ? 0 : -1;
843
10
    } else {
844
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
845
0
                     << " instance_id=" << instance_id_;
846
0
        return -1;
847
0
    }
848
11
}
849
850
/**
851
* 1. delete all remote data
852
* 2. delete all kv
853
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
854
*/
855
13
int InstanceRecycler::recycle_deleted_instance() {
856
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
857
858
13
    int ret = 0;
859
13
    auto start_time = steady_clock::now();
860
13
    const auto recycle_state = instance_info_.recycle_state();
861
862
13
    if (config::retain_deleted_instance_tombstone &&
863
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
864
4
        return 0;
865
4
    }
866
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
867
9
    DORIS_CLOUD_DEFER {
868
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
869
9
        if (ret != 0) {
870
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
871
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
872
0
                         << "s, instance_id=" << instance_id_;
873
9
        } else if (recycle_state ==
874
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
875
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
876
0
                      << "s, instance_id=" << instance_id_;
877
9
        } else {
878
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
879
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
880
9
                      << "s, instance_id=" << instance_id_;
881
9
        }
882
9
    };
883
884
9
    switch (recycle_state) {
885
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
886
6
        ret = recycle_deleted_instance_data();
887
6
        break;
888
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
889
3
        ret = recycle_deleted_instance_metadata();
890
3
        break;
891
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
892
0
        ret = remove_instance_key();
893
0
        break;
894
0
    default:
895
0
        LOG_WARNING("invalid instance recycle state")
896
0
                .tag("instance_id", instance_id_)
897
0
                .tag("recycle_state", instance_info_.recycle_state());
898
0
        ret = -1;
899
0
        break;
900
9
    }
901
902
9
    return ret;
903
9
}
904
905
6
int InstanceRecycler::recycle_deleted_instance_data() {
906
6
    int ret = 0;
907
908
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
909
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
910
6
        int res = recycle_tmp_rowsets();
911
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
912
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
913
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
914
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
915
            // and cannot be recycled.
916
0
            res = recycle_tmp_rowsets();
917
0
        }
918
6
        return res;
919
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
909
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
910
6
        int res = recycle_tmp_rowsets();
911
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
912
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
913
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
914
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
915
            // and cannot be recycled.
916
0
            res = recycle_tmp_rowsets();
917
0
        }
918
6
        return res;
919
6
    };
920
921
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
922
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
923
0
        return -1;
924
0
    }
925
926
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
927
6
    if (recycle_versioned_rowsets() != 0) {
928
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
929
0
        return -1;
930
0
    }
931
932
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
933
6
    if (recycle_operation_logs() != 0) {
934
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
935
0
        return -1;
936
0
    }
937
938
    // Step 4: Check if there are still cluster snapshots
939
6
    bool has_snapshots = false;
940
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
941
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
942
0
        return -1;
943
6
    } else if (has_snapshots) {
944
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
945
1
        return 0;
946
1
    }
947
948
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
949
5
                            instance_info().snapshot_switch_status() !=
950
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
951
5
    if (snapshot_enabled) {
952
1
        bool has_unrecycled_rowsets = false;
953
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
954
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
955
0
            return -1;
956
1
        } else if (has_unrecycled_rowsets) {
957
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
958
0
                    .tag("instance_id", instance_id_);
959
0
            return ret;
960
0
        }
961
4
    } else { // delete all remote data if snapshot is disabled
962
4
        for (auto& [_, accessor] : accessor_map_) {
963
4
            if (stopped()) {
964
0
                return ret;
965
0
            }
966
967
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
968
4
            int del_ret = accessor->delete_all();
969
4
            if (del_ret == 0) {
970
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
971
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
972
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
973
                // so the recycling has been successful.
974
0
                ret = -1;
975
0
            }
976
4
        }
977
978
4
        if (ret != 0) {
979
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
980
0
            return ret;
981
0
        }
982
4
    }
983
984
5
    if (update_instance_recycle_state(
985
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
986
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
987
0
        return -1;
988
0
    }
989
990
5
    return 0;
991
5
}
992
993
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
994
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
995
7
    if (instance_info_.has_successor_instance_id() &&
996
7
        !instance_info_.successor_instance_id().empty()) {
997
4
        std::string key = instance_key(instance_info_.successor_instance_id());
998
4
        std::unique_ptr<Transaction> txn;
999
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1000
4
        if (err != TxnErrorCode::TXN_OK) {
1001
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1002
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1003
0
                         << " err=" << err;
1004
0
            return -1;
1005
0
        }
1006
1007
4
        InstanceInfoPB successor_instance;
1008
4
        std::string value;
1009
4
        err = txn->get(key, &value);
1010
4
        if (err == TxnErrorCode::TXN_OK) {
1011
3
            InstanceInfoPB successor_instance;
1012
3
            if (!successor_instance.ParseFromString(value)) {
1013
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1014
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1015
0
                return -1;
1016
0
            }
1017
3
            if (!successor_instance.has_recycle_state() ||
1018
3
                successor_instance.recycle_state() !=
1019
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1020
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1021
2
                          << " instance_id=" << instance_id_
1022
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1023
2
                          << " successor_status=" << successor_instance.status()
1024
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1025
2
                return 0;
1026
2
            }
1027
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1028
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1029
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1030
0
                         << " err=" << err;
1031
0
            return -1;
1032
0
        }
1033
4
    }
1034
1035
    // delete all kv
1036
5
    std::unique_ptr<Transaction> txn;
1037
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1038
5
    if (err != TxnErrorCode::TXN_OK) {
1039
0
        LOG(WARNING) << "failed to create txn";
1040
0
        return -1;
1041
0
    }
1042
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1043
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1044
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1045
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1046
5
    txn->remove(start_txn_key, end_txn_key);
1047
5
    std::string start_version_key = version_key_prefix(instance_id_);
1048
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1049
5
    txn->remove(start_version_key, end_version_key);
1050
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1051
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1052
5
    txn->remove(start_meta_key, end_meta_key);
1053
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1054
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1055
5
    txn->remove(start_recycle_key, end_recycle_key);
1056
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1057
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1058
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1059
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1060
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1061
5
    txn->remove(start_copy_key, end_copy_key);
1062
    // should not remove job key range, because we need to reserve job recycle kv
1063
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1064
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1065
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1066
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1067
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1068
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1069
5
    std::string start_vault_key = storage_vault_key(key_info0);
1070
5
    std::string end_vault_key = storage_vault_key(key_info1);
1071
5
    txn->remove(start_vault_key, end_vault_key);
1072
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1073
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1074
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1075
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1076
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1077
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1078
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1079
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1080
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1081
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1082
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1083
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1084
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1085
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1086
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1087
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1088
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1089
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1090
1091
    // Updating the recycle state also commits this transaction, making the metadata deletions
1092
    // and state transition atomic.
1093
5
    if (update_instance_recycle_state(
1094
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1095
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1096
0
        return -1;
1097
0
    }
1098
1099
5
    return 0;
1100
5
}
1101
1102
0
int InstanceRecycler::remove_instance_key() {
1103
0
    std::unique_ptr<Transaction> txn;
1104
0
    std::string key = instance_key(instance_info_.instance_id());
1105
0
    std::string value;
1106
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1107
0
    if (err != TxnErrorCode::TXN_OK) {
1108
0
        LOG(WARNING) << "failed to create txn";
1109
0
        return -1;
1110
0
    }
1111
1112
0
    err = txn->get(key, &value);
1113
0
    if (err != TxnErrorCode::TXN_OK) {
1114
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1115
0
                     << ", err=" << err;
1116
0
        return -1;
1117
0
    }
1118
1119
0
    InstanceInfoPB instance;
1120
0
    if (!instance.ParseFromString(value)) {
1121
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1122
0
        return -1;
1123
0
    }
1124
1125
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1126
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1127
0
                     << instance_id_ << ", status=" << instance.status();
1128
0
        return -1;
1129
0
    }
1130
1131
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1132
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1133
0
                     << instance_id_
1134
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1135
0
                     << ", expected_state="
1136
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1137
0
        return -1;
1138
0
    }
1139
1140
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1141
0
    txn->remove(key);
1142
0
    err = txn->commit();
1143
0
    if (err != TxnErrorCode::TXN_OK) {
1144
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1145
0
                     << " err=" << err;
1146
0
        return -1;
1147
0
    }
1148
0
    return 0;
1149
0
}
1150
1151
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1152
7
                                                    InstanceRecycleState target_state) {
1153
7
    std::unique_ptr<Transaction> txn;
1154
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1155
7
    if (err != TxnErrorCode::TXN_OK) {
1156
0
        LOG(WARNING) << "failed to create txn";
1157
0
        return -1;
1158
0
    }
1159
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1160
7
}
1161
1162
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1163
                                                    InstanceRecycleState target_state,
1164
12
                                                    Transaction* txn) {
1165
12
    const bool valid_transition =
1166
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1167
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1168
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1169
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1170
1171
12
    if (!valid_transition) {
1172
1
        LOG_WARNING("invalid instance recycled state transition")
1173
1
                .tag("instance_id", instance_id_)
1174
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1175
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1176
1
        return -1;
1177
1
    }
1178
1179
11
    std::string key = instance_key({instance_id_});
1180
11
    std::string value;
1181
11
    TxnErrorCode err = txn->get(key, &value);
1182
11
    if (err != TxnErrorCode::TXN_OK) {
1183
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1184
0
                .tag("instance_id", instance_id_)
1185
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1186
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1187
0
                .tag("err", err);
1188
0
        return -1;
1189
0
    }
1190
1191
11
    InstanceInfoPB instance;
1192
11
    if (!instance.ParseFromString(value)) {
1193
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1194
0
                .tag("instance_id", instance_id_)
1195
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1196
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1197
0
        return -1;
1198
0
    }
1199
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1200
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1201
0
                .tag("instance_id", instance_id_)
1202
0
                .tag("status", instance.status())
1203
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1204
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1205
0
        return -1;
1206
0
    }
1207
11
    if (instance.recycle_state() != current_state) {
1208
1
        LOG_WARNING("instance recycled state changed before update")
1209
1
                .tag("instance_id", instance_id_)
1210
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1211
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1212
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1213
1
        return -1;
1214
1
    }
1215
1216
10
    instance.set_recycle_state(target_state);
1217
10
    instance.set_recycle_state_update_time_ms(
1218
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1219
10
    if (!instance.SerializeToString(&value)) {
1220
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1221
0
                .tag("instance_id", instance_id_)
1222
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1223
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1224
0
        return -1;
1225
0
    }
1226
1227
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1228
10
    txn->put(key, value);
1229
10
    err = txn->commit();
1230
10
    if (err != TxnErrorCode::TXN_OK) {
1231
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1232
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1233
0
        return -1;
1234
0
    }
1235
1236
10
    instance_info_.Swap(&instance);
1237
10
    LOG_INFO("updated instance recycled state")
1238
10
            .tag("instance_id", instance_id_)
1239
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1240
10
    return 0;
1241
10
}
1242
1243
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1244
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1245
9
    if (exists == nullptr) {
1246
0
        return -1;
1247
0
    }
1248
9
    *exists = false;
1249
1250
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1251
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1252
9
    std::string scan_begin = begin;
1253
1254
9
    while (true) {
1255
9
        std::unique_ptr<RangeGetIterator> it_range;
1256
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1257
9
        if (get_ret < 0) {
1258
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1259
0
                    .tag("instance_id", instance_id_)
1260
0
                    .tag("tablet_id", tablet_id)
1261
0
                    .tag("ret", get_ret);
1262
0
            return -1;
1263
0
        }
1264
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1265
6
            return 0;
1266
6
        }
1267
1268
3
        std::string last_key;
1269
3
        while (it_range->has_next()) {
1270
3
            auto [k, v] = it_range->next();
1271
3
            last_key.assign(k.data(), k.size());
1272
3
            doris::RowsetMetaCloudPB rowset_meta;
1273
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1274
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1275
0
                        .tag("instance_id", instance_id_)
1276
0
                        .tag("tablet_id", tablet_id)
1277
0
                        .tag("key", hex(k));
1278
0
                continue;
1279
0
            }
1280
3
            if (stats) {
1281
3
                ++stats->rowset_scan_count;
1282
3
            }
1283
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1284
3
                *exists = true;
1285
3
                return 0;
1286
3
            }
1287
3
        }
1288
1289
0
        if (!it_range->more()) {
1290
0
            return 0;
1291
0
        }
1292
1293
        // Continue scanning from the next key to keep each transaction short.
1294
0
        scan_begin = std::move(last_key);
1295
0
        scan_begin.push_back('\x00');
1296
0
    }
1297
9
}
1298
1299
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1300
                                                          const std::string& rowset_id,
1301
                                                          int64_t txn_id, bool* recycle_exists,
1302
11
                                                          bool* tmp_exists) {
1303
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1304
0
        return -1;
1305
0
    }
1306
11
    *recycle_exists = false;
1307
11
    *tmp_exists = false;
1308
1309
11
    if (txn_id <= 0) {
1310
0
        LOG_WARNING("invalid txn id when checking recycle/tmp 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("txn_id", txn_id);
1315
0
        return -1;
1316
0
    }
1317
1318
11
    std::unique_ptr<Transaction> txn;
1319
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1320
11
    if (err != TxnErrorCode::TXN_OK) {
1321
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1322
0
                .tag("instance_id", instance_id_)
1323
0
                .tag("tablet_id", tablet_id)
1324
0
                .tag("rowset_id", rowset_id)
1325
0
                .tag("txn_id", txn_id)
1326
0
                .tag("err", err);
1327
0
        return -1;
1328
0
    }
1329
1330
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1331
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1332
11
    if (ret == TxnErrorCode::TXN_OK) {
1333
1
        *recycle_exists = true;
1334
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1335
0
        LOG_WARNING("failed to check recycle rowset existence")
1336
0
                .tag("instance_id", instance_id_)
1337
0
                .tag("tablet_id", tablet_id)
1338
0
                .tag("rowset_id", rowset_id)
1339
0
                .tag("key", hex(recycle_key))
1340
0
                .tag("err", ret);
1341
0
        return -1;
1342
0
    }
1343
1344
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1345
11
    ret = key_exists(txn.get(), tmp_key, true);
1346
11
    if (ret == TxnErrorCode::TXN_OK) {
1347
1
        *tmp_exists = true;
1348
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1349
0
        LOG_WARNING("failed to check tmp rowset existence")
1350
0
                .tag("instance_id", instance_id_)
1351
0
                .tag("tablet_id", tablet_id)
1352
0
                .tag("txn_id", txn_id)
1353
0
                .tag("key", hex(tmp_key))
1354
0
                .tag("err", ret);
1355
0
        return -1;
1356
0
    }
1357
1358
11
    return 0;
1359
11
}
1360
1361
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1362
9
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1363
9
    if (!hint.empty()) {
1364
9
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1365
9
            return {hint, it->second};
1366
9
        }
1367
9
    }
1368
1369
0
    return {"", nullptr};
1370
9
}
1371
1372
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1373
                                               const std::string& packed_file_path,
1374
3
                                               PackedFileRecycleStats* stats) {
1375
3
    bool local_changed = false;
1376
3
    int64_t left_num = 0;
1377
3
    int64_t left_bytes = 0;
1378
3
    bool all_small_files_confirmed = true;
1379
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1380
1381
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1382
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1383
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1384
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1385
14
        LOG_INFO("packed slice correction status")
1386
14
                .tag("instance_id", instance_id_)
1387
14
                .tag("packed_file_path", packed_file_path)
1388
14
                .tag("small_file_path", file.path())
1389
14
                .tag("tablet_id", tablet_id)
1390
14
                .tag("rowset_id", rowset_id)
1391
14
                .tag("txn_id", txn_id)
1392
14
                .tag("size", file.size())
1393
14
                .tag("deleted", file.deleted())
1394
14
                .tag("corrected", file.corrected())
1395
14
                .tag("confirmed_this_round", confirmed_this_round);
1396
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
1381
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1382
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1383
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1384
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1385
        LOG_INFO("packed slice correction status")
1386
14
                .tag("instance_id", instance_id_)
1387
14
                .tag("packed_file_path", packed_file_path)
1388
14
                .tag("small_file_path", file.path())
1389
14
                .tag("tablet_id", tablet_id)
1390
14
                .tag("rowset_id", rowset_id)
1391
14
                .tag("txn_id", txn_id)
1392
14
                .tag("size", file.size())
1393
14
                .tag("deleted", file.deleted())
1394
14
                .tag("corrected", file.corrected())
1395
14
                .tag("confirmed_this_round", confirmed_this_round);
1396
14
    };
1397
1398
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1399
14
        auto* small_file = packed_info->mutable_slices(i);
1400
14
        if (small_file->deleted()) {
1401
3
            log_small_file_status(*small_file, small_file->corrected());
1402
3
            continue;
1403
3
        }
1404
1405
11
        if (small_file->corrected()) {
1406
0
            left_num++;
1407
0
            left_bytes += small_file->size();
1408
0
            log_small_file_status(*small_file, true);
1409
0
            continue;
1410
0
        }
1411
1412
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1413
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1414
0
                    .tag("instance_id", instance_id_)
1415
0
                    .tag("small_file_path", small_file->path())
1416
0
                    .tag("index", i);
1417
0
            return -1;
1418
0
        }
1419
1420
11
        int64_t tablet_id = small_file->tablet_id();
1421
11
        const std::string& rowset_id = small_file->rowset_id();
1422
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1423
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1424
0
                    .tag("instance_id", instance_id_)
1425
0
                    .tag("small_file_path", small_file->path())
1426
0
                    .tag("index", i)
1427
0
                    .tag("tablet_id", tablet_id)
1428
0
                    .tag("rowset_id", rowset_id)
1429
0
                    .tag("has_txn_id", small_file->has_txn_id())
1430
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1431
0
            return -1;
1432
0
        }
1433
11
        int64_t txn_id = small_file->txn_id();
1434
11
        bool recycle_exists = false;
1435
11
        bool tmp_exists = false;
1436
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1437
11
                                                &tmp_exists) != 0) {
1438
0
            return -1;
1439
0
        }
1440
1441
11
        bool small_file_confirmed = false;
1442
11
        if (tmp_exists) {
1443
1
            left_num++;
1444
1
            left_bytes += small_file->size();
1445
1
            small_file_confirmed = true;
1446
10
        } else if (recycle_exists) {
1447
1
            left_num++;
1448
1
            left_bytes += small_file->size();
1449
            // keep small_file_confirmed=false so the packed file remains uncorrected
1450
9
        } else {
1451
9
            bool rowset_exists = false;
1452
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1453
0
                return -1;
1454
0
            }
1455
1456
9
            if (!rowset_exists) {
1457
6
                if (!small_file->deleted()) {
1458
6
                    small_file->set_deleted(true);
1459
6
                    local_changed = true;
1460
6
                }
1461
6
                if (!small_file->corrected()) {
1462
6
                    small_file->set_corrected(true);
1463
6
                    local_changed = true;
1464
6
                }
1465
6
                small_file_confirmed = true;
1466
6
            } else {
1467
3
                left_num++;
1468
3
                left_bytes += small_file->size();
1469
3
                small_file_confirmed = true;
1470
3
            }
1471
9
        }
1472
1473
11
        if (!small_file_confirmed) {
1474
1
            all_small_files_confirmed = false;
1475
1
        }
1476
1477
11
        if (small_file->corrected() != small_file_confirmed) {
1478
4
            small_file->set_corrected(small_file_confirmed);
1479
4
            local_changed = true;
1480
4
        }
1481
1482
11
        log_small_file_status(*small_file, small_file_confirmed);
1483
11
    }
1484
1485
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1486
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1487
3
        local_changed = true;
1488
3
    }
1489
3
    if (packed_info->ref_cnt() != left_num) {
1490
3
        auto old_ref_cnt = packed_info->ref_cnt();
1491
3
        packed_info->set_ref_cnt(left_num);
1492
3
        LOG_INFO("corrected packed file ref count")
1493
3
                .tag("instance_id", instance_id_)
1494
3
                .tag("resource_id", packed_info->resource_id())
1495
3
                .tag("packed_file_path", packed_file_path)
1496
3
                .tag("old_ref_cnt", old_ref_cnt)
1497
3
                .tag("new_ref_cnt", left_num);
1498
3
        local_changed = true;
1499
3
    }
1500
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1501
2
        packed_info->set_corrected(all_small_files_confirmed);
1502
2
        local_changed = true;
1503
2
    }
1504
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1505
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1506
1
        local_changed = true;
1507
1
    }
1508
1509
3
    if (changed != nullptr) {
1510
3
        *changed = local_changed;
1511
3
    }
1512
3
    return 0;
1513
3
}
1514
1515
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1516
                                                 const std::string& packed_file_path,
1517
3
                                                 PackedFileRecycleStats* stats) {
1518
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1519
3
    bool correction_ok = false;
1520
3
    cloud::PackedFileInfoPB packed_info;
1521
1522
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1523
3
        if (stopped()) {
1524
0
            LOG_WARNING("recycler stopped before processing packed file")
1525
0
                    .tag("instance_id", instance_id_)
1526
0
                    .tag("packed_file_path", packed_file_path)
1527
0
                    .tag("attempt", attempt);
1528
0
            return -1;
1529
0
        }
1530
1531
3
        std::unique_ptr<Transaction> txn;
1532
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1533
3
        if (err != TxnErrorCode::TXN_OK) {
1534
0
            LOG_WARNING("failed to create txn when processing packed file")
1535
0
                    .tag("instance_id", instance_id_)
1536
0
                    .tag("packed_file_path", packed_file_path)
1537
0
                    .tag("attempt", attempt)
1538
0
                    .tag("err", err);
1539
0
            return -1;
1540
0
        }
1541
1542
3
        std::string packed_val;
1543
3
        err = txn->get(packed_key, &packed_val);
1544
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1545
0
            return 0;
1546
0
        }
1547
3
        if (err != TxnErrorCode::TXN_OK) {
1548
0
            LOG_WARNING("failed to get packed file kv")
1549
0
                    .tag("instance_id", instance_id_)
1550
0
                    .tag("packed_file_path", packed_file_path)
1551
0
                    .tag("attempt", attempt)
1552
0
                    .tag("err", err);
1553
0
            return -1;
1554
0
        }
1555
1556
3
        if (!packed_info.ParseFromString(packed_val)) {
1557
0
            LOG_WARNING("failed to parse packed file info")
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
1564
3
        int64_t now_sec = ::time(nullptr);
1565
3
        bool corrected = packed_info.corrected();
1566
3
        bool due = config::force_immediate_recycle ||
1567
3
                   now_sec - packed_info.created_at_sec() >=
1568
3
                           config::packed_file_correction_delay_seconds;
1569
1570
3
        if (!corrected && due) {
1571
3
            bool changed = false;
1572
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1573
0
                LOG_WARNING("correct_packed_file_info failed")
1574
0
                        .tag("instance_id", instance_id_)
1575
0
                        .tag("packed_file_path", packed_file_path)
1576
0
                        .tag("attempt", attempt);
1577
0
                return -1;
1578
0
            }
1579
3
            if (changed) {
1580
3
                std::string updated;
1581
3
                if (!packed_info.SerializeToString(&updated)) {
1582
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1583
0
                            .tag("instance_id", instance_id_)
1584
0
                            .tag("packed_file_path", packed_file_path)
1585
0
                            .tag("attempt", attempt);
1586
0
                    return -1;
1587
0
                }
1588
3
                txn->put(packed_key, updated);
1589
3
                err = txn->commit();
1590
3
                if (err == TxnErrorCode::TXN_OK) {
1591
3
                    if (stats) {
1592
3
                        ++stats->num_corrected;
1593
3
                    }
1594
3
                } else {
1595
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1596
0
                        LOG_WARNING(
1597
0
                                "failed to commit correction for packed file due to conflict, "
1598
0
                                "retrying")
1599
0
                                .tag("instance_id", instance_id_)
1600
0
                                .tag("packed_file_path", packed_file_path)
1601
0
                                .tag("attempt", attempt);
1602
0
                        sleep_for_packed_file_retry();
1603
0
                        packed_info.Clear();
1604
0
                        continue;
1605
0
                    }
1606
0
                    LOG_WARNING("failed to commit correction for packed file")
1607
0
                            .tag("instance_id", instance_id_)
1608
0
                            .tag("packed_file_path", packed_file_path)
1609
0
                            .tag("attempt", attempt)
1610
0
                            .tag("err", err);
1611
0
                    return -1;
1612
0
                }
1613
3
            }
1614
3
        }
1615
1616
3
        correction_ok = true;
1617
3
        break;
1618
3
    }
1619
1620
3
    if (!correction_ok) {
1621
0
        return -1;
1622
0
    }
1623
1624
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1625
3
          packed_info.ref_cnt() == 0)) {
1626
2
        return 0;
1627
2
    }
1628
1629
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1630
0
        LOG_WARNING("packed file missing resource id when recycling")
1631
0
                .tag("instance_id", instance_id_)
1632
0
                .tag("packed_file_path", packed_file_path);
1633
0
        return -1;
1634
0
    }
1635
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1636
1
    if (!accessor) {
1637
0
        LOG_WARNING("no accessor available to delete packed file")
1638
0
                .tag("instance_id", instance_id_)
1639
0
                .tag("packed_file_path", packed_file_path)
1640
0
                .tag("resource_id", packed_info.resource_id());
1641
0
        return -1;
1642
0
    }
1643
1
    int del_ret = accessor->delete_file(packed_file_path);
1644
1
    if (del_ret != 0 && del_ret != 1) {
1645
0
        LOG_WARNING("failed to delete packed file")
1646
0
                .tag("instance_id", instance_id_)
1647
0
                .tag("packed_file_path", packed_file_path)
1648
0
                .tag("resource_id", resource_id)
1649
0
                .tag("ret", del_ret);
1650
0
        return -1;
1651
0
    }
1652
1
    if (del_ret == 1) {
1653
0
        LOG_INFO("packed file already removed")
1654
0
                .tag("instance_id", instance_id_)
1655
0
                .tag("packed_file_path", packed_file_path)
1656
0
                .tag("resource_id", resource_id);
1657
1
    } else {
1658
1
        LOG_INFO("deleted packed file")
1659
1
                .tag("instance_id", instance_id_)
1660
1
                .tag("packed_file_path", packed_file_path)
1661
1
                .tag("resource_id", resource_id);
1662
1
    }
1663
1664
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1665
1
        std::unique_ptr<Transaction> del_txn;
1666
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1667
1
        if (err != TxnErrorCode::TXN_OK) {
1668
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1669
0
                    .tag("instance_id", instance_id_)
1670
0
                    .tag("packed_file_path", packed_file_path)
1671
0
                    .tag("del_attempt", del_attempt)
1672
0
                    .tag("err", err);
1673
0
            return -1;
1674
0
        }
1675
1676
1
        std::string latest_val;
1677
1
        err = del_txn->get(packed_key, &latest_val);
1678
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1679
0
            return 0;
1680
0
        }
1681
1
        if (err != TxnErrorCode::TXN_OK) {
1682
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1683
0
                    .tag("instance_id", instance_id_)
1684
0
                    .tag("packed_file_path", packed_file_path)
1685
0
                    .tag("del_attempt", del_attempt)
1686
0
                    .tag("err", err);
1687
0
            return -1;
1688
0
        }
1689
1690
1
        cloud::PackedFileInfoPB latest_info;
1691
1
        if (!latest_info.ParseFromString(latest_val)) {
1692
0
            LOG_WARNING("failed to parse packed file info before removal")
1693
0
                    .tag("instance_id", instance_id_)
1694
0
                    .tag("packed_file_path", packed_file_path)
1695
0
                    .tag("del_attempt", del_attempt);
1696
0
            return -1;
1697
0
        }
1698
1699
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1700
1
              latest_info.ref_cnt() == 0)) {
1701
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1702
0
                    .tag("instance_id", instance_id_)
1703
0
                    .tag("packed_file_path", packed_file_path)
1704
0
                    .tag("del_attempt", del_attempt);
1705
0
            return 0;
1706
0
        }
1707
1708
1
        del_txn->remove(packed_key);
1709
1
        err = del_txn->commit();
1710
1
        if (err == TxnErrorCode::TXN_OK) {
1711
1
            if (stats) {
1712
1
                ++stats->num_deleted;
1713
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1714
1
                                        static_cast<int64_t>(latest_val.size());
1715
1
                if (del_ret == 0 || del_ret == 1) {
1716
1
                    ++stats->num_object_deleted;
1717
1
                    int64_t object_size = latest_info.total_slice_bytes();
1718
1
                    if (object_size <= 0) {
1719
0
                        object_size = packed_info.total_slice_bytes();
1720
0
                    }
1721
1
                    stats->bytes_object_deleted += object_size;
1722
1
                }
1723
1
            }
1724
1
            LOG_INFO("removed packed file metadata")
1725
1
                    .tag("instance_id", instance_id_)
1726
1
                    .tag("packed_file_path", packed_file_path);
1727
1
            return 0;
1728
1
        }
1729
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1730
0
            if (del_attempt >= max_retry_times) {
1731
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1732
0
                        .tag("instance_id", instance_id_)
1733
0
                        .tag("packed_file_path", packed_file_path)
1734
0
                        .tag("del_attempt", del_attempt);
1735
0
                return -1;
1736
0
            }
1737
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1738
0
                    .tag("instance_id", instance_id_)
1739
0
                    .tag("packed_file_path", packed_file_path)
1740
0
                    .tag("del_attempt", del_attempt);
1741
0
            sleep_for_packed_file_retry();
1742
0
            continue;
1743
0
        }
1744
0
        LOG_WARNING("failed to remove packed file kv")
1745
0
                .tag("instance_id", instance_id_)
1746
0
                .tag("packed_file_path", packed_file_path)
1747
0
                .tag("del_attempt", del_attempt)
1748
0
                .tag("err", err);
1749
0
        return -1;
1750
0
    }
1751
1752
0
    return -1;
1753
1
}
1754
1755
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1756
4
                                            PackedFileRecycleStats* stats, int* ret) {
1757
4
    if (stats) {
1758
4
        ++stats->num_scanned;
1759
4
    }
1760
4
    std::string packed_file_path;
1761
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1762
0
        LOG_WARNING("failed to decode packed file key")
1763
0
                .tag("instance_id", instance_id_)
1764
0
                .tag("key", hex(key));
1765
0
        if (stats) {
1766
0
            ++stats->num_failed;
1767
0
        }
1768
0
        if (ret) {
1769
0
            *ret = -1;
1770
0
        }
1771
0
        return 0;
1772
0
    }
1773
1774
4
    cloud::PackedFileInfoPB packed_info;
1775
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1776
0
        LOG_WARNING("failed to parse packed file info from scan")
1777
0
                .tag("instance_id", instance_id_)
1778
0
                .tag("packed_file_path", packed_file_path);
1779
0
        if (stats) {
1780
0
            ++stats->num_failed;
1781
0
        }
1782
0
        if (ret) {
1783
0
            *ret = -1;
1784
0
        }
1785
0
        return 0;
1786
0
    }
1787
1788
4
    const int64_t now_sec = ::time(nullptr);
1789
4
    const bool due =
1790
4
            config::force_immediate_recycle ||
1791
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1792
4
    const bool need_correction = !packed_info.corrected() && due;
1793
4
    const bool need_recycle =
1794
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1795
4
    if (!need_correction && !need_recycle) {
1796
1
        return 0;
1797
1
    }
1798
1799
3
    std::string packed_key(key);
1800
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1801
3
    if (process_ret != 0) {
1802
0
        if (stats) {
1803
0
            ++stats->num_failed;
1804
0
        }
1805
0
        if (ret) {
1806
0
            *ret = -1;
1807
0
        }
1808
0
    }
1809
3
    return 0;
1810
4
}
1811
1812
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1813
6.34k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1814
6.34k
    if (config::force_immediate_recycle) {
1815
295
        return 0L;
1816
295
    }
1817
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1818
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1819
6.05k
    int64_t retention_seconds = config::retention_seconds;
1820
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1821
4.75k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1822
4.75k
    }
1823
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1824
6.05k
    if (*earlest_ts > final_expiration) {
1825
17
        *earlest_ts = final_expiration;
1826
17
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1827
17
    }
1828
6.05k
    return final_expiration;
1829
6.34k
}
1830
1831
int64_t calculate_partition_expired_time(
1832
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1833
13
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1834
13
    if (config::force_immediate_recycle) {
1835
7
        return 0L;
1836
7
    }
1837
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1838
6
                                                            : partition_meta_pb.creation_time();
1839
6
    int64_t retention_seconds = config::retention_seconds;
1840
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1841
6
        retention_seconds =
1842
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1843
6
    }
1844
6
    int64_t final_expiration = expiration + retention_seconds;
1845
6
    if (*earlest_ts > final_expiration) {
1846
2
        *earlest_ts = final_expiration;
1847
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1848
2
    }
1849
6
    return final_expiration;
1850
13
}
1851
1852
int64_t calculate_index_expired_time(const std::string& instance_id_,
1853
                                     const RecycleIndexPB& index_meta_pb,
1854
19
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1855
19
    if (config::force_immediate_recycle) {
1856
13
        return 0L;
1857
13
    }
1858
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1859
6
                                                        : index_meta_pb.creation_time();
1860
6
    int64_t retention_seconds = config::retention_seconds;
1861
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1862
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1863
6
    }
1864
6
    int64_t final_expiration = expiration + retention_seconds;
1865
6
    if (*earlest_ts > final_expiration) {
1866
2
        *earlest_ts = final_expiration;
1867
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1868
2
    }
1869
6
    return final_expiration;
1870
19
}
1871
1872
int64_t calculate_tmp_rowset_expired_time(
1873
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1874
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1875
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1876
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1877
    //  duration or timeout always < `retention_time` in practice.
1878
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1879
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1880
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1881
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1882
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1883
53.2k
    if (*earlest_ts > final_expiration) {
1884
20
        *earlest_ts = final_expiration;
1885
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1886
20
    }
1887
53.2k
    return final_expiration;
1888
53.2k
}
1889
1890
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1891
30.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1892
30.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1893
30.0k
    if (*earlest_ts > final_expiration / 1000) {
1894
8
        *earlest_ts = final_expiration / 1000;
1895
8
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1896
8
    }
1897
30.0k
    return final_expiration;
1898
30.0k
}
1899
1900
int64_t calculate_restore_job_expired_time(
1901
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1902
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1903
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1904
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1905
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1906
        // final state, recycle immediately
1907
41
        return 0L;
1908
41
    }
1909
    // not final state, wait much longer than the FE's timeout(1 day)
1910
0
    int64_t last_modified_s =
1911
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1912
0
    int64_t expiration = restore_job.expired_at_s() > 0
1913
0
                                 ? last_modified_s + restore_job.expired_at_s()
1914
0
                                 : last_modified_s;
1915
0
    int64_t final_expiration = expiration + config::retention_seconds;
1916
0
    if (*earlest_ts > final_expiration) {
1917
0
        *earlest_ts = final_expiration;
1918
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1919
0
    }
1920
0
    return final_expiration;
1921
41
}
1922
1923
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1924
537
    AbortTxnRequest req;
1925
537
    TxnInfoPB txn_info;
1926
537
    MetaServiceCode code = MetaServiceCode::OK;
1927
537
    std::string msg;
1928
537
    std::stringstream ss;
1929
537
    std::unique_ptr<Transaction> txn;
1930
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1931
537
    if (err != TxnErrorCode::TXN_OK) {
1932
0
        LOG_WARNING("failed to create txn").tag("err", err);
1933
0
        return -1;
1934
0
    }
1935
1936
    // get txn index
1937
537
    TxnIndexPB txn_idx_pb;
1938
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1939
537
    std::string index_val;
1940
537
    err = txn->get(index_key, &index_val);
1941
537
    if (err != TxnErrorCode::TXN_OK) {
1942
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1943
            // maybe recycled
1944
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1945
2
                    .tag("key", hex(index_key))
1946
2
                    .tag("txn_id", txn_id);
1947
2
            return 0;
1948
2
        }
1949
0
        LOG_WARNING("failed to get txn index")
1950
0
                .tag("err", err)
1951
0
                .tag("key", hex(index_key))
1952
0
                .tag("txn_id", txn_id);
1953
0
        return -1;
1954
2
    }
1955
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
1956
1
        LOG_WARNING("failed to parse txn index")
1957
1
                .tag("err", err)
1958
1
                .tag("key", hex(index_key))
1959
1
                .tag("txn_id", txn_id);
1960
1
        return -1;
1961
1
    }
1962
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1963
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
1964
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1965
3
                .tag("key", hex(index_key))
1966
3
                .tag("txn_id", txn_id)
1967
3
                .tag("db_id",
1968
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1969
3
        return -1;
1970
3
    }
1971
1972
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1973
531
    const int64_t owner_txn_id =
1974
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1975
531
    if (owner_txn_id <= 0) {
1976
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
1977
1
                .tag("key", hex(index_key))
1978
1
                .tag("txn_id", txn_id)
1979
1
                .tag("owner_txn_id", owner_txn_id);
1980
1
        return -1;
1981
1
    }
1982
1983
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
1984
530
    std::string info_val;
1985
530
    err = txn->get(info_key, &info_val);
1986
530
    if (err != TxnErrorCode::TXN_OK) {
1987
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1988
            // maybe recycled
1989
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
1990
1
                        owner_txn_id, instance_id_)
1991
1
                    .tag("key", hex(info_key))
1992
1
                    .tag("txn_id", txn_id)
1993
1
                    .tag("owner_txn_id", owner_txn_id);
1994
1
            return 0;
1995
1
        }
1996
0
        LOG_WARNING("failed to get txn info")
1997
0
                .tag("err", err)
1998
0
                .tag("key", hex(info_key))
1999
0
                .tag("txn_id", txn_id)
2000
0
                .tag("owner_txn_id", owner_txn_id);
2001
0
        return -1;
2002
1
    }
2003
529
    if (!txn_info.ParseFromString(info_val)) {
2004
1
        LOG_WARNING("failed to parse txn info")
2005
1
                .tag("err", err)
2006
1
                .tag("key", hex(info_key))
2007
1
                .tag("txn_id", txn_id)
2008
1
                .tag("owner_txn_id", owner_txn_id);
2009
1
        return -1;
2010
1
    }
2011
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2012
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2013
1
                .tag("key", hex(info_key))
2014
1
                .tag("txn_id", txn_id)
2015
1
                .tag("owner_txn_id", owner_txn_id)
2016
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2017
1
        return -1;
2018
1
    }
2019
2020
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2021
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2022
514
                .tag("key", hex(info_key))
2023
514
                .tag("txn_id", txn_id)
2024
514
                .tag("owner_txn_id", owner_txn_id);
2025
514
        return 0;
2026
514
    }
2027
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2028
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2029
4
                    owner_txn_id, txn_info.status())
2030
4
                .tag("key", hex(info_key))
2031
4
                .tag("txn_id", txn_id)
2032
4
                .tag("owner_txn_id", owner_txn_id);
2033
4
        return -1;
2034
4
    }
2035
2036
9
    req.set_txn_id(owner_txn_id);
2037
9
    req.set_db_id(db_id);
2038
2039
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2040
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2041
9
                 << " txn_info=" << txn_info.ShortDebugString();
2042
2043
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2044
9
    if (code != MetaServiceCode::OK) {
2045
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2046
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2047
0
                     << " code=" << code << " msg=" << msg;
2048
0
        return -1;
2049
0
    }
2050
2051
9
    err = txn->commit();
2052
9
    if (err != TxnErrorCode::TXN_OK) {
2053
0
        code = cast_as<ErrCategory::COMMIT>(err);
2054
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2055
0
        msg = ss.str();
2056
0
        return -1;
2057
0
    }
2058
2059
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2060
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2061
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2062
9
                 << " msg=" << msg;
2063
2064
9
    return 0;
2065
9
}
2066
2067
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2068
11
                                                   const std::string& job_id) {
2069
11
    FinishTabletJobRequest req;
2070
11
    FinishTabletJobResponse res;
2071
11
    req.set_action(FinishTabletJobRequest::ABORT);
2072
11
    MetaServiceCode code = MetaServiceCode::OK;
2073
11
    std::string msg;
2074
11
    std::stringstream ss;
2075
2076
11
    TabletIndexPB tablet_idx;
2077
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2078
11
    if (ret == 1) {
2079
        // tablet maybe recycled, directly return 0
2080
1
        return 0;
2081
10
    } else if (ret != 0) {
2082
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2083
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2084
0
        return ret;
2085
0
    }
2086
2087
10
    std::unique_ptr<Transaction> txn;
2088
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2089
10
    if (err != TxnErrorCode::TXN_OK) {
2090
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2091
0
        return -1;
2092
0
    }
2093
2094
10
    std::string job_key =
2095
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2096
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2097
10
    std::string job_val;
2098
10
    err = txn->get(job_key, &job_val);
2099
10
    if (err != TxnErrorCode::TXN_OK) {
2100
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2101
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2102
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2103
            // A previous recycler round may have aborted the job. The caller must recheck the
2104
            // recycle key before deleting object data.
2105
1
            return 0;
2106
1
        }
2107
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2108
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2109
0
                     << " key=" << hex(job_key);
2110
0
        return -1;
2111
1
    }
2112
2113
9
    TabletJobInfoPB job_pb;
2114
9
    if (!job_pb.ParseFromString(job_val)) {
2115
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2116
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2117
0
        return -1;
2118
0
    }
2119
2120
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2121
9
    for (const auto& compaction : job_pb.compaction()) {
2122
9
        if (compaction.id() == job_id) {
2123
5
            matched_compaction = &compaction;
2124
5
            break;
2125
5
        }
2126
9
    }
2127
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2128
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2129
9
        job_pb.schema_change().id() == job_id) {
2130
3
        matched_schema_change = &job_pb.schema_change();
2131
3
    }
2132
2133
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2134
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2135
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2136
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2137
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2138
        // both the base and mirrored schema-change records.
2139
8
        if (matched_compaction != nullptr) {
2140
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2141
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2142
5
        } else {
2143
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2144
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2145
3
        }
2146
8
        req.set_action(FinishTabletJobRequest::ABORT);
2147
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2148
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2149
8
                           ss);
2150
8
        if (code != MetaServiceCode::OK) {
2151
            // These two codes mean that the job cannot be aborted anymore.
2152
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2153
            // There is no running job that still owns the PREPARE rowset, so the caller may
2154
            // recheck the recycle key.
2155
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2156
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2157
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2158
            // job again and continue recycling only when the target job id no longer exists.
2159
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2160
0
                std::unique_ptr<Transaction> check_txn;
2161
0
                err = txn_kv_->create_txn(&check_txn);
2162
0
                if (err != TxnErrorCode::TXN_OK) {
2163
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2164
0
                                 << instance_id_ << " err=" << err;
2165
0
                    return -1;
2166
0
                }
2167
2168
0
                const auto& idx = req.job().idx();
2169
0
                std::string current_job_key =
2170
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2171
0
                                        idx.partition_id(), idx.tablet_id()});
2172
0
                std::string current_job_val;
2173
0
                err = check_txn->get(current_job_key, &current_job_val);
2174
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2175
0
                    no_job_to_abort = true;
2176
0
                } else if (err != TxnErrorCode::TXN_OK) {
2177
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2178
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2179
0
                                 << " key=" << hex(current_job_key);
2180
0
                    return -1;
2181
0
                } else {
2182
0
                    TabletJobInfoPB current_job;
2183
0
                    if (!current_job.ParseFromString(current_job_val)) {
2184
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2185
0
                                     << " tablet_id=" << idx.tablet_id()
2186
0
                                     << " key=" << hex(current_job_key);
2187
0
                        return -1;
2188
0
                    }
2189
0
                    if (matched_compaction != nullptr) {
2190
0
                        no_job_to_abort = true;
2191
0
                        for (const auto& compaction : current_job.compaction()) {
2192
0
                            if (compaction.id() == job_id) {
2193
0
                                no_job_to_abort = false;
2194
0
                                break;
2195
0
                            }
2196
0
                        }
2197
0
                    } else {
2198
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2199
0
                                          current_job.schema_change().id() != job_id;
2200
0
                    }
2201
0
                }
2202
0
            }
2203
0
            if (no_job_to_abort) {
2204
0
                return 0;
2205
0
            }
2206
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2207
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2208
0
                         << " msg=" << msg;
2209
0
            return -1;
2210
0
        }
2211
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2212
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2213
8
                     << " code=" << code << " msg=" << msg;
2214
8
    } else {
2215
        // clang-format off
2216
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2217
1
                  << ", instance_id=" << instance_id_ 
2218
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2219
1
                  << ", job_id=" << job_id
2220
1
                  << ", rowset_id=" << rowset_id;
2221
        // clang-format on
2222
1
    }
2223
2224
9
    return 0;
2225
9
}
2226
2227
template <typename T>
2228
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
13
        return rowset_meta_pb.mutable_rowset_meta();
2231
13
    } else {
2232
9
        return &rowset_meta_pb;
2233
9
    }
2234
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2228
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
13
        return rowset_meta_pb.mutable_rowset_meta();
2231
    } else {
2232
        return &rowset_meta_pb;
2233
    }
2234
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2228
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2229
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2230
        return rowset_meta_pb.mutable_rowset_meta();
2231
9
    } else {
2232
9
        return &rowset_meta_pb;
2233
9
    }
2234
9
}
2235
2236
template <typename T>
2237
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
833
        return rowset_meta_pb.rowset_meta();
2240
833
    } else {
2241
799
        return rowset_meta_pb;
2242
799
    }
2243
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2237
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
833
        return rowset_meta_pb.rowset_meta();
2240
    } else {
2241
        return rowset_meta_pb;
2242
    }
2243
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2237
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2238
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2239
        return rowset_meta_pb.rowset_meta();
2240
799
    } else {
2241
799
        return rowset_meta_pb;
2242
799
    }
2243
799
}
2244
2245
template <typename T>
2246
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2247
1.07k
        const T& rowset_meta_pb) {
2248
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return std::nullopt;
2251
0
        }
2252
545
    }
2253
2254
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
1.07k
    RelatedTxnOrJobAbortTask task;
2256
1.07k
    task.tablet_id = rs_meta.tablet_id();
2257
1.07k
    task.start_version = rs_meta.start_version();
2258
1.07k
    task.end_version = rs_meta.end_version();
2259
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2260
1.07k
    if (rs_meta.has_load_id()) {
2261
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
1.05k
        task.txn_id = rs_meta.txn_id();
2263
1.05k
        return task;
2264
1.05k
    }
2265
19
    if (rs_meta.has_job_id()) {
2266
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
14
        task.job_id = rs_meta.job_id();
2268
14
        return task;
2269
14
    }
2270
5
    return std::nullopt;
2271
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2247
545
        const T& rowset_meta_pb) {
2248
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
0
            return std::nullopt;
2251
0
        }
2252
545
    }
2253
2254
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
545
    RelatedTxnOrJobAbortTask task;
2256
545
    task.tablet_id = rs_meta.tablet_id();
2257
545
    task.start_version = rs_meta.start_version();
2258
545
    task.end_version = rs_meta.end_version();
2259
545
    task.rowset_id = rs_meta.rowset_id_v2();
2260
545
    if (rs_meta.has_load_id()) {
2261
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
534
        task.txn_id = rs_meta.txn_id();
2263
534
        return task;
2264
534
    }
2265
11
    if (rs_meta.has_job_id()) {
2266
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
10
        task.job_id = rs_meta.job_id();
2268
10
        return task;
2269
10
    }
2270
1
    return std::nullopt;
2271
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2247
526
        const T& rowset_meta_pb) {
2248
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2249
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2250
            return std::nullopt;
2251
        }
2252
    }
2253
2254
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2255
526
    RelatedTxnOrJobAbortTask task;
2256
526
    task.tablet_id = rs_meta.tablet_id();
2257
526
    task.start_version = rs_meta.start_version();
2258
526
    task.end_version = rs_meta.end_version();
2259
526
    task.rowset_id = rs_meta.rowset_id_v2();
2260
526
    if (rs_meta.has_load_id()) {
2261
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2262
518
        task.txn_id = rs_meta.txn_id();
2263
518
        return task;
2264
518
    }
2265
8
    if (rs_meta.has_job_id()) {
2266
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2267
4
        task.job_id = rs_meta.job_id();
2268
4
        return task;
2269
4
    }
2270
4
    return std::nullopt;
2271
8
}
2272
2273
template <typename T>
2274
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2275
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
0
            return false;
2279
0
        }
2280
268
    }
2281
2282
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
523
    }
2290
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2275
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
0
            return false;
2279
0
        }
2280
268
    }
2281
2282
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
264
    }
2290
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2275
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2276
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2277
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2278
            return false;
2279
        }
2280
    }
2281
2282
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2283
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2284
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2285
0
        return false;
2286
0
    }
2287
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2288
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2289
259
    }
2290
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2291
261
}
2292
2293
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2294
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2295
71
}
2296
2297
template <typename T>
2298
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2299
18
                                   const std::vector<std::string>& keys) {
2300
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
18
        std::unique_ptr<Transaction> txn;
2304
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
18
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
18
        std::vector<std::optional<std::string>> values;
2310
18
        err = txn->batch_get(&values, batch_keys);
2311
18
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
18
        DCHECK_EQ(values.size(), batch_keys.size());
2317
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
22
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
22
            const auto& key = batch_keys[i];
2323
22
            auto val = values[i].value();
2324
22
            T rowset_meta_pb;
2325
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
13
            }
2338
22
            val.clear();
2339
22
            rowset_meta_pb.SerializeToString(&val);
2340
22
            txn->put(key, val);
2341
22
        }
2342
18
        err = txn->commit();
2343
18
        if (err != TxnErrorCode::TXN_OK) {
2344
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
1
            return -1;
2346
1
        }
2347
18
    }
2348
2349
17
    return 0;
2350
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2299
11
                                   const std::vector<std::string>& keys) {
2300
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
11
        std::unique_ptr<Transaction> txn;
2304
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
11
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
11
        std::vector<std::optional<std::string>> values;
2310
11
        err = txn->batch_get(&values, batch_keys);
2311
11
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
11
        DCHECK_EQ(values.size(), batch_keys.size());
2317
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
13
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
13
            const auto& key = batch_keys[i];
2323
13
            auto val = values[i].value();
2324
13
            T rowset_meta_pb;
2325
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
13
            }
2338
13
            val.clear();
2339
13
            rowset_meta_pb.SerializeToString(&val);
2340
13
            txn->put(key, val);
2341
13
        }
2342
11
        err = txn->commit();
2343
11
        if (err != TxnErrorCode::TXN_OK) {
2344
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
1
            return -1;
2346
1
        }
2347
11
    }
2348
2349
10
    return 0;
2350
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2299
7
                                   const std::vector<std::string>& keys) {
2300
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2301
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2302
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2303
7
        std::unique_ptr<Transaction> txn;
2304
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2305
7
        if (err != TxnErrorCode::TXN_OK) {
2306
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2307
0
            return -1;
2308
0
        }
2309
7
        std::vector<std::optional<std::string>> values;
2310
7
        err = txn->batch_get(&values, batch_keys);
2311
7
        if (err != TxnErrorCode::TXN_OK) {
2312
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2313
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2314
0
            return -1;
2315
0
        }
2316
7
        DCHECK_EQ(values.size(), batch_keys.size());
2317
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2318
9
            if (!values[i].has_value()) {
2319
                // has already been removed by commit_rowset
2320
0
                continue;
2321
0
            }
2322
9
            const auto& key = batch_keys[i];
2323
9
            auto val = values[i].value();
2324
9
            T rowset_meta_pb;
2325
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2326
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2327
0
                             << " key=" << hex(key);
2328
0
                return -1;
2329
0
            }
2330
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2331
0
                continue;
2332
0
            }
2333
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2334
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2335
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2336
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2337
            }
2338
9
            val.clear();
2339
9
            rowset_meta_pb.SerializeToString(&val);
2340
9
            txn->put(key, val);
2341
9
        }
2342
7
        err = txn->commit();
2343
7
        if (err != TxnErrorCode::TXN_OK) {
2344
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2345
0
            return -1;
2346
0
        }
2347
7
    }
2348
2349
7
    return 0;
2350
7
}
2351
2352
template <typename T>
2353
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2354
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
1
        }
2360
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2355
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
1
        }
2360
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2355
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
0
        }
2360
7
    });
2361
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2354
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
11
        }
2360
11
    });
2361
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2354
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2355
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2356
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2357
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2358
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2359
7
        }
2360
7
    });
2361
7
}
2362
2363
template <typename T>
2364
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2365
                                 const std::vector<std::string>& keys,
2366
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
22
        std::unique_ptr<Transaction> txn;
2371
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
22
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
22
        std::vector<std::optional<std::string>> values;
2377
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
22
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
22
        DCHECK_EQ(values.size(), batch_keys.size());
2384
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
533
            const std::string& key = batch_keys[idx];
2386
533
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
533
            T rowset_meta_pb;
2391
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
533
                abort_task.has_value()) {
2398
533
                abort_task->key = key;
2399
533
                abort_tasks->emplace_back(std::move(*abort_task));
2400
533
            }
2401
533
        }
2402
22
    }
2403
20
    return 0;
2404
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2366
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
16
        std::unique_ptr<Transaction> txn;
2371
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
16
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
16
        std::vector<std::optional<std::string>> values;
2377
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
16
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
16
        DCHECK_EQ(values.size(), batch_keys.size());
2384
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
272
            const std::string& key = batch_keys[idx];
2386
272
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
272
            T rowset_meta_pb;
2391
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
272
                abort_task.has_value()) {
2398
272
                abort_task->key = key;
2399
272
                abort_tasks->emplace_back(std::move(*abort_task));
2400
272
            }
2401
272
        }
2402
16
    }
2403
15
    return 0;
2404
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2366
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2367
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2368
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2369
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2370
6
        std::unique_ptr<Transaction> txn;
2371
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2372
6
        if (err != TxnErrorCode::TXN_OK) {
2373
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2374
0
            return -1;
2375
0
        }
2376
6
        std::vector<std::optional<std::string>> values;
2377
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2378
6
        if (err != TxnErrorCode::TXN_OK) {
2379
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2380
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2381
0
            return -1;
2382
0
        }
2383
6
        DCHECK_EQ(values.size(), batch_keys.size());
2384
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2385
261
            const std::string& key = batch_keys[idx];
2386
261
            if (!values[idx].has_value()) {
2387
                // has already been removed
2388
0
                continue;
2389
0
            }
2390
261
            T rowset_meta_pb;
2391
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2392
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2393
0
                             << " key=" << hex(key);
2394
0
                return -1;
2395
0
            }
2396
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2397
261
                abort_task.has_value()) {
2398
261
                abort_task->key = key;
2399
261
                abort_tasks->emplace_back(std::move(*abort_task));
2400
261
            }
2401
261
        }
2402
6
    }
2403
5
    return 0;
2404
5
}
2405
2406
template <typename T>
2407
int batch_recheck_rowsets_after_abort(
2408
        TxnKv* txn_kv, const std::string& instance_id,
2409
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2410
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
18
    int ret = 0;
2412
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
20
        std::vector<std::string> batch_keys;
2415
20
        batch_keys.reserve(limit - offset);
2416
550
        for (size_t idx = offset; idx < limit; ++idx) {
2417
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
530
        }
2419
2420
20
        std::unique_ptr<Transaction> txn;
2421
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
20
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
20
        std::vector<std::optional<std::string>> values;
2430
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
20
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
20
        DCHECK_EQ(values.size(), batch_keys.size());
2438
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
20
                                 &batch_size);
2441
2442
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
530
            if (!values[idx].has_value()) {
2445
1
                continue;
2446
1
            }
2447
2448
529
            T rowset_meta_pb;
2449
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
1
                             << instance_id << " key=" << hex(key);
2464
1
                continue;
2465
1
            }
2466
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
528
        }
2468
20
    }
2469
18
    return ret;
2470
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2410
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
13
    int ret = 0;
2412
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
14
        std::vector<std::string> batch_keys;
2415
14
        batch_keys.reserve(limit - offset);
2416
283
        for (size_t idx = offset; idx < limit; ++idx) {
2417
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
269
        }
2419
2420
14
        std::unique_ptr<Transaction> txn;
2421
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
14
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
14
        std::vector<std::optional<std::string>> values;
2430
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
14
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
14
        DCHECK_EQ(values.size(), batch_keys.size());
2438
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
14
                                 &batch_size);
2441
2442
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
269
            if (!values[idx].has_value()) {
2445
1
                continue;
2446
1
            }
2447
2448
268
            T rowset_meta_pb;
2449
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
1
                             << instance_id << " key=" << hex(key);
2464
1
                continue;
2465
1
            }
2466
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
267
        }
2468
14
    }
2469
13
    return ret;
2470
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2410
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2411
5
    int ret = 0;
2412
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2413
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2414
6
        std::vector<std::string> batch_keys;
2415
6
        batch_keys.reserve(limit - offset);
2416
267
        for (size_t idx = offset; idx < limit; ++idx) {
2417
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2418
261
        }
2419
2420
6
        std::unique_ptr<Transaction> txn;
2421
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2422
6
        if (err != TxnErrorCode::TXN_OK) {
2423
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2424
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2425
0
            ret = -1;
2426
0
            continue;
2427
0
        }
2428
2429
6
        std::vector<std::optional<std::string>> values;
2430
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2431
6
        if (err != TxnErrorCode::TXN_OK) {
2432
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2433
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2434
0
            ret = -1;
2435
0
            continue;
2436
0
        }
2437
6
        DCHECK_EQ(values.size(), batch_keys.size());
2438
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2439
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2440
6
                                 &batch_size);
2441
2442
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2443
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2444
261
            if (!values[idx].has_value()) {
2445
0
                continue;
2446
0
            }
2447
2448
261
            T rowset_meta_pb;
2449
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2450
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2451
0
                             << instance_id << " key=" << hex(key);
2452
0
                ret = -1;
2453
0
                continue;
2454
0
            }
2455
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2456
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2457
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2458
0
                             << instance_id << " key=" << hex(key);
2459
0
                continue;
2460
0
            }
2461
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2462
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2463
0
                             << instance_id << " key=" << hex(key);
2464
0
                continue;
2465
0
            }
2466
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2467
261
        }
2468
6
    }
2469
5
    return ret;
2470
5
}
2471
2472
template <typename T>
2473
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2474
        const std::vector<std::string>& keys,
2475
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
20
    int ret = 0;
2483
533
    for (const auto& abort_task : abort_tasks) {
2484
533
        int abort_ret = 0;
2485
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
526
        } else {
2488
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
7
                                                     abort_task.job_id);
2490
7
        }
2491
533
        if (abort_ret != 0) {
2492
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
3
            ret = abort_ret;
2496
3
            continue;
2497
3
        }
2498
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
530
    }
2500
20
    return ret;
2501
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2475
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
15
    int ret = 0;
2483
272
    for (const auto& abort_task : abort_tasks) {
2484
272
        int abort_ret = 0;
2485
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
267
        } else {
2488
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
5
                                                     abort_task.job_id);
2490
5
        }
2491
272
        if (abort_ret != 0) {
2492
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
3
            ret = abort_ret;
2496
3
            continue;
2497
3
        }
2498
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
269
    }
2500
15
    return ret;
2501
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2475
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2476
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2477
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2478
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2479
0
        return -1;
2480
0
    }
2481
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2482
5
    int ret = 0;
2483
261
    for (const auto& abort_task : abort_tasks) {
2484
261
        int abort_ret = 0;
2485
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2486
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2487
259
        } else {
2488
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2489
2
                                                     abort_task.job_id);
2490
2
        }
2491
261
        if (abort_ret != 0) {
2492
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2493
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2494
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2495
0
            ret = abort_ret;
2496
0
            continue;
2497
0
        }
2498
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2499
261
    }
2500
5
    return ret;
2501
5
}
2502
2503
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2504
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2505
15
        std::atomic_long* num_recycled) {
2506
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2507
15
                                  num_recycled]() mutable {
2508
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
15
                                                                            keys_to_recheck);
2511
15
        if (abort_ret != 0) {
2512
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
2
                            "instance_id="
2514
2
                         << instance_id_;
2515
2
        }
2516
15
        if (keys_to_recheck.empty()) {
2517
2
            return;
2518
2
        }
2519
2520
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
13
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
267
            const auto& current_meta = current_rowset.rowset_meta();
2529
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
267
                                   current_meta.rowset_id_v2()) != 0) {
2531
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
1
                continue;
2533
1
            }
2534
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2535
266
                                                   current_meta.tablet_id(),
2536
266
                                                   current_meta.rowset_id_v2()) != 0) {
2537
0
                continue;
2538
0
            }
2539
266
            std::vector<std::string> keys {key};
2540
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2541
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2542
0
                continue;
2543
0
            }
2544
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2545
266
        }
2546
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2507
2
                                  num_recycled]() mutable {
2508
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
2
                                                                            keys_to_recheck);
2511
2
        if (abort_ret != 0) {
2512
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
0
                            "instance_id="
2514
0
                         << instance_id_;
2515
0
        }
2516
2
        if (keys_to_recheck.empty()) {
2517
0
            return;
2518
0
        }
2519
2520
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
2
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
2
            const auto& current_meta = current_rowset.rowset_meta();
2529
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
2
                                   current_meta.rowset_id_v2()) != 0) {
2531
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
0
                continue;
2533
0
            }
2534
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2535
2
                                                   current_meta.tablet_id(),
2536
2
                                                   current_meta.rowset_id_v2()) != 0) {
2537
0
                continue;
2538
0
            }
2539
2
            std::vector<std::string> keys {key};
2540
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2541
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2542
0
                continue;
2543
0
            }
2544
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2545
2
        }
2546
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2507
13
                                  num_recycled]() mutable {
2508
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2509
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2510
13
                                                                            keys_to_recheck);
2511
13
        if (abort_ret != 0) {
2512
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2513
2
                            "instance_id="
2514
2
                         << instance_id_;
2515
2
        }
2516
13
        if (keys_to_recheck.empty()) {
2517
2
            return;
2518
2
        }
2519
2520
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2521
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2522
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2523
11
        if (recheck_ret != 0) {
2524
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2525
0
                         << instance_id_;
2526
0
        }
2527
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2528
265
            const auto& current_meta = current_rowset.rowset_meta();
2529
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2530
265
                                   current_meta.rowset_id_v2()) != 0) {
2531
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2532
1
                continue;
2533
1
            }
2534
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2535
264
                                                   current_meta.tablet_id(),
2536
264
                                                   current_meta.rowset_id_v2()) != 0) {
2537
0
                continue;
2538
0
            }
2539
264
            std::vector<std::string> keys {key};
2540
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2541
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2542
0
                continue;
2543
0
            }
2544
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2545
264
        }
2546
11
    });
2547
15
    if (ret != 0) {
2548
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2549
0
    }
2550
15
}
2551
2552
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2553
                                                      std::vector<std::string> rowset_keys_to_abort,
2554
                                                      std::atomic_long* num_recycled,
2555
5
                                                      RecyclerMetricsContext* metrics_context) {
2556
5
    if (rowset_keys_to_abort.empty()) {
2557
0
        return;
2558
0
    }
2559
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2560
5
                        metrics_context]() mutable {
2561
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2562
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2563
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2564
5
        if (abort_ret != 0) {
2565
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2566
0
                            "instance_id="
2567
0
                         << instance_id_;
2568
0
        }
2569
2570
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2571
5
        std::vector<std::string> keys_to_delete;
2572
5
        std::vector<std::string> ref_count_keys_to_delete;
2573
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2574
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2575
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2576
5
        if (recheck_ret != 0) {
2577
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2578
0
                         << instance_id_;
2579
0
        }
2580
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2581
261
            keys_to_delete.push_back(key);
2582
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2583
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2584
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2585
261
        }
2586
2587
5
        if (keys_to_delete.empty()) {
2588
0
            return;
2589
0
        }
2590
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2591
5
                               *metrics_context) != 0) {
2592
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2593
0
            return;
2594
0
        }
2595
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2596
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2597
261
                                                   rowset.rowset_id_v2()) != 0) {
2598
0
                return;
2599
0
            }
2600
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2601
0
                return;
2602
0
            }
2603
261
        }
2604
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2605
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2606
0
            return;
2607
0
        }
2608
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2609
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2610
0
                         << instance_id_;
2611
0
            return;
2612
0
        }
2613
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2614
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2560
3
                        metrics_context]() mutable {
2561
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2562
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2563
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2564
3
        if (abort_ret != 0) {
2565
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2566
0
                            "instance_id="
2567
0
                         << instance_id_;
2568
0
        }
2569
2570
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2571
3
        std::vector<std::string> keys_to_delete;
2572
3
        std::vector<std::string> ref_count_keys_to_delete;
2573
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2574
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2575
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2576
3
        if (recheck_ret != 0) {
2577
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2578
0
                         << instance_id_;
2579
0
        }
2580
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2581
3
            keys_to_delete.push_back(key);
2582
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2583
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2584
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2585
3
        }
2586
2587
3
        if (keys_to_delete.empty()) {
2588
0
            return;
2589
0
        }
2590
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2591
3
                               *metrics_context) != 0) {
2592
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2593
0
            return;
2594
0
        }
2595
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2596
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2597
3
                                                   rowset.rowset_id_v2()) != 0) {
2598
0
                return;
2599
0
            }
2600
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2601
0
                return;
2602
0
            }
2603
3
        }
2604
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2605
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2606
0
            return;
2607
0
        }
2608
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2609
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2610
0
                         << instance_id_;
2611
0
            return;
2612
0
        }
2613
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2614
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2560
2
                        metrics_context]() mutable {
2561
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2562
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2563
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2564
2
        if (abort_ret != 0) {
2565
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2566
0
                            "instance_id="
2567
0
                         << instance_id_;
2568
0
        }
2569
2570
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2571
2
        std::vector<std::string> keys_to_delete;
2572
2
        std::vector<std::string> ref_count_keys_to_delete;
2573
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2574
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2575
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2576
2
        if (recheck_ret != 0) {
2577
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2578
0
                         << instance_id_;
2579
0
        }
2580
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2581
258
            keys_to_delete.push_back(key);
2582
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2583
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2584
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2585
258
        }
2586
2587
2
        if (keys_to_delete.empty()) {
2588
0
            return;
2589
0
        }
2590
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2591
2
                               *metrics_context) != 0) {
2592
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2593
0
            return;
2594
0
        }
2595
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2596
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2597
258
                                                   rowset.rowset_id_v2()) != 0) {
2598
0
                return;
2599
0
            }
2600
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2601
0
                return;
2602
0
            }
2603
258
        }
2604
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2605
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2606
0
            return;
2607
0
        }
2608
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2609
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2610
0
                         << instance_id_;
2611
0
            return;
2612
0
        }
2613
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2614
2
    });
2615
5
}
2616
2617
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2618
1
    const std::string task_name = "recycle_ref_rowsets";
2619
1
    *has_unrecycled_rowsets = false;
2620
2621
1
    std::string data_rowset_ref_count_key_start =
2622
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2623
1
    std::string data_rowset_ref_count_key_end =
2624
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2625
2626
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2627
2628
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2629
1
    register_recycle_task(task_name, start_time);
2630
2631
1
    DORIS_CLOUD_DEFER {
2632
1
        unregister_recycle_task(task_name);
2633
1
        int64_t cost =
2634
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2635
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2636
1
                .tag("instance_id", instance_id_);
2637
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2631
1
    DORIS_CLOUD_DEFER {
2632
1
        unregister_recycle_task(task_name);
2633
1
        int64_t cost =
2634
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2635
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2636
1
                .tag("instance_id", instance_id_);
2637
1
    };
2638
2639
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2640
1
    std::set<int64_t> tablets_with_refs;
2641
1
    int64_t num_scanned = 0;
2642
2643
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2644
0
        ++num_scanned;
2645
0
        int64_t tablet_id;
2646
0
        std::string rowset_id;
2647
0
        std::string_view key(k);
2648
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2649
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2650
0
            return 0; // Continue scanning
2651
0
        }
2652
2653
0
        tablets_with_refs.insert(tablet_id);
2654
0
        return 0;
2655
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2656
2657
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2658
1
                         std::move(scan_func)) != 0) {
2659
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2660
0
        return -1;
2661
0
    }
2662
2663
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2664
1
             tablets_with_refs.size(), num_scanned)
2665
1
            .tag("instance_id", instance_id_);
2666
2667
    // Phase 2: Recycle each tablet
2668
1
    int64_t num_recycled_tablets = 0;
2669
1
    for (int64_t tablet_id : tablets_with_refs) {
2670
0
        if (stopped()) {
2671
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2672
0
                    .tag("instance_id", instance_id_)
2673
0
                    .tag("tablets_processed", num_recycled_tablets)
2674
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2675
0
            break;
2676
0
        }
2677
2678
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2679
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2680
0
            LOG_WARNING("failed to recycle tablet")
2681
0
                    .tag("instance_id", instance_id_)
2682
0
                    .tag("tablet_id", tablet_id);
2683
0
            return -1;
2684
0
        }
2685
0
        ++num_recycled_tablets;
2686
0
    }
2687
2688
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2689
1
            .tag("instance_id", instance_id_)
2690
1
            .tag("total_tablets", tablets_with_refs.size());
2691
2692
    // Phase 3: Scan again to check if any ref count keys still exist
2693
1
    std::unique_ptr<Transaction> txn;
2694
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2695
1
    if (err != TxnErrorCode::TXN_OK) {
2696
0
        LOG_WARNING("failed to create txn for final check")
2697
0
                .tag("instance_id", instance_id_)
2698
0
                .tag("err", err);
2699
0
        return -1;
2700
0
    }
2701
2702
1
    std::unique_ptr<RangeGetIterator> iter;
2703
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2704
1
    if (err != TxnErrorCode::TXN_OK) {
2705
0
        LOG_WARNING("failed to create range iterator for final check")
2706
0
                .tag("instance_id", instance_id_)
2707
0
                .tag("err", err);
2708
0
        return -1;
2709
0
    }
2710
2711
1
    *has_unrecycled_rowsets = iter->has_next();
2712
1
    if (*has_unrecycled_rowsets) {
2713
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2714
0
                .tag("instance_id", instance_id_);
2715
0
    }
2716
2717
1
    return 0;
2718
1
}
2719
2720
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2721
16
                                                         RecyclerMetricsContext* metrics_context) {
2722
16
    std::string end = prefix;
2723
16
    end.push_back('\xff');
2724
16
    std::vector<std::string_view> keys;
2725
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2726
20.0k
        keys.push_back(key);
2727
20.0k
        return 0;
2728
20.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2725
4
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2726
4
        keys.push_back(key);
2727
4
        return 0;
2728
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2725
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2726
20.0k
        keys.push_back(key);
2727
20.0k
        return 0;
2728
20.0k
    };
2729
16
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2730
16
        if (keys.empty()) {
2731
0
            return 0;
2732
0
        }
2733
16
        DORIS_CLOUD_DEFER {
2734
16
            keys.clear();
2735
16
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2733
4
        DORIS_CLOUD_DEFER {
2734
4
            keys.clear();
2735
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2733
12
        DORIS_CLOUD_DEFER {
2734
12
            keys.clear();
2735
12
        };
2736
16
        const size_t num_keys = keys.size();
2737
16
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2738
0
            LOG_WARNING("failed to delete table stream offsets")
2739
0
                    .tag("instance_id", instance_id_)
2740
0
                    .tag("num_keys", num_keys);
2741
0
            return -1;
2742
0
        }
2743
16
        metrics_context->total_recycled_num += num_keys;
2744
16
        metrics_context->report();
2745
16
        return 0;
2746
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2729
4
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2730
4
        if (keys.empty()) {
2731
0
            return 0;
2732
0
        }
2733
4
        DORIS_CLOUD_DEFER {
2734
4
            keys.clear();
2735
4
        };
2736
4
        const size_t num_keys = keys.size();
2737
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2738
0
            LOG_WARNING("failed to delete table stream offsets")
2739
0
                    .tag("instance_id", instance_id_)
2740
0
                    .tag("num_keys", num_keys);
2741
0
            return -1;
2742
0
        }
2743
4
        metrics_context->total_recycled_num += num_keys;
2744
4
        metrics_context->report();
2745
4
        return 0;
2746
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2729
12
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2730
12
        if (keys.empty()) {
2731
0
            return 0;
2732
0
        }
2733
12
        DORIS_CLOUD_DEFER {
2734
12
            keys.clear();
2735
12
        };
2736
12
        const size_t num_keys = keys.size();
2737
12
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2738
0
            LOG_WARNING("failed to delete table stream offsets")
2739
0
                    .tag("instance_id", instance_id_)
2740
0
                    .tag("num_keys", num_keys);
2741
0
            return -1;
2742
0
        }
2743
12
        metrics_context->total_recycled_num += num_keys;
2744
12
        metrics_context->report();
2745
12
        return 0;
2746
12
    };
2747
16
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2748
16
}
2749
2750
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2751
                                              const RecycleIndexPB& recycle_index,
2752
8
                                              std::string_view recycle_key) {
2753
8
    std::unique_ptr<Transaction> txn;
2754
8
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2755
8
    if (err != TxnErrorCode::TXN_OK) {
2756
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2757
0
                .tag("instance_id", instance_id_)
2758
0
                .tag("stream_id", stream_id)
2759
0
                .tag("err", err);
2760
0
        return -1;
2761
0
    }
2762
2763
8
    std::string current_recycle_value;
2764
8
    err = txn->get(recycle_key, &current_recycle_value);
2765
8
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2766
0
        return 0;
2767
0
    }
2768
8
    if (err != TxnErrorCode::TXN_OK) {
2769
0
        LOG_WARNING("failed to read table stream recycle index")
2770
0
                .tag("instance_id", instance_id_)
2771
0
                .tag("stream_id", stream_id)
2772
0
                .tag("err", err);
2773
0
        return -1;
2774
0
    }
2775
8
    RecycleIndexPB current_recycle_index;
2776
8
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2777
8
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2778
8
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2779
8
        current_recycle_index.db_id() != recycle_index.db_id() ||
2780
8
        current_recycle_index.table_id() != recycle_index.table_id() ||
2781
8
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2782
0
        LOG_WARNING("table stream recycle index changed during recycling")
2783
0
                .tag("instance_id", instance_id_)
2784
0
                .tag("stream_id", stream_id);
2785
0
        return -1;
2786
0
    }
2787
2788
8
    txn->remove(recycle_key);
2789
8
    err = txn->commit();
2790
8
    if (err != TxnErrorCode::TXN_OK) {
2791
0
        LOG_WARNING("failed to commit final table stream cleanup")
2792
0
                .tag("instance_id", instance_id_)
2793
0
                .tag("stream_id", stream_id)
2794
0
                .tag("err", err);
2795
0
        return -1;
2796
0
    }
2797
8
    return 0;
2798
8
}
2799
2800
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2801
8
                                     std::string_view recycle_key) {
2802
8
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2803
0
        LOG_WARNING("table stream recycle index is missing binding")
2804
0
                .tag("instance_id", instance_id_)
2805
0
                .tag("stream_id", stream_id);
2806
0
        return -1;
2807
0
    }
2808
2809
8
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2810
8
    DORIS_CLOUD_DEFER {
2811
8
        metrics_context.finish_report();
2812
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2810
3
    DORIS_CLOUD_DEFER {
2811
3
        metrics_context.finish_report();
2812
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2810
5
    DORIS_CLOUD_DEFER {
2811
5
        metrics_context.finish_report();
2812
5
    };
2813
8
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2814
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2815
8
            recycle_index.stream_db_id(), stream_id);
2816
8
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2817
0
        return -1;
2818
0
    }
2819
8
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2820
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2821
8
            recycle_index.stream_db_id(), stream_id);
2822
8
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2823
8
        stopped()) {
2824
0
        return -1;
2825
0
    }
2826
8
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2827
8
}
2828
2829
int InstanceRecycler::recycle_partition_table_stream_offsets(
2830
        int64_t db_id, int64_t table_id, int64_t partition_id,
2831
12
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2832
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2833
12
    DORIS_CLOUD_DEFER {
2834
12
        metrics_context.finish_report();
2835
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2833
1
    DORIS_CLOUD_DEFER {
2834
1
        metrics_context.finish_report();
2835
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2833
11
    DORIS_CLOUD_DEFER {
2834
11
        metrics_context.finish_report();
2835
11
    };
2836
12
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2837
17
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2838
5
        const size_t end_index =
2839
5
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2840
5
        std::unique_ptr<Transaction> txn;
2841
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2842
5
        if (err != TxnErrorCode::TXN_OK) {
2843
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2844
0
                    .tag("instance_id", instance_id_)
2845
0
                    .tag("partition_id", partition_id)
2846
0
                    .tag("err", err);
2847
0
            return -1;
2848
0
        }
2849
12
        for (size_t i = begin_index; i < end_index; ++i) {
2850
7
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2851
7
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2852
7
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2853
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2854
0
                        .tag("instance_id", instance_id_)
2855
0
                        .tag("partition_id", partition_id)
2856
0
                        .tag("stream_id", stream.stream_id());
2857
0
                return -1;
2858
0
            }
2859
7
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2860
7
                                                 stream.base_table_id(), stream.stream_db_id(),
2861
7
                                                 stream.stream_id(), partition_id}));
2862
7
            versioned_remove_all(
2863
7
                    txn.get(), versioned::table_stream_offset_key(
2864
7
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2865
7
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2866
7
        }
2867
5
        err = txn->commit();
2868
5
        if (err != TxnErrorCode::TXN_OK) {
2869
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2870
0
                    .tag("instance_id", instance_id_)
2871
0
                    .tag("partition_id", partition_id)
2872
0
                    .tag("err", err);
2873
0
            return -1;
2874
0
        }
2875
5
        metrics_context.total_recycled_num += end_index - begin_index;
2876
5
        metrics_context.report();
2877
5
    }
2878
12
    return 0;
2879
12
}
2880
2881
25
int InstanceRecycler::recycle_indexes() {
2882
25
    const std::string task_name = "recycle_indexes";
2883
25
    int64_t num_scanned = 0;
2884
25
    int64_t num_expired = 0;
2885
25
    int64_t num_recycled = 0;
2886
25
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2887
2888
25
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2889
25
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2890
25
    std::string index_key0;
2891
25
    std::string index_key1;
2892
25
    recycle_index_key(index_key_info0, &index_key0);
2893
25
    recycle_index_key(index_key_info1, &index_key1);
2894
2895
25
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2896
2897
25
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2898
25
    register_recycle_task(task_name, start_time);
2899
2900
25
    DORIS_CLOUD_DEFER {
2901
25
        unregister_recycle_task(task_name);
2902
25
        int64_t cost =
2903
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2904
25
        metrics_context.finish_report();
2905
25
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2906
25
                .tag("instance_id", instance_id_)
2907
25
                .tag("num_scanned", num_scanned)
2908
25
                .tag("num_expired", num_expired)
2909
25
                .tag("num_recycled", num_recycled);
2910
25
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2900
4
    DORIS_CLOUD_DEFER {
2901
4
        unregister_recycle_task(task_name);
2902
4
        int64_t cost =
2903
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2904
4
        metrics_context.finish_report();
2905
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2906
4
                .tag("instance_id", instance_id_)
2907
4
                .tag("num_scanned", num_scanned)
2908
4
                .tag("num_expired", num_expired)
2909
4
                .tag("num_recycled", num_recycled);
2910
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2900
21
    DORIS_CLOUD_DEFER {
2901
21
        unregister_recycle_task(task_name);
2902
21
        int64_t cost =
2903
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2904
21
        metrics_context.finish_report();
2905
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2906
21
                .tag("instance_id", instance_id_)
2907
21
                .tag("num_scanned", num_scanned)
2908
21
                .tag("num_expired", num_expired)
2909
21
                .tag("num_recycled", num_recycled);
2910
21
    };
2911
2912
25
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2913
2914
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2915
25
    std::vector<std::string_view> index_keys;
2916
25
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2917
18
        ++num_scanned;
2918
18
        RecycleIndexPB index_pb;
2919
18
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2920
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2921
0
            return -1;
2922
0
        }
2923
18
        int64_t current_time = ::time(nullptr);
2924
18
        if (current_time <
2925
18
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2926
0
            return 0;
2927
0
        }
2928
18
        ++num_expired;
2929
        // decode index_id
2930
18
        auto k1 = k;
2931
18
        k1.remove_prefix(1);
2932
18
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2933
18
        decode_key(&k1, &out);
2934
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2935
18
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2936
18
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2937
18
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2938
18
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2939
        // Change state to RECYCLING
2940
18
        std::unique_ptr<Transaction> txn;
2941
18
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2942
18
        if (err != TxnErrorCode::TXN_OK) {
2943
0
            LOG_WARNING("failed to create txn").tag("err", err);
2944
0
            return -1;
2945
0
        }
2946
18
        std::string val;
2947
18
        err = txn->get(k, &val);
2948
18
        if (err ==
2949
18
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2950
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2951
0
            return 0;
2952
0
        }
2953
18
        if (err != TxnErrorCode::TXN_OK) {
2954
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2955
0
            return -1;
2956
0
        }
2957
18
        index_pb.Clear();
2958
18
        if (!index_pb.ParseFromString(val)) {
2959
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2960
0
            return -1;
2961
0
        }
2962
18
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2963
16
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2964
16
            txn->put(k, index_pb.SerializeAsString());
2965
16
            err = txn->commit();
2966
16
            if (err != TxnErrorCode::TXN_OK) {
2967
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2968
0
                return -1;
2969
0
            }
2970
16
        }
2971
18
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2972
8
            if (recycle_stream(index_id, index_pb, k) != 0) {
2973
0
                LOG_WARNING("failed to recycle table stream")
2974
0
                        .tag("instance_id", instance_id_)
2975
0
                        .tag("stream_id", index_id);
2976
0
                return -1;
2977
0
            }
2978
8
            metrics_context.total_recycled_num = ++num_recycled;
2979
8
            metrics_context.report();
2980
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2981
8
            return 0;
2982
8
        }
2983
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2984
1
            LOG_WARNING("failed to recycle tablets under index")
2985
1
                    .tag("table_id", index_pb.table_id())
2986
1
                    .tag("instance_id", instance_id_)
2987
1
                    .tag("index_id", index_id);
2988
1
            return -1;
2989
1
        }
2990
2991
9
        if (index_pb.has_db_id()) {
2992
            // Recycle the versioned keys
2993
3
            std::unique_ptr<Transaction> txn;
2994
3
            err = txn_kv_->create_txn(&txn);
2995
3
            if (err != TxnErrorCode::TXN_OK) {
2996
0
                LOG_WARNING("failed to create txn").tag("err", err);
2997
0
                return -1;
2998
0
            }
2999
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3000
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3001
3
            std::string index_inverted_key = versioned::index_inverted_key(
3002
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3003
3
            versioned_remove_all(txn.get(), meta_key);
3004
3
            txn->remove(index_key);
3005
3
            txn->remove(index_inverted_key);
3006
3
            err = txn->commit();
3007
3
            if (err != TxnErrorCode::TXN_OK) {
3008
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3009
0
                return -1;
3010
0
            }
3011
3
        }
3012
3013
9
        metrics_context.total_recycled_num = ++num_recycled;
3014
9
        metrics_context.report();
3015
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3016
9
        index_keys.push_back(k);
3017
9
        return 0;
3018
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2916
5
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2917
5
        ++num_scanned;
2918
5
        RecycleIndexPB index_pb;
2919
5
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2920
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2921
0
            return -1;
2922
0
        }
2923
5
        int64_t current_time = ::time(nullptr);
2924
5
        if (current_time <
2925
5
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2926
0
            return 0;
2927
0
        }
2928
5
        ++num_expired;
2929
        // decode index_id
2930
5
        auto k1 = k;
2931
5
        k1.remove_prefix(1);
2932
5
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2933
5
        decode_key(&k1, &out);
2934
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2935
5
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2936
5
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2937
5
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2938
5
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2939
        // Change state to RECYCLING
2940
5
        std::unique_ptr<Transaction> txn;
2941
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2942
5
        if (err != TxnErrorCode::TXN_OK) {
2943
0
            LOG_WARNING("failed to create txn").tag("err", err);
2944
0
            return -1;
2945
0
        }
2946
5
        std::string val;
2947
5
        err = txn->get(k, &val);
2948
5
        if (err ==
2949
5
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2950
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2951
0
            return 0;
2952
0
        }
2953
5
        if (err != TxnErrorCode::TXN_OK) {
2954
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2955
0
            return -1;
2956
0
        }
2957
5
        index_pb.Clear();
2958
5
        if (!index_pb.ParseFromString(val)) {
2959
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2960
0
            return -1;
2961
0
        }
2962
5
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2963
4
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2964
4
            txn->put(k, index_pb.SerializeAsString());
2965
4
            err = txn->commit();
2966
4
            if (err != TxnErrorCode::TXN_OK) {
2967
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2968
0
                return -1;
2969
0
            }
2970
4
        }
2971
5
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2972
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
2973
0
                LOG_WARNING("failed to recycle table stream")
2974
0
                        .tag("instance_id", instance_id_)
2975
0
                        .tag("stream_id", index_id);
2976
0
                return -1;
2977
0
            }
2978
3
            metrics_context.total_recycled_num = ++num_recycled;
2979
3
            metrics_context.report();
2980
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2981
3
            return 0;
2982
3
        }
2983
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2984
1
            LOG_WARNING("failed to recycle tablets under index")
2985
1
                    .tag("table_id", index_pb.table_id())
2986
1
                    .tag("instance_id", instance_id_)
2987
1
                    .tag("index_id", index_id);
2988
1
            return -1;
2989
1
        }
2990
2991
1
        if (index_pb.has_db_id()) {
2992
            // Recycle the versioned keys
2993
1
            std::unique_ptr<Transaction> txn;
2994
1
            err = txn_kv_->create_txn(&txn);
2995
1
            if (err != TxnErrorCode::TXN_OK) {
2996
0
                LOG_WARNING("failed to create txn").tag("err", err);
2997
0
                return -1;
2998
0
            }
2999
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3000
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3001
1
            std::string index_inverted_key = versioned::index_inverted_key(
3002
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3003
1
            versioned_remove_all(txn.get(), meta_key);
3004
1
            txn->remove(index_key);
3005
1
            txn->remove(index_inverted_key);
3006
1
            err = txn->commit();
3007
1
            if (err != TxnErrorCode::TXN_OK) {
3008
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3009
0
                return -1;
3010
0
            }
3011
1
        }
3012
3013
1
        metrics_context.total_recycled_num = ++num_recycled;
3014
1
        metrics_context.report();
3015
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3016
1
        index_keys.push_back(k);
3017
1
        return 0;
3018
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2916
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2917
13
        ++num_scanned;
2918
13
        RecycleIndexPB index_pb;
2919
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2920
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2921
0
            return -1;
2922
0
        }
2923
13
        int64_t current_time = ::time(nullptr);
2924
13
        if (current_time <
2925
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2926
0
            return 0;
2927
0
        }
2928
13
        ++num_expired;
2929
        // decode index_id
2930
13
        auto k1 = k;
2931
13
        k1.remove_prefix(1);
2932
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2933
13
        decode_key(&k1, &out);
2934
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2935
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2936
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2937
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2938
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2939
        // Change state to RECYCLING
2940
13
        std::unique_ptr<Transaction> txn;
2941
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2942
13
        if (err != TxnErrorCode::TXN_OK) {
2943
0
            LOG_WARNING("failed to create txn").tag("err", err);
2944
0
            return -1;
2945
0
        }
2946
13
        std::string val;
2947
13
        err = txn->get(k, &val);
2948
13
        if (err ==
2949
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2950
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2951
0
            return 0;
2952
0
        }
2953
13
        if (err != TxnErrorCode::TXN_OK) {
2954
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2955
0
            return -1;
2956
0
        }
2957
13
        index_pb.Clear();
2958
13
        if (!index_pb.ParseFromString(val)) {
2959
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2960
0
            return -1;
2961
0
        }
2962
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2963
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2964
12
            txn->put(k, index_pb.SerializeAsString());
2965
12
            err = txn->commit();
2966
12
            if (err != TxnErrorCode::TXN_OK) {
2967
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2968
0
                return -1;
2969
0
            }
2970
12
        }
2971
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
2972
5
            if (recycle_stream(index_id, index_pb, k) != 0) {
2973
0
                LOG_WARNING("failed to recycle table stream")
2974
0
                        .tag("instance_id", instance_id_)
2975
0
                        .tag("stream_id", index_id);
2976
0
                return -1;
2977
0
            }
2978
5
            metrics_context.total_recycled_num = ++num_recycled;
2979
5
            metrics_context.report();
2980
5
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2981
5
            return 0;
2982
5
        }
2983
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2984
0
            LOG_WARNING("failed to recycle tablets under index")
2985
0
                    .tag("table_id", index_pb.table_id())
2986
0
                    .tag("instance_id", instance_id_)
2987
0
                    .tag("index_id", index_id);
2988
0
            return -1;
2989
0
        }
2990
2991
8
        if (index_pb.has_db_id()) {
2992
            // Recycle the versioned keys
2993
2
            std::unique_ptr<Transaction> txn;
2994
2
            err = txn_kv_->create_txn(&txn);
2995
2
            if (err != TxnErrorCode::TXN_OK) {
2996
0
                LOG_WARNING("failed to create txn").tag("err", err);
2997
0
                return -1;
2998
0
            }
2999
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3000
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3001
2
            std::string index_inverted_key = versioned::index_inverted_key(
3002
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3003
2
            versioned_remove_all(txn.get(), meta_key);
3004
2
            txn->remove(index_key);
3005
2
            txn->remove(index_inverted_key);
3006
2
            err = txn->commit();
3007
2
            if (err != TxnErrorCode::TXN_OK) {
3008
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3009
0
                return -1;
3010
0
            }
3011
2
        }
3012
3013
8
        metrics_context.total_recycled_num = ++num_recycled;
3014
8
        metrics_context.report();
3015
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3016
8
        index_keys.push_back(k);
3017
8
        return 0;
3018
8
    };
3019
3020
25
    auto loop_done = [&index_keys, this]() -> int {
3021
13
        if (index_keys.empty()) return 0;
3022
5
        DORIS_CLOUD_DEFER {
3023
5
            index_keys.clear();
3024
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3022
1
        DORIS_CLOUD_DEFER {
3023
1
            index_keys.clear();
3024
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3022
4
        DORIS_CLOUD_DEFER {
3023
4
            index_keys.clear();
3024
4
        };
3025
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3026
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3027
0
            return -1;
3028
0
        }
3029
5
        return 0;
3030
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3020
4
    auto loop_done = [&index_keys, this]() -> int {
3021
4
        if (index_keys.empty()) return 0;
3022
1
        DORIS_CLOUD_DEFER {
3023
1
            index_keys.clear();
3024
1
        };
3025
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3026
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3027
0
            return -1;
3028
0
        }
3029
1
        return 0;
3030
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3020
9
    auto loop_done = [&index_keys, this]() -> int {
3021
9
        if (index_keys.empty()) return 0;
3022
4
        DORIS_CLOUD_DEFER {
3023
4
            index_keys.clear();
3024
4
        };
3025
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3026
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3027
0
            return -1;
3028
0
        }
3029
4
        return 0;
3030
4
    };
3031
3032
25
    if (config::enable_recycler_stats_metrics) {
3033
0
        scan_and_statistics_indexes();
3034
0
    }
3035
    // recycle_func and loop_done for scan and recycle
3036
25
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3037
25
}
3038
3039
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3040
8.25k
                             int64_t tablet_id) {
3041
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3042
3043
8.25k
    std::unique_ptr<Transaction> txn;
3044
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3045
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3046
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3047
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3048
0
        return false;
3049
0
    }
3050
3051
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3052
8.25k
    std::string tablet_idx_val;
3053
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3054
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3055
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3056
0
                     << " tablet_id=" << tablet_id << " err=" << err
3057
0
                     << " key=" << hex(tablet_idx_key);
3058
0
        return false;
3059
0
    }
3060
3061
8.25k
    TabletIndexPB tablet_idx_pb;
3062
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3063
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3064
0
                     << " tablet_id=" << tablet_id;
3065
0
        return false;
3066
0
    }
3067
3068
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3069
        // In the previous version, the db_id was not set in the index_pb.
3070
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3071
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3072
0
                  << " instance_id=" << instance_id
3073
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3074
0
        return true;
3075
0
    }
3076
3077
8.25k
    std::string ver_val;
3078
8.25k
    std::string ver_key =
3079
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3080
8.25k
                                   tablet_idx_pb.partition_id()});
3081
8.25k
    err = txn->get(ver_key, &ver_val);
3082
3083
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3084
214
        LOG(INFO) << ""
3085
214
                     "partition version not found, instance_id="
3086
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3087
214
                  << " table_id=" << tablet_idx_pb.table_id()
3088
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3089
214
                  << " key=" << hex(ver_key);
3090
214
        return true;
3091
214
    }
3092
3093
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3094
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3095
0
                     << " db_id=" << tablet_idx_pb.db_id()
3096
0
                     << " table_id=" << tablet_idx_pb.table_id()
3097
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3098
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3099
0
        return false;
3100
0
    }
3101
3102
8.03k
    VersionPB version_pb;
3103
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3104
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3105
0
                     << " db_id=" << tablet_idx_pb.db_id()
3106
0
                     << " table_id=" << tablet_idx_pb.table_id()
3107
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3108
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3109
0
        return false;
3110
0
    }
3111
3112
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3113
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3114
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3115
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3116
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3117
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3118
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3119
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3120
4.00k
                     << " key=" << hex(ver_key);
3121
4.00k
        return false;
3122
4.00k
    }
3123
4.03k
    return true;
3124
8.03k
}
3125
3126
20
int InstanceRecycler::recycle_partitions() {
3127
20
    const std::string task_name = "recycle_partitions";
3128
20
    int64_t num_scanned = 0;
3129
20
    int64_t num_expired = 0;
3130
20
    int64_t num_recycled = 0;
3131
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3132
3133
20
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3134
20
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3135
20
    std::string part_key0;
3136
20
    std::string part_key1;
3137
20
    recycle_partition_key(part_key_info0, &part_key0);
3138
20
    recycle_partition_key(part_key_info1, &part_key1);
3139
3140
20
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3141
3142
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3143
20
    register_recycle_task(task_name, start_time);
3144
3145
20
    DORIS_CLOUD_DEFER {
3146
20
        unregister_recycle_task(task_name);
3147
20
        int64_t cost =
3148
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3149
20
        metrics_context.finish_report();
3150
20
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3151
20
                .tag("instance_id", instance_id_)
3152
20
                .tag("num_scanned", num_scanned)
3153
20
                .tag("num_expired", num_expired)
3154
20
                .tag("num_recycled", num_recycled);
3155
20
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3145
2
    DORIS_CLOUD_DEFER {
3146
2
        unregister_recycle_task(task_name);
3147
2
        int64_t cost =
3148
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3149
2
        metrics_context.finish_report();
3150
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3151
2
                .tag("instance_id", instance_id_)
3152
2
                .tag("num_scanned", num_scanned)
3153
2
                .tag("num_expired", num_expired)
3154
2
                .tag("num_recycled", num_recycled);
3155
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3145
18
    DORIS_CLOUD_DEFER {
3146
18
        unregister_recycle_task(task_name);
3147
18
        int64_t cost =
3148
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3149
18
        metrics_context.finish_report();
3150
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3151
18
                .tag("instance_id", instance_id_)
3152
18
                .tag("num_scanned", num_scanned)
3153
18
                .tag("num_expired", num_expired)
3154
18
                .tag("num_recycled", num_recycled);
3155
18
    };
3156
3157
20
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3158
3159
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3160
20
    std::vector<std::string_view> partition_keys;
3161
20
    std::vector<std::string> partition_version_keys;
3162
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3163
13
        ++num_scanned;
3164
13
        RecyclePartitionPB part_pb;
3165
13
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3166
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3167
0
            return -1;
3168
0
        }
3169
13
        int64_t current_time = ::time(nullptr);
3170
13
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3171
13
                                                            &earlest_ts)) { // not expired
3172
0
            return 0;
3173
0
        }
3174
13
        ++num_expired;
3175
        // decode partition_id
3176
13
        auto k1 = k;
3177
13
        k1.remove_prefix(1);
3178
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3179
13
        decode_key(&k1, &out);
3180
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3181
13
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3182
13
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3183
13
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3184
13
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3185
        // Change state to RECYCLING
3186
13
        std::unique_ptr<Transaction> txn;
3187
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3188
13
        if (err != TxnErrorCode::TXN_OK) {
3189
0
            LOG_WARNING("failed to create txn").tag("err", err);
3190
0
            return -1;
3191
0
        }
3192
13
        std::string val;
3193
13
        err = txn->get(k, &val);
3194
13
        if (err ==
3195
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3196
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3197
0
            return 0;
3198
0
        }
3199
13
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            LOG_WARNING("failed to get kv");
3201
0
            return -1;
3202
0
        }
3203
13
        part_pb.Clear();
3204
13
        if (!part_pb.ParseFromString(val)) {
3205
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3206
0
            return -1;
3207
0
        }
3208
        // Partitions with PREPARED state MUST have no data
3209
13
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3210
11
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3211
11
            txn->put(k, part_pb.SerializeAsString());
3212
11
            err = txn->commit();
3213
11
            if (err != TxnErrorCode::TXN_OK) {
3214
0
                LOG_WARNING("failed to commit txn: {}", err);
3215
0
                return -1;
3216
0
            }
3217
11
        }
3218
3219
13
        int ret = 0;
3220
37
        for (int64_t index_id : part_pb.index_id()) {
3221
37
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3222
1
                LOG_WARNING("failed to recycle tablets under partition")
3223
1
                        .tag("table_id", part_pb.table_id())
3224
1
                        .tag("instance_id", instance_id_)
3225
1
                        .tag("index_id", index_id)
3226
1
                        .tag("partition_id", partition_id);
3227
1
                ret = -1;
3228
1
            }
3229
37
        }
3230
13
        if (ret == 0 && part_pb.has_db_id() &&
3231
13
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3232
12
                                                   partition_id, part_pb.table_streams()) != 0) {
3233
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3234
0
                    .tag("instance_id", instance_id_)
3235
0
                    .tag("table_id", part_pb.table_id())
3236
0
                    .tag("partition_id", partition_id);
3237
0
            ret = -1;
3238
0
        }
3239
13
        if (ret == 0 && part_pb.has_db_id()) {
3240
            // Recycle the versioned keys
3241
12
            std::unique_ptr<Transaction> txn;
3242
12
            err = txn_kv_->create_txn(&txn);
3243
12
            if (err != TxnErrorCode::TXN_OK) {
3244
0
                LOG_WARNING("failed to create txn").tag("err", err);
3245
0
                return -1;
3246
0
            }
3247
12
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3248
12
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3249
12
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3250
12
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3251
12
            std::string partition_version_key =
3252
12
                    versioned::partition_version_key({instance_id_, partition_id});
3253
12
            versioned_remove_all(txn.get(), meta_key);
3254
12
            txn->remove(index_key);
3255
12
            txn->remove(inverted_index_key);
3256
12
            versioned_remove_all(txn.get(), partition_version_key);
3257
12
            err = txn->commit();
3258
12
            if (err != TxnErrorCode::TXN_OK) {
3259
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3260
0
                return -1;
3261
0
            }
3262
12
        }
3263
3264
13
        if (ret == 0) {
3265
12
            ++num_recycled;
3266
12
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3267
12
            partition_keys.push_back(k);
3268
12
            if (part_pb.db_id() > 0) {
3269
12
                partition_version_keys.push_back(partition_version_key(
3270
12
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3271
12
            }
3272
12
            metrics_context.total_recycled_num = num_recycled;
3273
12
            metrics_context.report();
3274
12
        }
3275
13
        return ret;
3276
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3162
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3163
2
        ++num_scanned;
3164
2
        RecyclePartitionPB part_pb;
3165
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3166
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3167
0
            return -1;
3168
0
        }
3169
2
        int64_t current_time = ::time(nullptr);
3170
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3171
2
                                                            &earlest_ts)) { // not expired
3172
0
            return 0;
3173
0
        }
3174
2
        ++num_expired;
3175
        // decode partition_id
3176
2
        auto k1 = k;
3177
2
        k1.remove_prefix(1);
3178
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3179
2
        decode_key(&k1, &out);
3180
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3181
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3182
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3183
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3184
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3185
        // Change state to RECYCLING
3186
2
        std::unique_ptr<Transaction> txn;
3187
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3188
2
        if (err != TxnErrorCode::TXN_OK) {
3189
0
            LOG_WARNING("failed to create txn").tag("err", err);
3190
0
            return -1;
3191
0
        }
3192
2
        std::string val;
3193
2
        err = txn->get(k, &val);
3194
2
        if (err ==
3195
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3196
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3197
0
            return 0;
3198
0
        }
3199
2
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            LOG_WARNING("failed to get kv");
3201
0
            return -1;
3202
0
        }
3203
2
        part_pb.Clear();
3204
2
        if (!part_pb.ParseFromString(val)) {
3205
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3206
0
            return -1;
3207
0
        }
3208
        // Partitions with PREPARED state MUST have no data
3209
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3210
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3211
1
            txn->put(k, part_pb.SerializeAsString());
3212
1
            err = txn->commit();
3213
1
            if (err != TxnErrorCode::TXN_OK) {
3214
0
                LOG_WARNING("failed to commit txn: {}", err);
3215
0
                return -1;
3216
0
            }
3217
1
        }
3218
3219
2
        int ret = 0;
3220
2
        for (int64_t index_id : part_pb.index_id()) {
3221
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3222
1
                LOG_WARNING("failed to recycle tablets under partition")
3223
1
                        .tag("table_id", part_pb.table_id())
3224
1
                        .tag("instance_id", instance_id_)
3225
1
                        .tag("index_id", index_id)
3226
1
                        .tag("partition_id", partition_id);
3227
1
                ret = -1;
3228
1
            }
3229
2
        }
3230
2
        if (ret == 0 && part_pb.has_db_id() &&
3231
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3232
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3233
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3234
0
                    .tag("instance_id", instance_id_)
3235
0
                    .tag("table_id", part_pb.table_id())
3236
0
                    .tag("partition_id", partition_id);
3237
0
            ret = -1;
3238
0
        }
3239
2
        if (ret == 0 && part_pb.has_db_id()) {
3240
            // Recycle the versioned keys
3241
1
            std::unique_ptr<Transaction> txn;
3242
1
            err = txn_kv_->create_txn(&txn);
3243
1
            if (err != TxnErrorCode::TXN_OK) {
3244
0
                LOG_WARNING("failed to create txn").tag("err", err);
3245
0
                return -1;
3246
0
            }
3247
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3248
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3249
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3250
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3251
1
            std::string partition_version_key =
3252
1
                    versioned::partition_version_key({instance_id_, partition_id});
3253
1
            versioned_remove_all(txn.get(), meta_key);
3254
1
            txn->remove(index_key);
3255
1
            txn->remove(inverted_index_key);
3256
1
            versioned_remove_all(txn.get(), partition_version_key);
3257
1
            err = txn->commit();
3258
1
            if (err != TxnErrorCode::TXN_OK) {
3259
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3260
0
                return -1;
3261
0
            }
3262
1
        }
3263
3264
2
        if (ret == 0) {
3265
1
            ++num_recycled;
3266
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3267
1
            partition_keys.push_back(k);
3268
1
            if (part_pb.db_id() > 0) {
3269
1
                partition_version_keys.push_back(partition_version_key(
3270
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3271
1
            }
3272
1
            metrics_context.total_recycled_num = num_recycled;
3273
1
            metrics_context.report();
3274
1
        }
3275
2
        return ret;
3276
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3162
11
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3163
11
        ++num_scanned;
3164
11
        RecyclePartitionPB part_pb;
3165
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3166
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3167
0
            return -1;
3168
0
        }
3169
11
        int64_t current_time = ::time(nullptr);
3170
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3171
11
                                                            &earlest_ts)) { // not expired
3172
0
            return 0;
3173
0
        }
3174
11
        ++num_expired;
3175
        // decode partition_id
3176
11
        auto k1 = k;
3177
11
        k1.remove_prefix(1);
3178
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3179
11
        decode_key(&k1, &out);
3180
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3181
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3182
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3183
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3184
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3185
        // Change state to RECYCLING
3186
11
        std::unique_ptr<Transaction> txn;
3187
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3188
11
        if (err != TxnErrorCode::TXN_OK) {
3189
0
            LOG_WARNING("failed to create txn").tag("err", err);
3190
0
            return -1;
3191
0
        }
3192
11
        std::string val;
3193
11
        err = txn->get(k, &val);
3194
11
        if (err ==
3195
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3196
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3197
0
            return 0;
3198
0
        }
3199
11
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            LOG_WARNING("failed to get kv");
3201
0
            return -1;
3202
0
        }
3203
11
        part_pb.Clear();
3204
11
        if (!part_pb.ParseFromString(val)) {
3205
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3206
0
            return -1;
3207
0
        }
3208
        // Partitions with PREPARED state MUST have no data
3209
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3210
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3211
10
            txn->put(k, part_pb.SerializeAsString());
3212
10
            err = txn->commit();
3213
10
            if (err != TxnErrorCode::TXN_OK) {
3214
0
                LOG_WARNING("failed to commit txn: {}", err);
3215
0
                return -1;
3216
0
            }
3217
10
        }
3218
3219
11
        int ret = 0;
3220
35
        for (int64_t index_id : part_pb.index_id()) {
3221
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3222
0
                LOG_WARNING("failed to recycle tablets under partition")
3223
0
                        .tag("table_id", part_pb.table_id())
3224
0
                        .tag("instance_id", instance_id_)
3225
0
                        .tag("index_id", index_id)
3226
0
                        .tag("partition_id", partition_id);
3227
0
                ret = -1;
3228
0
            }
3229
35
        }
3230
11
        if (ret == 0 && part_pb.has_db_id() &&
3231
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3232
11
                                                   partition_id, part_pb.table_streams()) != 0) {
3233
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3234
0
                    .tag("instance_id", instance_id_)
3235
0
                    .tag("table_id", part_pb.table_id())
3236
0
                    .tag("partition_id", partition_id);
3237
0
            ret = -1;
3238
0
        }
3239
11
        if (ret == 0 && part_pb.has_db_id()) {
3240
            // Recycle the versioned keys
3241
11
            std::unique_ptr<Transaction> txn;
3242
11
            err = txn_kv_->create_txn(&txn);
3243
11
            if (err != TxnErrorCode::TXN_OK) {
3244
0
                LOG_WARNING("failed to create txn").tag("err", err);
3245
0
                return -1;
3246
0
            }
3247
11
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3248
11
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3249
11
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3250
11
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3251
11
            std::string partition_version_key =
3252
11
                    versioned::partition_version_key({instance_id_, partition_id});
3253
11
            versioned_remove_all(txn.get(), meta_key);
3254
11
            txn->remove(index_key);
3255
11
            txn->remove(inverted_index_key);
3256
11
            versioned_remove_all(txn.get(), partition_version_key);
3257
11
            err = txn->commit();
3258
11
            if (err != TxnErrorCode::TXN_OK) {
3259
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3260
0
                return -1;
3261
0
            }
3262
11
        }
3263
3264
11
        if (ret == 0) {
3265
11
            ++num_recycled;
3266
11
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3267
11
            partition_keys.push_back(k);
3268
11
            if (part_pb.db_id() > 0) {
3269
11
                partition_version_keys.push_back(partition_version_key(
3270
11
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3271
11
            }
3272
11
            metrics_context.total_recycled_num = num_recycled;
3273
11
            metrics_context.report();
3274
11
        }
3275
11
        return ret;
3276
11
    };
3277
3278
20
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3279
9
        if (partition_keys.empty()) return 0;
3280
8
        DORIS_CLOUD_DEFER {
3281
8
            partition_keys.clear();
3282
8
            partition_version_keys.clear();
3283
8
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3280
1
        DORIS_CLOUD_DEFER {
3281
1
            partition_keys.clear();
3282
1
            partition_version_keys.clear();
3283
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3280
7
        DORIS_CLOUD_DEFER {
3281
7
            partition_keys.clear();
3282
7
            partition_version_keys.clear();
3283
7
        };
3284
8
        std::unique_ptr<Transaction> txn;
3285
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3286
8
        if (err != TxnErrorCode::TXN_OK) {
3287
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3288
0
            return -1;
3289
0
        }
3290
12
        for (auto& k : partition_keys) {
3291
12
            txn->remove(k);
3292
12
        }
3293
12
        for (auto& k : partition_version_keys) {
3294
12
            txn->remove(k);
3295
12
        }
3296
8
        err = txn->commit();
3297
8
        if (err != TxnErrorCode::TXN_OK) {
3298
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3299
0
                         << " err=" << err;
3300
0
            return -1;
3301
0
        }
3302
8
        return 0;
3303
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3278
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3279
2
        if (partition_keys.empty()) return 0;
3280
1
        DORIS_CLOUD_DEFER {
3281
1
            partition_keys.clear();
3282
1
            partition_version_keys.clear();
3283
1
        };
3284
1
        std::unique_ptr<Transaction> txn;
3285
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3286
1
        if (err != TxnErrorCode::TXN_OK) {
3287
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3288
0
            return -1;
3289
0
        }
3290
1
        for (auto& k : partition_keys) {
3291
1
            txn->remove(k);
3292
1
        }
3293
1
        for (auto& k : partition_version_keys) {
3294
1
            txn->remove(k);
3295
1
        }
3296
1
        err = txn->commit();
3297
1
        if (err != TxnErrorCode::TXN_OK) {
3298
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3299
0
                         << " err=" << err;
3300
0
            return -1;
3301
0
        }
3302
1
        return 0;
3303
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3278
7
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3279
7
        if (partition_keys.empty()) return 0;
3280
7
        DORIS_CLOUD_DEFER {
3281
7
            partition_keys.clear();
3282
7
            partition_version_keys.clear();
3283
7
        };
3284
7
        std::unique_ptr<Transaction> txn;
3285
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3286
7
        if (err != TxnErrorCode::TXN_OK) {
3287
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3288
0
            return -1;
3289
0
        }
3290
11
        for (auto& k : partition_keys) {
3291
11
            txn->remove(k);
3292
11
        }
3293
11
        for (auto& k : partition_version_keys) {
3294
11
            txn->remove(k);
3295
11
        }
3296
7
        err = txn->commit();
3297
7
        if (err != TxnErrorCode::TXN_OK) {
3298
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3299
0
                         << " err=" << err;
3300
0
            return -1;
3301
0
        }
3302
7
        return 0;
3303
7
    };
3304
3305
20
    if (config::enable_recycler_stats_metrics) {
3306
0
        scan_and_statistics_partitions();
3307
0
    }
3308
    // recycle_func and loop_done for scan and recycle
3309
20
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3310
20
}
3311
3312
14
int InstanceRecycler::recycle_versions() {
3313
14
    if (should_recycle_versioned_keys()) {
3314
2
        return recycle_orphan_partitions();
3315
2
    }
3316
3317
12
    int64_t num_scanned = 0;
3318
12
    int64_t num_recycled = 0;
3319
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3320
3321
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3322
3323
12
    auto start_time = steady_clock::now();
3324
3325
12
    DORIS_CLOUD_DEFER {
3326
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3327
12
        metrics_context.finish_report();
3328
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3329
12
                .tag("instance_id", instance_id_)
3330
12
                .tag("num_scanned", num_scanned)
3331
12
                .tag("num_recycled", num_recycled);
3332
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3325
12
    DORIS_CLOUD_DEFER {
3326
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3327
12
        metrics_context.finish_report();
3328
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3329
12
                .tag("instance_id", instance_id_)
3330
12
                .tag("num_scanned", num_scanned)
3331
12
                .tag("num_recycled", num_recycled);
3332
12
    };
3333
3334
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3335
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3336
12
    int64_t last_scanned_table_id = 0;
3337
12
    bool is_recycled = false; // Is last scanned kv recycled
3338
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3339
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3340
2
        ++num_scanned;
3341
2
        auto k1 = k;
3342
2
        k1.remove_prefix(1);
3343
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3344
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3345
2
        decode_key(&k1, &out);
3346
2
        DCHECK_EQ(out.size(), 6) << k;
3347
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3348
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3349
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3350
0
            return 0;
3351
0
        }
3352
2
        last_scanned_table_id = table_id;
3353
2
        is_recycled = false;
3354
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3355
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3356
2
        std::unique_ptr<Transaction> txn;
3357
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3358
2
        if (err != TxnErrorCode::TXN_OK) {
3359
0
            return -1;
3360
0
        }
3361
2
        std::unique_ptr<RangeGetIterator> iter;
3362
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3363
2
        if (err != TxnErrorCode::TXN_OK) {
3364
0
            return -1;
3365
0
        }
3366
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3367
1
            return 0;
3368
1
        }
3369
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3370
        // 1. Remove all partition version kvs of this table
3371
1
        auto partition_version_key_begin =
3372
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3373
1
        auto partition_version_key_end =
3374
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3375
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3376
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3377
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3378
1
                     << " table_id=" << table_id;
3379
        // 2. Remove the table version kv of this table
3380
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3381
1
        txn->remove(tbl_version_key);
3382
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3383
        // 3. Remove mow delete bitmap update lock and tablet job lock
3384
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3385
1
        txn->remove(lock_key);
3386
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3387
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3388
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3389
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3390
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3391
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3392
1
                     << " table_id=" << table_id;
3393
1
        err = txn->commit();
3394
1
        if (err != TxnErrorCode::TXN_OK) {
3395
0
            return -1;
3396
0
        }
3397
1
        metrics_context.total_recycled_num = ++num_recycled;
3398
1
        metrics_context.report();
3399
1
        is_recycled = true;
3400
1
        return 0;
3401
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3339
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3340
2
        ++num_scanned;
3341
2
        auto k1 = k;
3342
2
        k1.remove_prefix(1);
3343
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3344
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3345
2
        decode_key(&k1, &out);
3346
2
        DCHECK_EQ(out.size(), 6) << k;
3347
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3348
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3349
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3350
0
            return 0;
3351
0
        }
3352
2
        last_scanned_table_id = table_id;
3353
2
        is_recycled = false;
3354
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3355
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3356
2
        std::unique_ptr<Transaction> txn;
3357
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3358
2
        if (err != TxnErrorCode::TXN_OK) {
3359
0
            return -1;
3360
0
        }
3361
2
        std::unique_ptr<RangeGetIterator> iter;
3362
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3363
2
        if (err != TxnErrorCode::TXN_OK) {
3364
0
            return -1;
3365
0
        }
3366
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3367
1
            return 0;
3368
1
        }
3369
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3370
        // 1. Remove all partition version kvs of this table
3371
1
        auto partition_version_key_begin =
3372
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3373
1
        auto partition_version_key_end =
3374
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3375
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3376
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3377
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3378
1
                     << " table_id=" << table_id;
3379
        // 2. Remove the table version kv of this table
3380
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3381
1
        txn->remove(tbl_version_key);
3382
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3383
        // 3. Remove mow delete bitmap update lock and tablet job lock
3384
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3385
1
        txn->remove(lock_key);
3386
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3387
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3388
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3389
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3390
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3391
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3392
1
                     << " table_id=" << table_id;
3393
1
        err = txn->commit();
3394
1
        if (err != TxnErrorCode::TXN_OK) {
3395
0
            return -1;
3396
0
        }
3397
1
        metrics_context.total_recycled_num = ++num_recycled;
3398
1
        metrics_context.report();
3399
1
        is_recycled = true;
3400
1
        return 0;
3401
1
    };
3402
3403
12
    if (config::enable_recycler_stats_metrics) {
3404
0
        scan_and_statistics_versions();
3405
0
    }
3406
    // recycle_func and loop_done for scan and recycle
3407
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3408
14
}
3409
3410
3
int InstanceRecycler::recycle_orphan_partitions() {
3411
3
    int64_t num_scanned = 0;
3412
3
    int64_t num_recycled = 0;
3413
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3414
3415
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3416
3
            .tag("instance_id", instance_id_);
3417
3418
3
    auto start_time = steady_clock::now();
3419
3420
3
    DORIS_CLOUD_DEFER {
3421
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3422
3
        metrics_context.finish_report();
3423
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3424
3
                .tag("instance_id", instance_id_)
3425
3
                .tag("num_scanned", num_scanned)
3426
3
                .tag("num_recycled", num_recycled);
3427
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3420
3
    DORIS_CLOUD_DEFER {
3421
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3422
3
        metrics_context.finish_report();
3423
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3424
3
                .tag("instance_id", instance_id_)
3425
3
                .tag("num_scanned", num_scanned)
3426
3
                .tag("num_recycled", num_recycled);
3427
3
    };
3428
3429
3
    bool is_empty_table = false;        // whether the table has no indexes
3430
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3431
3
    int64_t current_table_id = 0;       // current scanning table id
3432
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3433
3
                         &current_table_id, &is_table_kvs_recycled,
3434
3
                         this](std::string_view k, std::string_view) {
3435
2
        ++num_scanned;
3436
3437
2
        std::string_view k1(k);
3438
2
        int64_t db_id, table_id, partition_id;
3439
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3440
2
                                                            &partition_id)) {
3441
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3442
0
            return -1;
3443
2
        } else if (table_id != current_table_id) {
3444
2
            current_table_id = table_id;
3445
2
            is_table_kvs_recycled = false;
3446
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3447
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3448
2
            if (err != TxnErrorCode::TXN_OK) {
3449
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3450
0
                             << " table_id=" << table_id << " err=" << err;
3451
0
                return -1;
3452
0
            }
3453
2
        }
3454
3455
2
        if (!is_empty_table) {
3456
            // table is not empty, skip recycle
3457
1
            return 0;
3458
1
        }
3459
3460
1
        std::unique_ptr<Transaction> txn;
3461
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3462
1
        if (err != TxnErrorCode::TXN_OK) {
3463
0
            return -1;
3464
0
        }
3465
3466
        // 1. Remove all partition related kvs
3467
1
        std::string partition_meta_key =
3468
1
                versioned::meta_partition_key({instance_id_, partition_id});
3469
1
        std::string partition_index_key =
3470
1
                versioned::partition_index_key({instance_id_, partition_id});
3471
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3472
1
                {instance_id_, db_id, table_id, partition_id});
3473
1
        std::string partition_version_key =
3474
1
                versioned::partition_version_key({instance_id_, partition_id});
3475
1
        txn->remove(partition_index_key);
3476
1
        txn->remove(partition_inverted_key);
3477
1
        versioned_remove_all(txn.get(), partition_meta_key);
3478
1
        versioned_remove_all(txn.get(), partition_version_key);
3479
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3480
1
                     << " table_id=" << table_id << " db_id=" << db_id
3481
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3482
1
                     << " partition_version_key=" << hex(partition_version_key);
3483
3484
1
        if (!is_table_kvs_recycled) {
3485
1
            is_table_kvs_recycled = true;
3486
3487
            // 2. Remove the table version kv of this table
3488
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3489
1
            versioned_remove_all(txn.get(), table_version_key);
3490
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3491
            // 3. Remove mow delete bitmap update lock and tablet job lock
3492
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3493
1
            txn->remove(lock_key);
3494
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3495
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3496
1
            std::string tablet_job_key_end =
3497
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3498
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3499
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3500
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3501
1
                         << " table_id=" << table_id;
3502
1
        }
3503
3504
1
        err = txn->commit();
3505
1
        if (err != TxnErrorCode::TXN_OK) {
3506
0
            return -1;
3507
0
        }
3508
1
        metrics_context.total_recycled_num = ++num_recycled;
3509
1
        metrics_context.report();
3510
1
        return 0;
3511
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
3434
2
                         this](std::string_view k, std::string_view) {
3435
2
        ++num_scanned;
3436
3437
2
        std::string_view k1(k);
3438
2
        int64_t db_id, table_id, partition_id;
3439
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3440
2
                                                            &partition_id)) {
3441
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3442
0
            return -1;
3443
2
        } else if (table_id != current_table_id) {
3444
2
            current_table_id = table_id;
3445
2
            is_table_kvs_recycled = false;
3446
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3447
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3448
2
            if (err != TxnErrorCode::TXN_OK) {
3449
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3450
0
                             << " table_id=" << table_id << " err=" << err;
3451
0
                return -1;
3452
0
            }
3453
2
        }
3454
3455
2
        if (!is_empty_table) {
3456
            // table is not empty, skip recycle
3457
1
            return 0;
3458
1
        }
3459
3460
1
        std::unique_ptr<Transaction> txn;
3461
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3462
1
        if (err != TxnErrorCode::TXN_OK) {
3463
0
            return -1;
3464
0
        }
3465
3466
        // 1. Remove all partition related kvs
3467
1
        std::string partition_meta_key =
3468
1
                versioned::meta_partition_key({instance_id_, partition_id});
3469
1
        std::string partition_index_key =
3470
1
                versioned::partition_index_key({instance_id_, partition_id});
3471
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3472
1
                {instance_id_, db_id, table_id, partition_id});
3473
1
        std::string partition_version_key =
3474
1
                versioned::partition_version_key({instance_id_, partition_id});
3475
1
        txn->remove(partition_index_key);
3476
1
        txn->remove(partition_inverted_key);
3477
1
        versioned_remove_all(txn.get(), partition_meta_key);
3478
1
        versioned_remove_all(txn.get(), partition_version_key);
3479
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3480
1
                     << " table_id=" << table_id << " db_id=" << db_id
3481
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3482
1
                     << " partition_version_key=" << hex(partition_version_key);
3483
3484
1
        if (!is_table_kvs_recycled) {
3485
1
            is_table_kvs_recycled = true;
3486
3487
            // 2. Remove the table version kv of this table
3488
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3489
1
            versioned_remove_all(txn.get(), table_version_key);
3490
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3491
            // 3. Remove mow delete bitmap update lock and tablet job lock
3492
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3493
1
            txn->remove(lock_key);
3494
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3495
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3496
1
            std::string tablet_job_key_end =
3497
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3498
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3499
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3500
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3501
1
                         << " table_id=" << table_id;
3502
1
        }
3503
3504
1
        err = txn->commit();
3505
1
        if (err != TxnErrorCode::TXN_OK) {
3506
0
            return -1;
3507
0
        }
3508
1
        metrics_context.total_recycled_num = ++num_recycled;
3509
1
        metrics_context.report();
3510
1
        return 0;
3511
1
    };
3512
3513
    // recycle_func and loop_done for scan and recycle
3514
3
    return scan_and_recycle(
3515
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3516
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3517
3
            std::move(recycle_func));
3518
3
}
3519
3520
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3521
                                      RecyclerMetricsContext& metrics_context,
3522
56
                                      int64_t partition_id) {
3523
56
    bool is_multi_version =
3524
56
            instance_info_.has_multi_version_status() &&
3525
56
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3526
56
    int64_t num_scanned = 0;
3527
56
    std::atomic_long num_recycled = 0;
3528
3529
56
    std::string tablet_key_begin, tablet_key_end;
3530
56
    std::string stats_key_begin, stats_key_end;
3531
56
    std::string job_key_begin, job_key_end;
3532
3533
56
    std::string tablet_belongs;
3534
56
    if (partition_id > 0) {
3535
        // recycle tablets in a partition belonging to the index
3536
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3537
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3538
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3539
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3540
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3541
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3542
37
        tablet_belongs = "partition";
3543
37
    } else {
3544
        // recycle tablets in the index
3545
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3546
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3547
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3548
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3549
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3550
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3551
19
        tablet_belongs = "index";
3552
19
    }
3553
3554
56
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3555
56
            .tag("table_id", table_id)
3556
56
            .tag("index_id", index_id)
3557
56
            .tag("partition_id", partition_id);
3558
3559
56
    auto start_time = steady_clock::now();
3560
3561
56
    DORIS_CLOUD_DEFER {
3562
56
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3563
56
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3564
56
                .tag("instance_id", instance_id_)
3565
56
                .tag("table_id", table_id)
3566
56
                .tag("index_id", index_id)
3567
56
                .tag("partition_id", partition_id)
3568
56
                .tag("num_scanned", num_scanned)
3569
56
                .tag("num_recycled", num_recycled);
3570
56
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3561
4
    DORIS_CLOUD_DEFER {
3562
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3563
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3564
4
                .tag("instance_id", instance_id_)
3565
4
                .tag("table_id", table_id)
3566
4
                .tag("index_id", index_id)
3567
4
                .tag("partition_id", partition_id)
3568
4
                .tag("num_scanned", num_scanned)
3569
4
                .tag("num_recycled", num_recycled);
3570
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3561
52
    DORIS_CLOUD_DEFER {
3562
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3563
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3564
52
                .tag("instance_id", instance_id_)
3565
52
                .tag("table_id", table_id)
3566
52
                .tag("index_id", index_id)
3567
52
                .tag("partition_id", partition_id)
3568
52
                .tag("num_scanned", num_scanned)
3569
52
                .tag("num_recycled", num_recycled);
3570
52
    };
3571
3572
    // The tablet key and id which have been recycled.
3573
56
    struct TabletInfo {
3574
56
        std::string_view tablet_meta_key;
3575
56
        int64_t tablet_id;
3576
56
    };
3577
56
    SyncExecutor<TabletInfo> sync_executor(
3578
56
            _thread_pool_group.recycle_tablet_pool,
3579
56
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3580
56
                        index_id, partition_id),
3581
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3581
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3581
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3582
3583
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3584
56
    std::vector<std::string> init_rs_keys;
3585
56
    bool has_failure = false;
3586
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3587
8.25k
        ++num_scanned;
3588
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3589
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3590
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3591
0
            has_failure = true;
3592
0
            return -1;
3593
0
        }
3594
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3595
3596
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3597
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3598
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3599
4.00k
            has_failure = true;
3600
4.00k
            return -1;
3601
4.00k
        }
3602
3603
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3604
4.25k
        sync_executor.add(
3605
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3606
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3607
2
                        LOG_WARNING("failed to recycle tablet")
3608
2
                                .tag("instance_id", instance_id_)
3609
2
                                .tag("tablet_id", tid);
3610
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3611
2
                    }
3612
4.25k
                    ++num_recycled;
3613
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3614
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3615
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3605
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3606
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3607
0
                        LOG_WARNING("failed to recycle tablet")
3608
0
                                .tag("instance_id", instance_id_)
3609
0
                                .tag("tablet_id", tid);
3610
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3611
0
                    }
3612
4.00k
                    ++num_recycled;
3613
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3614
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3615
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3605
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3606
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3607
2
                        LOG_WARNING("failed to recycle tablet")
3608
2
                                .tag("instance_id", instance_id_)
3609
2
                                .tag("tablet_id", tid);
3610
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3611
2
                    }
3612
248
                    ++num_recycled;
3613
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3614
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3615
250
                });
3616
4.25k
        return 0;
3617
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3586
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3587
8.00k
        ++num_scanned;
3588
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3589
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3590
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3591
0
            has_failure = true;
3592
0
            return -1;
3593
0
        }
3594
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3595
3596
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3597
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3598
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3599
4.00k
            has_failure = true;
3600
4.00k
            return -1;
3601
4.00k
        }
3602
3603
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3604
4.00k
        sync_executor.add(
3605
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3606
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3607
4.00k
                        LOG_WARNING("failed to recycle tablet")
3608
4.00k
                                .tag("instance_id", instance_id_)
3609
4.00k
                                .tag("tablet_id", tid);
3610
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3611
4.00k
                    }
3612
4.00k
                    ++num_recycled;
3613
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3614
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3615
4.00k
                });
3616
4.00k
        return 0;
3617
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3586
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3587
251
        ++num_scanned;
3588
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3589
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3590
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3591
0
            has_failure = true;
3592
0
            return -1;
3593
0
        }
3594
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3595
3596
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3597
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3598
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3599
1
            has_failure = true;
3600
1
            return -1;
3601
1
        }
3602
3603
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3604
250
        sync_executor.add(
3605
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3606
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3607
250
                        LOG_WARNING("failed to recycle tablet")
3608
250
                                .tag("instance_id", instance_id_)
3609
250
                                .tag("tablet_id", tid);
3610
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3611
250
                    }
3612
250
                    ++num_recycled;
3613
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3614
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3615
250
                });
3616
250
        return 0;
3617
250
    };
3618
3619
56
    auto loop_done = [&, this]() -> int {
3620
52
        int ret = 0;
3621
52
        bool finished = true;
3622
52
        bool has_empty_key = false;
3623
52
        DORIS_CLOUD_DEFER {
3624
52
            init_rs_keys.clear();
3625
52
            has_failure = false;
3626
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3623
4
        DORIS_CLOUD_DEFER {
3624
4
            init_rs_keys.clear();
3625
4
            has_failure = false;
3626
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3623
48
        DORIS_CLOUD_DEFER {
3624
48
            init_rs_keys.clear();
3625
48
            has_failure = false;
3626
48
        };
3627
52
        auto tablets_info = sync_executor.when_all(&finished);
3628
52
        if (!finished) {
3629
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3630
1
            return -1;
3631
1
        }
3632
3633
51
        size_t size_before_erase = tablets_info.size();
3634
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3634
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3634
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3635
51
        if (tablets_info.empty()) {
3636
2
            return size_before_erase == 0 ? 0 : -1;
3637
49
        } else if (size_before_erase != tablets_info.size()) {
3638
1
            has_empty_key = true;
3639
1
        }
3640
3641
49
        ret = has_empty_key ? -1 : 0;
3642
        // sort the vector using key's order
3643
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3644
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3645
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3643
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3644
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3645
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3643
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3644
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3645
958
        });
3646
49
        std::unique_ptr<Transaction> txn;
3647
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3648
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3649
0
            return -1;
3650
0
        }
3651
49
        std::string tablet_key_end;
3652
49
        if (!tablets_info.empty()) {
3653
49
            if (!has_empty_key && !has_failure) {
3654
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3655
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3656
47
            } else {
3657
8
                for (auto& tablet_info : tablets_info) {
3658
8
                    txn->remove(tablet_info.tablet_meta_key);
3659
8
                }
3660
2
            }
3661
49
        }
3662
49
        if (is_multi_version) {
3663
6
            for (auto& tablet_info : tablets_info) {
3664
                // Remove all versions of tablet compact stats for recycled tablet
3665
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3666
6
                LOG_INFO("remove versioned tablet compact stats key")
3667
6
                        .tag("compact_stats_key", hex(k));
3668
6
                versioned_remove_all(txn.get(), k);
3669
6
            }
3670
6
            for (auto& tablet_info : tablets_info) {
3671
                // Remove all versions of tablet load stats for recycled tablet
3672
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3673
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3674
6
                versioned_remove_all(txn.get(), k);
3675
6
            }
3676
6
            for (auto& tablet_info : tablets_info) {
3677
                // Remove all versions of meta tablet for recycled tablet
3678
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3679
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3680
6
                versioned_remove_all(txn.get(), k);
3681
6
            }
3682
5
        }
3683
4.25k
        for (auto& tablet_info : tablets_info) {
3684
4.25k
            std::string k;
3685
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3686
4.25k
            txn->remove(k);
3687
4.25k
        }
3688
4.25k
        for (auto& tablet_info : tablets_info) {
3689
4.25k
            std::string k;
3690
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3691
4.25k
            txn->remove(k);
3692
4.25k
        }
3693
49
        for (auto& k : init_rs_keys) {
3694
0
            txn->remove(k);
3695
0
        }
3696
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3697
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3698
0
                         << ", err=" << err;
3699
0
            return -1;
3700
0
        }
3701
49
        return ret;
3702
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3619
4
    auto loop_done = [&, this]() -> int {
3620
4
        int ret = 0;
3621
4
        bool finished = true;
3622
4
        bool has_empty_key = false;
3623
4
        DORIS_CLOUD_DEFER {
3624
4
            init_rs_keys.clear();
3625
4
            has_failure = false;
3626
4
        };
3627
4
        auto tablets_info = sync_executor.when_all(&finished);
3628
4
        if (!finished) {
3629
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3630
0
            return -1;
3631
0
        }
3632
3633
4
        size_t size_before_erase = tablets_info.size();
3634
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3635
4
        if (tablets_info.empty()) {
3636
2
            return size_before_erase == 0 ? 0 : -1;
3637
2
        } else if (size_before_erase != tablets_info.size()) {
3638
0
            has_empty_key = true;
3639
0
        }
3640
3641
2
        ret = has_empty_key ? -1 : 0;
3642
        // sort the vector using key's order
3643
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3644
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3645
2
        });
3646
2
        std::unique_ptr<Transaction> txn;
3647
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3648
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3649
0
            return -1;
3650
0
        }
3651
2
        std::string tablet_key_end;
3652
2
        if (!tablets_info.empty()) {
3653
2
            if (!has_empty_key && !has_failure) {
3654
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3655
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3656
2
            } else {
3657
0
                for (auto& tablet_info : tablets_info) {
3658
0
                    txn->remove(tablet_info.tablet_meta_key);
3659
0
                }
3660
0
            }
3661
2
        }
3662
2
        if (is_multi_version) {
3663
0
            for (auto& tablet_info : tablets_info) {
3664
                // Remove all versions of tablet compact stats for recycled tablet
3665
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3666
0
                LOG_INFO("remove versioned tablet compact stats key")
3667
0
                        .tag("compact_stats_key", hex(k));
3668
0
                versioned_remove_all(txn.get(), k);
3669
0
            }
3670
0
            for (auto& tablet_info : tablets_info) {
3671
                // Remove all versions of tablet load stats for recycled tablet
3672
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3673
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3674
0
                versioned_remove_all(txn.get(), k);
3675
0
            }
3676
0
            for (auto& tablet_info : tablets_info) {
3677
                // Remove all versions of meta tablet for recycled tablet
3678
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3679
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3680
0
                versioned_remove_all(txn.get(), k);
3681
0
            }
3682
0
        }
3683
4.00k
        for (auto& tablet_info : tablets_info) {
3684
4.00k
            std::string k;
3685
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3686
4.00k
            txn->remove(k);
3687
4.00k
        }
3688
4.00k
        for (auto& tablet_info : tablets_info) {
3689
4.00k
            std::string k;
3690
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3691
4.00k
            txn->remove(k);
3692
4.00k
        }
3693
2
        for (auto& k : init_rs_keys) {
3694
0
            txn->remove(k);
3695
0
        }
3696
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3697
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3698
0
                         << ", err=" << err;
3699
0
            return -1;
3700
0
        }
3701
2
        return ret;
3702
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3619
48
    auto loop_done = [&, this]() -> int {
3620
48
        int ret = 0;
3621
48
        bool finished = true;
3622
48
        bool has_empty_key = false;
3623
48
        DORIS_CLOUD_DEFER {
3624
48
            init_rs_keys.clear();
3625
48
            has_failure = false;
3626
48
        };
3627
48
        auto tablets_info = sync_executor.when_all(&finished);
3628
48
        if (!finished) {
3629
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3630
1
            return -1;
3631
1
        }
3632
3633
47
        size_t size_before_erase = tablets_info.size();
3634
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3635
47
        if (tablets_info.empty()) {
3636
0
            return size_before_erase == 0 ? 0 : -1;
3637
47
        } else if (size_before_erase != tablets_info.size()) {
3638
1
            has_empty_key = true;
3639
1
        }
3640
3641
47
        ret = has_empty_key ? -1 : 0;
3642
        // sort the vector using key's order
3643
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3644
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3645
47
        });
3646
47
        std::unique_ptr<Transaction> txn;
3647
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3648
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3649
0
            return -1;
3650
0
        }
3651
47
        std::string tablet_key_end;
3652
47
        if (!tablets_info.empty()) {
3653
47
            if (!has_empty_key && !has_failure) {
3654
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3655
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3656
45
            } else {
3657
8
                for (auto& tablet_info : tablets_info) {
3658
8
                    txn->remove(tablet_info.tablet_meta_key);
3659
8
                }
3660
2
            }
3661
47
        }
3662
47
        if (is_multi_version) {
3663
6
            for (auto& tablet_info : tablets_info) {
3664
                // Remove all versions of tablet compact stats for recycled tablet
3665
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3666
6
                LOG_INFO("remove versioned tablet compact stats key")
3667
6
                        .tag("compact_stats_key", hex(k));
3668
6
                versioned_remove_all(txn.get(), k);
3669
6
            }
3670
6
            for (auto& tablet_info : tablets_info) {
3671
                // Remove all versions of tablet load stats for recycled tablet
3672
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3673
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3674
6
                versioned_remove_all(txn.get(), k);
3675
6
            }
3676
6
            for (auto& tablet_info : tablets_info) {
3677
                // Remove all versions of meta tablet for recycled tablet
3678
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3679
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3680
6
                versioned_remove_all(txn.get(), k);
3681
6
            }
3682
5
        }
3683
248
        for (auto& tablet_info : tablets_info) {
3684
248
            std::string k;
3685
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3686
248
            txn->remove(k);
3687
248
        }
3688
248
        for (auto& tablet_info : tablets_info) {
3689
248
            std::string k;
3690
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3691
248
            txn->remove(k);
3692
248
        }
3693
47
        for (auto& k : init_rs_keys) {
3694
0
            txn->remove(k);
3695
0
        }
3696
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3697
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3698
0
                         << ", err=" << err;
3699
0
            return -1;
3700
0
        }
3701
47
        return ret;
3702
47
    };
3703
3704
56
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3705
56
                               std::move(loop_done));
3706
56
    if (ret != 0) {
3707
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3708
5
        return ret;
3709
5
    }
3710
3711
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3712
51
    std::unique_ptr<Transaction> txn;
3713
51
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3714
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3715
0
        return -1;
3716
0
    }
3717
51
    txn->remove(stats_key_begin, stats_key_end);
3718
51
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3719
51
                 << " end=" << hex(stats_key_end);
3720
51
    txn->remove(job_key_begin, job_key_end);
3721
51
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3722
51
    std::string schema_key_begin, schema_key_end;
3723
51
    std::string schema_dict_key;
3724
51
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3725
51
    if (partition_id <= 0) {
3726
        // Delete schema kv of this index
3727
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3728
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3729
15
        txn->remove(schema_key_begin, schema_key_end);
3730
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3731
15
                     << " end=" << hex(schema_key_end);
3732
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3733
15
        txn->remove(schema_dict_key);
3734
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3735
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3736
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3737
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3738
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3739
15
                     << " end=" << hex(versioned_schema_key_end);
3740
15
    }
3741
3742
51
    TxnErrorCode err = txn->commit();
3743
51
    if (err != TxnErrorCode::TXN_OK) {
3744
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3745
0
                     << " err=" << err;
3746
0
        return -1;
3747
0
    }
3748
3749
51
    return ret;
3750
51
}
3751
3752
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3753
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3754
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3755
5.61k
    if (num_segments <= 0) return 0;
3756
3757
5.61k
    std::vector<std::string> file_paths;
3758
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3759
0
        return -1;
3760
0
    }
3761
3762
    // Process inverted indexes
3763
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3764
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3765
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3766
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3767
5.61k
    bool delete_rowset_data_by_prefix = false;
3768
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3769
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3770
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3771
0
        delete_rowset_data_by_prefix = true;
3772
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3773
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3774
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3775
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3776
10.0k
            }
3777
10.0k
        }
3778
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3779
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3780
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3781
2.00k
        }
3782
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3783
        // schema version and index id are not found, delete rowset data by prefix directly.
3784
0
        delete_rowset_data_by_prefix = true;
3785
809
    } else {
3786
        // otherwise, try to get schema kv
3787
809
        InvertedIndexInfo index_info;
3788
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3789
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3790
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3791
809
                                 &inverted_index_get_ret);
3792
809
        if (inverted_index_get_ret == 0) {
3793
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3794
809
                index_format = index_info.first;
3795
809
            }
3796
809
            index_ids = index_info.second;
3797
809
        } else if (inverted_index_get_ret == 1) {
3798
            // 1. Schema kv not found means tablet has been recycled
3799
            // Maybe some tablet recycle failed by some bugs
3800
            // We need to delete again to double check
3801
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3802
            // because we are uncertain about the inverted index information.
3803
            // If there are inverted indexes, some data might not be deleted,
3804
            // but this is acceptable as we have made our best effort to delete the data.
3805
0
            LOG_INFO(
3806
0
                    "delete rowset data schema kv not found, need to delete again to double "
3807
0
                    "check")
3808
0
                    .tag("instance_id", instance_id_)
3809
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3810
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3811
            // Currently index_ids is guaranteed to be empty,
3812
            // but we clear it again here as a safeguard against future code changes
3813
            // that might cause index_ids to no longer be empty
3814
0
            index_format = InvertedIndexStorageFormatPB::V2;
3815
0
            index_ids.clear();
3816
0
        } else {
3817
            // failed to get schema kv, delete rowset data by prefix directly.
3818
0
            delete_rowset_data_by_prefix = true;
3819
0
        }
3820
809
    }
3821
3822
5.61k
    if (delete_rowset_data_by_prefix) {
3823
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3824
0
                                  rs_meta_pb.rowset_id_v2());
3825
0
    }
3826
3827
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3828
5.61k
    if (it == accessor_map_.end()) {
3829
1.59k
        LOG_WARNING("instance has no such resource id")
3830
1.59k
                .tag("instance_id", instance_id_)
3831
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3832
1.59k
        return -1;
3833
1.59k
    }
3834
4.01k
    auto& accessor = it->second;
3835
3836
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3837
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3838
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3839
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3840
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3841
20.0k
                                         &file_paths);
3842
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3843
40.0k
            for (const auto& index_id : index_ids) {
3844
40.0k
                add_file_to_delete_if_not_packed(
3845
40.0k
                        rs_meta_pb,
3846
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3847
40.0k
                                               index_id.second),
3848
40.0k
                        &file_paths);
3849
40.0k
            }
3850
20.0k
        } else if (!index_ids.empty()) {
3851
2
            add_file_to_delete_if_not_packed(
3852
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3853
2
                    &file_paths);
3854
2
        }
3855
20.0k
    }
3856
3857
    // Process delete bitmap - check where it's stored.
3858
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3859
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3860
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3861
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3862
0
                .tag("instance_id", instance_id_)
3863
0
                .tag("tablet_id", tablet_id)
3864
0
                .tag("rowset_id", rowset_id);
3865
0
        return -1;
3866
0
    }
3867
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3868
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3869
2.00k
    }
3870
    // TODO(AlexYue): seems could do do batch
3871
4.01k
    return accessor->delete_files(file_paths);
3872
4.01k
}
3873
3874
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3875
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3876
62.6k
            .tag("instance_id", instance_id_)
3877
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3878
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3879
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3880
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3881
62.6k
    if (index_map.empty()) {
3882
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3883
62.6k
                .tag("instance_id", instance_id_)
3884
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3885
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3886
62.6k
        return 0;
3887
62.6k
    }
3888
3889
18
    struct PackedSmallFileInfo {
3890
18
        std::string small_file_path;
3891
18
    };
3892
18
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3893
18
    packed_file_updates.reserve(index_map.size());
3894
27
    for (const auto& [small_path, index_pb] : index_map) {
3895
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3896
0
            continue;
3897
0
        }
3898
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3899
27
                PackedSmallFileInfo {small_path});
3900
27
    }
3901
18
    if (packed_file_updates.empty()) {
3902
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3903
0
                .tag("instance_id", instance_id_)
3904
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3905
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3906
0
                .tag("index_map_size", index_map.size());
3907
0
        return 0;
3908
0
    }
3909
3910
18
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3911
18
    int ret = 0;
3912
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3913
24
        if (small_files.empty()) {
3914
0
            continue;
3915
0
        }
3916
3917
24
        bool success = false;
3918
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3919
24
            std::unique_ptr<Transaction> txn;
3920
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3921
24
            if (err != TxnErrorCode::TXN_OK) {
3922
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3923
0
                        .tag("instance_id", instance_id_)
3924
0
                        .tag("packed_file_path", packed_file_path)
3925
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3926
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3927
0
                        .tag("err", err);
3928
0
                ret = -1;
3929
0
                break;
3930
0
            }
3931
3932
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3933
24
            std::string packed_val;
3934
24
            err = txn->get(packed_key, &packed_val);
3935
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3936
0
                LOG_WARNING("packed file info not found when recycling rowset")
3937
0
                        .tag("instance_id", instance_id_)
3938
0
                        .tag("packed_file_path", packed_file_path)
3939
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3940
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3941
0
                        .tag("key", hex(packed_key))
3942
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3943
                // Skip this packed file entry and continue with others
3944
0
                success = true;
3945
0
                break;
3946
0
            }
3947
24
            if (err != TxnErrorCode::TXN_OK) {
3948
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3949
0
                        .tag("instance_id", instance_id_)
3950
0
                        .tag("packed_file_path", packed_file_path)
3951
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3952
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3953
0
                        .tag("err", err);
3954
0
                ret = -1;
3955
0
                break;
3956
0
            }
3957
3958
24
            cloud::PackedFileInfoPB packed_info;
3959
24
            if (!packed_info.ParseFromString(packed_val)) {
3960
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3961
0
                        .tag("instance_id", instance_id_)
3962
0
                        .tag("packed_file_path", packed_file_path)
3963
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3964
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3965
0
                ret = -1;
3966
0
                break;
3967
0
            }
3968
3969
24
            LOG_INFO("packed file update check")
3970
24
                    .tag("instance_id", instance_id_)
3971
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3972
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3973
24
                    .tag("merged_file_path", packed_file_path)
3974
24
                    .tag("requested_small_files", small_files.size())
3975
24
                    .tag("merge_entries", packed_info.slices_size());
3976
3977
24
            auto* small_file_entries = packed_info.mutable_slices();
3978
24
            int64_t changed_files = 0;
3979
24
            int64_t missing_entries = 0;
3980
24
            int64_t already_deleted = 0;
3981
27
            for (const auto& small_file_info : small_files) {
3982
27
                bool found = false;
3983
87
                for (auto& small_file_entry : *small_file_entries) {
3984
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3985
27
                        if (!small_file_entry.deleted()) {
3986
27
                            small_file_entry.set_deleted(true);
3987
27
                            if (!small_file_entry.corrected()) {
3988
27
                                small_file_entry.set_corrected(true);
3989
27
                            }
3990
27
                            ++changed_files;
3991
27
                        } else {
3992
0
                            ++already_deleted;
3993
0
                        }
3994
27
                        found = true;
3995
27
                        break;
3996
27
                    }
3997
87
                }
3998
27
                if (!found) {
3999
0
                    ++missing_entries;
4000
0
                    LOG_WARNING("packed file info missing small file entry")
4001
0
                            .tag("instance_id", instance_id_)
4002
0
                            .tag("packed_file_path", packed_file_path)
4003
0
                            .tag("small_file_path", small_file_info.small_file_path)
4004
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4005
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4006
0
                }
4007
27
            }
4008
4009
24
            if (changed_files == 0) {
4010
0
                LOG_INFO("skip merge file update: no merge entries changed")
4011
0
                        .tag("instance_id", instance_id_)
4012
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4013
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4014
0
                        .tag("merged_file_path", packed_file_path)
4015
0
                        .tag("missing_entries", missing_entries)
4016
0
                        .tag("already_deleted", already_deleted)
4017
0
                        .tag("requested_small_files", small_files.size())
4018
0
                        .tag("merge_entries", packed_info.slices_size());
4019
0
                success = true;
4020
0
                break;
4021
0
            }
4022
4023
            // Calculate remaining files
4024
24
            int64_t left_file_count = 0;
4025
24
            int64_t left_file_bytes = 0;
4026
141
            for (const auto& small_file_entry : packed_info.slices()) {
4027
141
                if (!small_file_entry.deleted()) {
4028
57
                    ++left_file_count;
4029
57
                    left_file_bytes += small_file_entry.size();
4030
57
                }
4031
141
            }
4032
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4033
24
            packed_info.set_ref_cnt(left_file_count);
4034
24
            LOG_INFO("updated packed file reference info")
4035
24
                    .tag("instance_id", instance_id_)
4036
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4037
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4038
24
                    .tag("packed_file_path", packed_file_path)
4039
24
                    .tag("ref_cnt", left_file_count)
4040
24
                    .tag("left_file_bytes", left_file_bytes);
4041
4042
24
            if (left_file_count == 0) {
4043
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4044
7
            }
4045
4046
24
            std::string updated_val;
4047
24
            if (!packed_info.SerializeToString(&updated_val)) {
4048
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4049
0
                        .tag("instance_id", instance_id_)
4050
0
                        .tag("packed_file_path", packed_file_path)
4051
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4052
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4053
0
                ret = -1;
4054
0
                break;
4055
0
            }
4056
4057
24
            txn->put(packed_key, updated_val);
4058
24
            err = txn->commit();
4059
24
            if (err == TxnErrorCode::TXN_OK) {
4060
24
                success = true;
4061
24
                if (left_file_count == 0) {
4062
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4063
7
                            .tag("instance_id", instance_id_)
4064
7
                            .tag("packed_file_path", packed_file_path);
4065
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4066
0
                        ret = -1;
4067
0
                    }
4068
7
                }
4069
24
                break;
4070
24
            }
4071
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4072
0
                if (attempt >= max_retry_times) {
4073
0
                    LOG_WARNING("packed file info update conflict after max retry")
4074
0
                            .tag("instance_id", instance_id_)
4075
0
                            .tag("packed_file_path", packed_file_path)
4076
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4077
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4078
0
                            .tag("changed_files", changed_files)
4079
0
                            .tag("attempt", attempt);
4080
0
                    ret = -1;
4081
0
                    break;
4082
0
                }
4083
0
                LOG_WARNING("packed file info update conflict, retrying")
4084
0
                        .tag("instance_id", instance_id_)
4085
0
                        .tag("packed_file_path", packed_file_path)
4086
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4087
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4088
0
                        .tag("changed_files", changed_files)
4089
0
                        .tag("attempt", attempt);
4090
0
                sleep_for_packed_file_retry();
4091
0
                continue;
4092
0
            }
4093
4094
0
            LOG_WARNING("failed to commit packed file info update")
4095
0
                    .tag("instance_id", instance_id_)
4096
0
                    .tag("packed_file_path", packed_file_path)
4097
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4098
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4099
0
                    .tag("err", err)
4100
0
                    .tag("changed_files", changed_files);
4101
0
            ret = -1;
4102
0
            break;
4103
0
        }
4104
4105
24
        if (!success) {
4106
0
            ret = -1;
4107
0
        }
4108
24
    }
4109
4110
18
    return ret;
4111
18
}
4112
4113
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4114
        int64_t tablet_id, const std::string& rowset_id,
4115
61.0k
        DeleteBitmapStorageType* out_storage_type) {
4116
61.0k
    if (out_storage_type) {
4117
58.5k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4118
58.5k
    }
4119
4120
    // Get delete bitmap storage info from FDB
4121
61.0k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4122
61.0k
    std::unique_ptr<Transaction> txn;
4123
61.0k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4124
61.0k
    if (err != TxnErrorCode::TXN_OK) {
4125
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4126
0
                .tag("instance_id", instance_id_)
4127
0
                .tag("tablet_id", tablet_id)
4128
0
                .tag("rowset_id", rowset_id)
4129
0
                .tag("err", err);
4130
0
        return -1;
4131
0
    }
4132
4133
61.0k
    ValueBuf dbm_val;
4134
61.0k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4135
61.0k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4136
        // No delete bitmap for this rowset, nothing to do
4137
6.23k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4138
6.23k
                .tag("instance_id", instance_id_)
4139
6.23k
                .tag("tablet_id", tablet_id)
4140
6.23k
                .tag("rowset_id", rowset_id);
4141
6.23k
        return 0;
4142
6.23k
    }
4143
54.8k
    if (err != TxnErrorCode::TXN_OK) {
4144
0
        LOG_WARNING("failed to get delete bitmap storage")
4145
0
                .tag("instance_id", instance_id_)
4146
0
                .tag("tablet_id", tablet_id)
4147
0
                .tag("rowset_id", rowset_id)
4148
0
                .tag("err", err);
4149
0
        return -1;
4150
0
    }
4151
4152
54.8k
    DeleteBitmapStoragePB storage;
4153
54.8k
    if (!dbm_val.to_pb(&storage)) {
4154
0
        LOG_WARNING("failed to parse delete bitmap storage")
4155
0
                .tag("instance_id", instance_id_)
4156
0
                .tag("tablet_id", tablet_id)
4157
0
                .tag("rowset_id", rowset_id);
4158
0
        return -1;
4159
0
    }
4160
4161
54.8k
    if (storage.store_in_fdb()) {
4162
0
        if (out_storage_type) {
4163
0
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4164
0
        }
4165
0
        return 0;
4166
0
    }
4167
4168
    // Check if delete bitmap is stored in standalone file.
4169
54.8k
    if (!storage.has_packed_slice_location() ||
4170
54.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4171
54.8k
        if (out_storage_type) {
4172
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4173
53.5k
        }
4174
54.8k
        return 0;
4175
54.8k
    }
4176
4177
18.4E
    if (out_storage_type) {
4178
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4179
0
    }
4180
4181
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4182
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4183
4184
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4185
18.4E
            .tag("instance_id", instance_id_)
4186
18.4E
            .tag("tablet_id", tablet_id)
4187
18.4E
            .tag("rowset_id", rowset_id)
4188
18.4E
            .tag("packed_file_path", packed_file_path);
4189
4190
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4191
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4192
1
        std::unique_ptr<Transaction> update_txn;
4193
1
        err = txn_kv_->create_txn(&update_txn);
4194
1
        if (err != TxnErrorCode::TXN_OK) {
4195
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4196
0
                    .tag("instance_id", instance_id_)
4197
0
                    .tag("tablet_id", tablet_id)
4198
0
                    .tag("rowset_id", rowset_id)
4199
0
                    .tag("err", err);
4200
0
            return -1;
4201
0
        }
4202
4203
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4204
1
        std::string packed_val;
4205
1
        err = update_txn->get(packed_key, &packed_val);
4206
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4207
0
            LOG_WARNING("packed file info not found for delete bitmap")
4208
0
                    .tag("instance_id", instance_id_)
4209
0
                    .tag("tablet_id", tablet_id)
4210
0
                    .tag("rowset_id", rowset_id)
4211
0
                    .tag("packed_file_path", packed_file_path);
4212
0
            return 0;
4213
0
        }
4214
1
        if (err != TxnErrorCode::TXN_OK) {
4215
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4216
0
                    .tag("instance_id", instance_id_)
4217
0
                    .tag("tablet_id", tablet_id)
4218
0
                    .tag("rowset_id", rowset_id)
4219
0
                    .tag("packed_file_path", packed_file_path)
4220
0
                    .tag("err", err);
4221
0
            return -1;
4222
0
        }
4223
4224
1
        cloud::PackedFileInfoPB packed_info;
4225
1
        if (!packed_info.ParseFromString(packed_val)) {
4226
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4227
0
                    .tag("instance_id", instance_id_)
4228
0
                    .tag("tablet_id", tablet_id)
4229
0
                    .tag("rowset_id", rowset_id)
4230
0
                    .tag("packed_file_path", packed_file_path);
4231
0
            return -1;
4232
0
        }
4233
4234
        // Find and mark the small file entry as deleted
4235
        // Use tablet_id and rowset_id to match entry instead of path,
4236
        // because path format may vary with path_version (with or without shard prefix)
4237
1
        auto* entries = packed_info.mutable_slices();
4238
1
        bool found = false;
4239
1
        bool already_deleted = false;
4240
1
        for (auto& entry : *entries) {
4241
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4242
1
                if (!entry.deleted()) {
4243
1
                    entry.set_deleted(true);
4244
1
                    if (!entry.corrected()) {
4245
1
                        entry.set_corrected(true);
4246
1
                    }
4247
1
                } else {
4248
0
                    already_deleted = true;
4249
0
                }
4250
1
                found = true;
4251
1
                break;
4252
1
            }
4253
1
        }
4254
4255
1
        if (!found) {
4256
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4257
0
                    .tag("instance_id", instance_id_)
4258
0
                    .tag("tablet_id", tablet_id)
4259
0
                    .tag("rowset_id", rowset_id)
4260
0
                    .tag("packed_file_path", packed_file_path);
4261
0
            return 0;
4262
0
        }
4263
4264
1
        if (already_deleted) {
4265
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4266
0
                    .tag("instance_id", instance_id_)
4267
0
                    .tag("tablet_id", tablet_id)
4268
0
                    .tag("rowset_id", rowset_id)
4269
0
                    .tag("packed_file_path", packed_file_path);
4270
0
            return 0;
4271
0
        }
4272
4273
        // Calculate remaining files
4274
1
        int64_t left_file_count = 0;
4275
1
        int64_t left_file_bytes = 0;
4276
1
        for (const auto& entry : packed_info.slices()) {
4277
1
            if (!entry.deleted()) {
4278
0
                ++left_file_count;
4279
0
                left_file_bytes += entry.size();
4280
0
            }
4281
1
        }
4282
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4283
1
        packed_info.set_ref_cnt(left_file_count);
4284
4285
1
        if (left_file_count == 0) {
4286
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4287
1
        }
4288
4289
1
        std::string updated_val;
4290
1
        if (!packed_info.SerializeToString(&updated_val)) {
4291
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4292
0
                    .tag("instance_id", instance_id_)
4293
0
                    .tag("tablet_id", tablet_id)
4294
0
                    .tag("rowset_id", rowset_id)
4295
0
                    .tag("packed_file_path", packed_file_path);
4296
0
            return -1;
4297
0
        }
4298
4299
1
        update_txn->put(packed_key, updated_val);
4300
1
        err = update_txn->commit();
4301
1
        if (err == TxnErrorCode::TXN_OK) {
4302
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4303
1
                    .tag("instance_id", instance_id_)
4304
1
                    .tag("tablet_id", tablet_id)
4305
1
                    .tag("rowset_id", rowset_id)
4306
1
                    .tag("packed_file_path", packed_file_path)
4307
1
                    .tag("left_file_count", left_file_count);
4308
1
            if (left_file_count == 0) {
4309
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4310
0
                    return -1;
4311
0
                }
4312
1
            }
4313
1
            return 0;
4314
1
        }
4315
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4316
0
            if (attempt >= max_retry_times) {
4317
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4318
0
                        .tag("instance_id", instance_id_)
4319
0
                        .tag("tablet_id", tablet_id)
4320
0
                        .tag("rowset_id", rowset_id)
4321
0
                        .tag("packed_file_path", packed_file_path)
4322
0
                        .tag("attempt", attempt);
4323
0
                return -1;
4324
0
            }
4325
0
            sleep_for_packed_file_retry();
4326
0
            continue;
4327
0
        }
4328
4329
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4330
0
                .tag("instance_id", instance_id_)
4331
0
                .tag("tablet_id", tablet_id)
4332
0
                .tag("rowset_id", rowset_id)
4333
0
                .tag("packed_file_path", packed_file_path)
4334
0
                .tag("err", err);
4335
0
        return -1;
4336
0
    }
4337
4338
18.4E
    return -1;
4339
18.4E
}
4340
4341
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4342
                                                const std::string& packed_key,
4343
8
                                                const cloud::PackedFileInfoPB& packed_info) {
4344
8
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4345
0
        LOG_WARNING("packed file missing resource id when recycling")
4346
0
                .tag("instance_id", instance_id_)
4347
0
                .tag("packed_file_path", packed_file_path);
4348
0
        return -1;
4349
0
    }
4350
4351
8
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4352
8
    if (!accessor) {
4353
0
        LOG_WARNING("no accessor available to delete packed file")
4354
0
                .tag("instance_id", instance_id_)
4355
0
                .tag("packed_file_path", packed_file_path)
4356
0
                .tag("resource_id", packed_info.resource_id());
4357
0
        return -1;
4358
0
    }
4359
4360
8
    int del_ret = accessor->delete_file(packed_file_path);
4361
8
    if (del_ret != 0 && del_ret != 1) {
4362
0
        LOG_WARNING("failed to delete packed file")
4363
0
                .tag("instance_id", instance_id_)
4364
0
                .tag("packed_file_path", packed_file_path)
4365
0
                .tag("resource_id", resource_id)
4366
0
                .tag("ret", del_ret);
4367
0
        return -1;
4368
0
    }
4369
8
    if (del_ret == 1) {
4370
0
        LOG_INFO("packed file already removed")
4371
0
                .tag("instance_id", instance_id_)
4372
0
                .tag("packed_file_path", packed_file_path)
4373
0
                .tag("resource_id", resource_id);
4374
8
    } else {
4375
8
        LOG_INFO("deleted packed file")
4376
8
                .tag("instance_id", instance_id_)
4377
8
                .tag("packed_file_path", packed_file_path)
4378
8
                .tag("resource_id", resource_id);
4379
8
    }
4380
4381
8
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4382
8
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4383
8
        std::unique_ptr<Transaction> del_txn;
4384
8
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4385
8
        if (err != TxnErrorCode::TXN_OK) {
4386
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4387
0
                    .tag("instance_id", instance_id_)
4388
0
                    .tag("packed_file_path", packed_file_path)
4389
0
                    .tag("attempt", attempt)
4390
0
                    .tag("err", err);
4391
0
            return -1;
4392
0
        }
4393
4394
8
        std::string latest_val;
4395
8
        err = del_txn->get(packed_key, &latest_val);
4396
8
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4397
0
            return 0;
4398
0
        }
4399
8
        if (err != TxnErrorCode::TXN_OK) {
4400
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4401
0
                    .tag("instance_id", instance_id_)
4402
0
                    .tag("packed_file_path", packed_file_path)
4403
0
                    .tag("attempt", attempt)
4404
0
                    .tag("err", err);
4405
0
            return -1;
4406
0
        }
4407
4408
8
        cloud::PackedFileInfoPB latest_info;
4409
8
        if (!latest_info.ParseFromString(latest_val)) {
4410
0
            LOG_WARNING("failed to parse packed file info before removal")
4411
0
                    .tag("instance_id", instance_id_)
4412
0
                    .tag("packed_file_path", packed_file_path)
4413
0
                    .tag("attempt", attempt);
4414
0
            return -1;
4415
0
        }
4416
4417
8
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4418
8
              latest_info.ref_cnt() == 0)) {
4419
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4420
0
                    .tag("instance_id", instance_id_)
4421
0
                    .tag("packed_file_path", packed_file_path)
4422
0
                    .tag("attempt", attempt);
4423
0
            return 0;
4424
0
        }
4425
4426
8
        del_txn->remove(packed_key);
4427
8
        err = del_txn->commit();
4428
8
        if (err == TxnErrorCode::TXN_OK) {
4429
8
            LOG_INFO("removed packed file metadata")
4430
8
                    .tag("instance_id", instance_id_)
4431
8
                    .tag("packed_file_path", packed_file_path);
4432
8
            return 0;
4433
8
        }
4434
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4435
0
            if (attempt >= max_retry_times) {
4436
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4437
0
                        .tag("instance_id", instance_id_)
4438
0
                        .tag("packed_file_path", packed_file_path)
4439
0
                        .tag("attempt", attempt);
4440
0
                return -1;
4441
0
            }
4442
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4443
0
                    .tag("instance_id", instance_id_)
4444
0
                    .tag("packed_file_path", packed_file_path)
4445
0
                    .tag("attempt", attempt);
4446
0
            sleep_for_packed_file_retry();
4447
0
            continue;
4448
0
        }
4449
0
        LOG_WARNING("failed to remove packed file kv")
4450
0
                .tag("instance_id", instance_id_)
4451
0
                .tag("packed_file_path", packed_file_path)
4452
0
                .tag("attempt", attempt)
4453
0
                .tag("err", err);
4454
0
        return -1;
4455
0
    }
4456
0
    return -1;
4457
8
}
4458
4459
int InstanceRecycler::delete_rowset_data(
4460
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4461
66
        RecyclerMetricsContext& metrics_context) {
4462
66
    int ret = 0;
4463
    // resource_id -> file_paths
4464
66
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4465
    // (resource_id, tablet_id, rowset_id)
4466
66
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4467
66
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4468
4469
56.4k
    for (const auto& [_, rs] : rowsets) {
4470
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4471
        // due to aborted schema change.
4472
56.4k
        if (is_formal_rowset) {
4473
3.19k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4474
                // Tablet has been recycled and this rowset has no packed slices, so file data
4475
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4476
                // slice info must still run to decrement packed file ref counts.
4477
0
                continue;
4478
0
            }
4479
3.19k
        }
4480
4481
56.4k
        int64_t num_segments = rs.num_segments();
4482
        // Check num_segments before accessor lookup, because empty rowsets
4483
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4484
        // set. Skipping them early avoids a spurious "no such resource id" error
4485
        // that marks the entire batch as failed and prevents txn_remove from
4486
        // cleaning up recycle KV keys.
4487
56.4k
        if (num_segments <= 0) {
4488
0
            metrics_context.total_recycled_num++;
4489
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4490
0
            continue;
4491
0
        }
4492
4493
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4494
        // possible if the accessor is not initilized correctly
4495
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4496
2.00k
            LOG_WARNING("instance has no such resource id")
4497
2.00k
                    .tag("instance_id", instance_id_)
4498
2.00k
                    .tag("resource_id", rs.resource_id());
4499
2.00k
            ret = -1;
4500
2.00k
            continue;
4501
2.00k
        }
4502
4503
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4504
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4505
54.4k
        int64_t tablet_id = rs.tablet_id();
4506
54.4k
        LOG_INFO("recycle rowset merge index size")
4507
54.4k
                .tag("instance_id", instance_id_)
4508
54.4k
                .tag("tablet_id", tablet_id)
4509
54.4k
                .tag("rowset_id", rowset_id)
4510
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4511
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4512
0
            ret = -1;
4513
0
            continue;
4514
0
        }
4515
4516
        // Process delete bitmap - check where it's stored.
4517
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4518
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
4519
54.4k
                                                           &delete_bitmap_storage_type) != 0) {
4520
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4521
0
                    .tag("instance_id", instance_id_)
4522
0
                    .tag("tablet_id", tablet_id)
4523
0
                    .tag("rowset_id", rowset_id);
4524
0
            ret = -1;
4525
0
            continue;
4526
0
        }
4527
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4528
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4529
51.5k
        }
4530
4531
        // Process inverted indexes
4532
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4533
        // default format as v1.
4534
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4535
54.4k
                                                            ? rs.inverted_index_storage_format()
4536
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4537
54.4k
        int inverted_index_get_ret = 0;
4538
54.4k
        if (rs.has_tablet_schema()) {
4539
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4540
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4541
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4542
53.5k
                }
4543
53.5k
            }
4544
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4545
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4546
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4547
26.5k
            }
4548
27.6k
        } else {
4549
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4550
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4551
0
                                "instance_id="
4552
0
                             << instance_id_ << " tablet_id=" << tablet_id
4553
0
                             << " rowset_id=" << rowset_id;
4554
0
                ret = -1;
4555
0
                continue;
4556
0
            }
4557
27.6k
            InvertedIndexInfo index_info;
4558
27.6k
            inverted_index_get_ret =
4559
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4560
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4561
27.6k
                                     &inverted_index_get_ret);
4562
27.6k
            if (inverted_index_get_ret == 0) {
4563
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4564
27.1k
                    index_format = index_info.first;
4565
27.1k
                }
4566
27.1k
                index_ids = index_info.second;
4567
27.1k
            } else if (inverted_index_get_ret == 1) {
4568
                // 1. Schema kv not found means tablet has been recycled
4569
                // Maybe some tablet recycle failed by some bugs
4570
                // We need to delete again to double check
4571
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4572
                // because we are uncertain about the inverted index information.
4573
                // If there are inverted indexes, some data might not be deleted,
4574
                // but this is acceptable as we have made our best effort to delete the data.
4575
503
                LOG_INFO(
4576
503
                        "delete rowset data schema kv not found, need to delete again to "
4577
503
                        "double "
4578
503
                        "check")
4579
503
                        .tag("instance_id", instance_id_)
4580
503
                        .tag("tablet_id", tablet_id)
4581
503
                        .tag("rowset", rs.ShortDebugString());
4582
                // Currently index_ids is guaranteed to be empty,
4583
                // but we clear it again here as a safeguard against future code changes
4584
                // that might cause index_ids to no longer be empty
4585
503
                index_format = InvertedIndexStorageFormatPB::V2;
4586
503
                index_ids.clear();
4587
18.4E
            } else {
4588
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4589
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4590
18.4E
                ret = -1;
4591
18.4E
                continue;
4592
18.4E
            }
4593
27.6k
        }
4594
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4595
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4596
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4597
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4598
10
            continue;
4599
10
        }
4600
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4601
270k
            auto segment_id = rowset_segment_id(rs, i);
4602
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4603
270k
                                             &file_paths);
4604
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4605
537k
                for (const auto& index_id : index_ids) {
4606
537k
                    add_file_to_delete_if_not_packed(
4607
537k
                            rs,
4608
537k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4609
537k
                                                   index_id.second),
4610
537k
                            &file_paths);
4611
537k
                }
4612
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4613
                // try to recycle inverted index v2 when get_ret == 1
4614
                // we treat schema not found as if it has a v2 format inverted index
4615
                // to reduce chance of data leakage
4616
2.50k
                if (inverted_index_get_ret == 1) {
4617
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4618
2.50k
                            .tag("instance_id", instance_id_)
4619
2.50k
                            .tag("inverted index v2 path",
4620
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4621
2.50k
                }
4622
2.50k
                add_file_to_delete_if_not_packed(
4623
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4624
2.50k
            }
4625
270k
        }
4626
54.4k
    }
4627
4628
66
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4629
66
                                                 "delete_rowset_data",
4630
66
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4630
6
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_0clERKi
Line
Count
Source
4630
57
                                                 [](const int& ret) { return ret != 0; });
4631
66
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4632
53
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
53
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
53
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
53
                                     &accessor_map_);
4638
53
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
53
            auto& accessor = accessor_map_[*rid];
4645
53
            int ret = accessor->delete_files(*paths);
4646
53
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
53
                std::set<std::string> deleted_rowset_id;
4651
4652
53
                std::for_each(paths->begin(), paths->end(),
4653
53
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
863k
                               this](const std::string& path) {
4655
863k
                                  std::vector<std::string> str;
4656
863k
                                  butil::SplitString(path, '/', &str);
4657
863k
                                  std::string rowset_id;
4658
863k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
859k
                                      rowset_id = str.back().substr(0, pos);
4660
859k
                                  } else {
4661
3.43k
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
3.43k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
3.43k
                                      return;
4666
3.43k
                                  }
4667
859k
                                  auto rs_meta = rowsets.find(rowset_id);
4668
859k
                                  if (rs_meta != rowsets.end() &&
4669
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4671
54.4k
                                      metrics_context.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4674
54.4k
                                              rs_meta->second.num_segments();
4675
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4676
54.4k
                                              rs_meta->second.total_disk_size();
4677
54.4k
                                      metrics_context.total_recycled_num++;
4678
54.4k
                                  }
4679
859k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4654
7
                               this](const std::string& path) {
4655
7
                                  std::vector<std::string> str;
4656
7
                                  butil::SplitString(path, '/', &str);
4657
7
                                  std::string rowset_id;
4658
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
7
                                      rowset_id = str.back().substr(0, pos);
4660
7
                                  } else {
4661
0
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
0
                                      return;
4666
0
                                  }
4667
7
                                  auto rs_meta = rowsets.find(rowset_id);
4668
7
                                  if (rs_meta != rowsets.end() &&
4669
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
7
                                      deleted_rowset_id.emplace(rowset_id);
4671
7
                                      metrics_context.total_recycled_data_size +=
4672
7
                                              rs_meta->second.total_disk_size();
4673
7
                                      segment_metrics_context_.total_recycled_num +=
4674
7
                                              rs_meta->second.num_segments();
4675
7
                                      segment_metrics_context_.total_recycled_data_size +=
4676
7
                                              rs_meta->second.total_disk_size();
4677
7
                                      metrics_context.total_recycled_num++;
4678
7
                                  }
4679
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEvENKUlRSD_E_clESN_
Line
Count
Source
4654
863k
                               this](const std::string& path) {
4655
863k
                                  std::vector<std::string> str;
4656
863k
                                  butil::SplitString(path, '/', &str);
4657
863k
                                  std::string rowset_id;
4658
863k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
859k
                                      rowset_id = str.back().substr(0, pos);
4660
859k
                                  } else {
4661
3.43k
                                      if (path.find("packed_file/") != std::string::npos) {
4662
0
                                          return; // packed files do not have rowset_id encoded
4663
0
                                      }
4664
3.43k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
3.43k
                                      return;
4666
3.43k
                                  }
4667
859k
                                  auto rs_meta = rowsets.find(rowset_id);
4668
859k
                                  if (rs_meta != rowsets.end() &&
4669
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4671
54.4k
                                      metrics_context.total_recycled_data_size +=
4672
54.4k
                                              rs_meta->second.total_disk_size();
4673
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4674
54.4k
                                              rs_meta->second.num_segments();
4675
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4676
54.4k
                                              rs_meta->second.total_disk_size();
4677
54.4k
                                      metrics_context.total_recycled_num++;
4678
54.4k
                                  }
4679
859k
                              });
4680
53
            }
4681
53
            return ret;
4682
53
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4632
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
6
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
6
                                     &accessor_map_);
4638
6
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
6
            auto& accessor = accessor_map_[*rid];
4645
6
            int ret = accessor->delete_files(*paths);
4646
6
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
6
                std::set<std::string> deleted_rowset_id;
4651
4652
6
                std::for_each(paths->begin(), paths->end(),
4653
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
6
                               this](const std::string& path) {
4655
6
                                  std::vector<std::string> str;
4656
6
                                  butil::SplitString(path, '/', &str);
4657
6
                                  std::string rowset_id;
4658
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
6
                                      rowset_id = str.back().substr(0, pos);
4660
6
                                  } else {
4661
6
                                      if (path.find("packed_file/") != std::string::npos) {
4662
6
                                          return; // packed files do not have rowset_id encoded
4663
6
                                      }
4664
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
6
                                      return;
4666
6
                                  }
4667
6
                                  auto rs_meta = rowsets.find(rowset_id);
4668
6
                                  if (rs_meta != rowsets.end() &&
4669
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
6
                                      deleted_rowset_id.emplace(rowset_id);
4671
6
                                      metrics_context.total_recycled_data_size +=
4672
6
                                              rs_meta->second.total_disk_size();
4673
6
                                      segment_metrics_context_.total_recycled_num +=
4674
6
                                              rs_meta->second.num_segments();
4675
6
                                      segment_metrics_context_.total_recycled_data_size +=
4676
6
                                              rs_meta->second.total_disk_size();
4677
6
                                      metrics_context.total_recycled_num++;
4678
6
                                  }
4679
6
                              });
4680
6
            }
4681
6
            return ret;
4682
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_1clEv
Line
Count
Source
4632
47
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4633
47
            DCHECK(accessor_map_.count(*rid))
4634
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4635
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4636
47
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4637
47
                                     &accessor_map_);
4638
47
            if (!accessor_map_.contains(*rid)) {
4639
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4640
0
                        .tag("resource_id", resource_id)
4641
0
                        .tag("instance_id", instance_id_);
4642
0
                return -1;
4643
0
            }
4644
47
            auto& accessor = accessor_map_[*rid];
4645
47
            int ret = accessor->delete_files(*paths);
4646
47
            if (!ret) {
4647
                // deduplication of different files with the same rowset id
4648
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4649
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4650
47
                std::set<std::string> deleted_rowset_id;
4651
4652
47
                std::for_each(paths->begin(), paths->end(),
4653
47
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4654
47
                               this](const std::string& path) {
4655
47
                                  std::vector<std::string> str;
4656
47
                                  butil::SplitString(path, '/', &str);
4657
47
                                  std::string rowset_id;
4658
47
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4659
47
                                      rowset_id = str.back().substr(0, pos);
4660
47
                                  } else {
4661
47
                                      if (path.find("packed_file/") != std::string::npos) {
4662
47
                                          return; // packed files do not have rowset_id encoded
4663
47
                                      }
4664
47
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4665
47
                                      return;
4666
47
                                  }
4667
47
                                  auto rs_meta = rowsets.find(rowset_id);
4668
47
                                  if (rs_meta != rowsets.end() &&
4669
47
                                      !deleted_rowset_id.contains(rowset_id)) {
4670
47
                                      deleted_rowset_id.emplace(rowset_id);
4671
47
                                      metrics_context.total_recycled_data_size +=
4672
47
                                              rs_meta->second.total_disk_size();
4673
47
                                      segment_metrics_context_.total_recycled_num +=
4674
47
                                              rs_meta->second.num_segments();
4675
47
                                      segment_metrics_context_.total_recycled_data_size +=
4676
47
                                              rs_meta->second.total_disk_size();
4677
47
                                      metrics_context.total_recycled_num++;
4678
47
                                  }
4679
47
                              });
4680
47
            }
4681
47
            return ret;
4682
47
        });
4683
53
    }
4684
66
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4685
10
        LOG_INFO(
4686
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4687
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4688
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4689
10
        concurrent_delete_executor.add([&]() -> int {
4690
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4691
10
            if (!ret) {
4692
10
                auto rs = rowsets.at(rowset_id);
4693
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4694
10
                metrics_context.total_recycled_num++;
4695
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4696
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4697
10
            }
4698
10
            return ret;
4699
10
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEENK3$_2clEv
Line
Count
Source
4689
10
        concurrent_delete_executor.add([&]() -> int {
4690
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4691
10
            if (!ret) {
4692
10
                auto rs = rowsets.at(rowset_id);
4693
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4694
10
                metrics_context.total_recycled_num++;
4695
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4696
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4697
10
            }
4698
10
            return ret;
4699
10
        });
4700
10
    }
4701
4702
66
    bool finished = true;
4703
66
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4704
66
    for (int r : rets) {
4705
63
        if (r != 0) {
4706
0
            ret = -1;
4707
0
            break;
4708
0
        }
4709
63
    }
4710
66
    ret = finished ? ret : -1;
4711
66
    return ret;
4712
66
}
4713
4714
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4715
3.58k
                                         const std::string& rowset_id) {
4716
3.58k
    auto it = accessor_map_.find(resource_id);
4717
3.58k
    if (it == accessor_map_.end()) {
4718
400
        LOG_WARNING("instance has no such resource id")
4719
400
                .tag("instance_id", instance_id_)
4720
400
                .tag("resource_id", resource_id)
4721
400
                .tag("tablet_id", tablet_id)
4722
400
                .tag("rowset_id", rowset_id);
4723
400
        return -1;
4724
400
    }
4725
3.18k
    auto& accessor = it->second;
4726
3.18k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4727
3.58k
}
4728
4729
58.7k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4730
58.7k
    std::lock_guard lock(recycled_tablets_mtx_);
4731
58.7k
    return recycled_tablets_.contains(tablet_id);
4732
58.7k
}
4733
4734
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4735
55.5k
                                                                int64_t tablet_id) {
4736
55.5k
    bool is_mow = true;
4737
55.5k
    if (partition_id != -1) {
4738
55.3k
        std::lock_guard lock(partition_mow_cache_mutex);
4739
55.3k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4740
            // cache hit
4741
1
            is_mow = it->second;
4742
1
            return is_mow ? 1 : 0;
4743
1
        }
4744
55.3k
    }
4745
4746
55.5k
    TabletIndexPB tablet_index;
4747
55.5k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4748
55.5k
    if (ret == 1) {
4749
        // maybe recycled
4750
55.5k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4751
55.5k
    }
4752
22
    if (ret != 0) {
4753
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4754
0
                     << ", tablet_id=" << tablet_id;
4755
0
        return ret;
4756
0
    }
4757
4758
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4759
    // obtaining its partition ID from the tablet index.
4760
22
    if (partition_id == -1) {
4761
0
        partition_id = tablet_index.partition_id();
4762
0
        std::lock_guard lock(partition_mow_cache_mutex);
4763
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4764
0
            is_mow = it->second;
4765
0
            return is_mow ? 1 : 0;
4766
0
        }
4767
0
    }
4768
4769
22
    std::string tablet_meta_key =
4770
22
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4771
22
                             partition_id, tablet_id});
4772
22
    std::string tablet_meta_value;
4773
22
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4774
22
    if (ret == 1) {
4775
        // maybe recycled
4776
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4777
10
    }
4778
12
    if (ret != 0) {
4779
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4780
0
                     << ", tablet_id=" << tablet_id;
4781
0
        return ret;
4782
0
    }
4783
4784
12
    TabletMetaCloudPB tablet_meta;
4785
12
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4786
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4787
0
                     << ", tablet_id=" << tablet_id;
4788
0
        return -1;
4789
0
    }
4790
    // The row-binlog companion of a MoW data tablet stores versioned delete bitmaps copied from
4791
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4792
    // false value as the MoW state of the whole partition.
4793
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isRowBinlogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4794
12
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_ROW_BINLOG) {
4795
1
        return 1;
4796
1
    }
4797
11
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4798
11
    std::lock_guard lock(partition_mow_cache_mutex);
4799
11
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4800
11
    return it->second ? 1 : 0;
4801
12
}
4802
4803
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4804
55.5k
                                                         const std::string& rowset_id) {
4805
55.5k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4806
55.5k
    if (ret <= 0) {
4807
1.00k
        return ret;
4808
1.00k
    }
4809
4810
54.5k
    std::string dbm_start_key =
4811
54.5k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4812
54.5k
    std::string dbm_end_key = dbm_start_key;
4813
54.5k
    encode_int64(INT64_MAX, &dbm_end_key);
4814
54.5k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4815
54.5k
    if (ret != 0) {
4816
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_;
4817
0
    }
4818
54.5k
    return ret;
4819
55.5k
}
4820
4821
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4822
51.2k
    std::string delete_bitmap_start =
4823
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4824
51.2k
    std::string delete_bitmap_end =
4825
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4826
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4827
51.2k
    if (ret != 0) {
4828
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4829
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4830
0
    }
4831
51.2k
    return ret;
4832
51.2k
}
4833
4834
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4835
4
    if (key.empty()) {
4836
0
        return false;
4837
0
    }
4838
4
    std::string_view key_view = key;
4839
4
    key_view.remove_prefix(1); // remove keyspace prefix
4840
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4841
4
    if (decode_key(&key_view, &decoded) != 0) {
4842
0
        return false;
4843
0
    }
4844
4
    if (decoded.size() < 4) {
4845
0
        return false;
4846
0
    }
4847
4
    try {
4848
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4849
4
    } catch (const std::bad_variant_access&) {
4850
0
        return false;
4851
0
    }
4852
4
    return true;
4853
4
}
4854
4855
14
int InstanceRecycler::recycle_packed_files() {
4856
14
    const std::string task_name = "recycle_packed_files";
4857
14
    auto start_tp = steady_clock::now();
4858
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4859
14
    int ret = 0;
4860
14
    PackedFileRecycleStats stats;
4861
4862
14
    register_recycle_task(task_name, start_time);
4863
14
    DORIS_CLOUD_DEFER {
4864
14
        unregister_recycle_task(task_name);
4865
14
        int64_t cost =
4866
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4867
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4868
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4869
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4870
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4871
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4872
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4873
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4874
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4875
14
                                                             stats.bytes_object_deleted);
4876
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4877
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4878
14
                .tag("instance_id", instance_id_)
4879
14
                .tag("num_scanned", stats.num_scanned)
4880
14
                .tag("num_corrected", stats.num_corrected)
4881
14
                .tag("num_deleted", stats.num_deleted)
4882
14
                .tag("num_failed", stats.num_failed)
4883
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4884
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4885
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4886
14
                .tag("bytes_deleted", stats.bytes_deleted)
4887
14
                .tag("ret", ret);
4888
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4863
14
    DORIS_CLOUD_DEFER {
4864
14
        unregister_recycle_task(task_name);
4865
14
        int64_t cost =
4866
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4867
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4868
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4869
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4870
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4871
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4872
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4873
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4874
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4875
14
                                                             stats.bytes_object_deleted);
4876
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4877
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4878
14
                .tag("instance_id", instance_id_)
4879
14
                .tag("num_scanned", stats.num_scanned)
4880
14
                .tag("num_corrected", stats.num_corrected)
4881
14
                .tag("num_deleted", stats.num_deleted)
4882
14
                .tag("num_failed", stats.num_failed)
4883
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4884
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4885
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4886
14
                .tag("bytes_deleted", stats.bytes_deleted)
4887
14
                .tag("ret", ret);
4888
14
    };
4889
4890
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4891
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4892
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4893
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
4890
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4891
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4892
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4893
4
    };
4894
4895
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4896
4897
14
    std::string begin = packed_file_key({instance_id_, ""});
4898
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4899
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4900
0
        ret = -1;
4901
0
    }
4902
4903
14
    return ret;
4904
14
}
4905
4906
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4907
                                                  RecyclerMetricsContext& metrics_context,
4908
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4909
0
    std::string tablet_key_begin, tablet_key_end;
4910
4911
0
    if (partition_id > 0) {
4912
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4913
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4914
0
    } else {
4915
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4916
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4917
0
    }
4918
    // for calculate the total num or bytes of recyled objects
4919
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4920
0
                                                          std::string_view v) -> int {
4921
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4922
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4923
0
            return 0;
4924
0
        }
4925
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4926
4927
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4928
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4929
0
            return 0;
4930
0
        }
4931
4932
0
        if (!is_empty_tablet) {
4933
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4934
0
                return 0;
4935
0
            }
4936
0
            tablet_metrics_context_.total_need_recycle_num++;
4937
0
        }
4938
0
        return 0;
4939
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_
4940
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4941
0
    metrics_context.report(true);
4942
0
    tablet_metrics_context_.report(true);
4943
0
    segment_metrics_context_.report(true);
4944
0
    return ret;
4945
0
}
4946
4947
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4948
0
                                                 RecyclerMetricsContext& metrics_context) {
4949
0
    int ret = 0;
4950
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4951
0
    std::unique_ptr<Transaction> txn;
4952
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4953
0
        LOG_WARNING("failed to recycle tablet ")
4954
0
                .tag("tablet id", tablet_id)
4955
0
                .tag("instance_id", instance_id_)
4956
0
                .tag("reason", "failed to create txn");
4957
0
        ret = -1;
4958
0
    }
4959
0
    GetRowsetResponse resp;
4960
0
    std::string msg;
4961
0
    MetaServiceCode code = MetaServiceCode::OK;
4962
    // get rowsets in tablet
4963
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4964
0
                        tablet_id, code, msg, &resp);
4965
0
    if (code != MetaServiceCode::OK) {
4966
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4967
0
                .tag("tablet id", tablet_id)
4968
0
                .tag("msg", msg)
4969
0
                .tag("code", code)
4970
0
                .tag("instance id", instance_id_);
4971
0
        ret = -1;
4972
0
    }
4973
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4974
        /*
4975
        * For compatibility, we skip the loop for [0-1] here.
4976
        * The purpose of this loop is to delete object files,
4977
        * and since [0-1] only has meta and doesn't have object files,
4978
        * skipping it doesn't affect system correctness.
4979
        *
4980
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4981
        * would return error -1 directly, causing the recycle operation to fail.
4982
        *
4983
        * [0-1] doesn't have resource id is a bug.
4984
        * In the future, we will fix this problem, after that,
4985
        * we can remove this if statement.
4986
        *
4987
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4988
        */
4989
4990
0
        if (rs_meta.end_version() == 1) {
4991
            // Assert that [0-1] has no resource_id to make sure
4992
            // this if statement will not be forgetted to remove
4993
            // when the resource id bug is fixed
4994
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4995
0
            continue;
4996
0
        }
4997
0
        if (!rs_meta.has_resource_id()) {
4998
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4999
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5000
0
                    .tag("instance_id", instance_id_)
5001
0
                    .tag("tablet_id", tablet_id);
5002
0
            continue;
5003
0
        }
5004
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5005
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5006
        // possible if the accessor is not initilized correctly
5007
0
        if (it == accessor_map_.end()) [[unlikely]] {
5008
0
            LOG_WARNING(
5009
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5010
0
                    "recycle process")
5011
0
                    .tag("tablet id", tablet_id)
5012
0
                    .tag("instance_id", instance_id_)
5013
0
                    .tag("resource_id", rs_meta.resource_id())
5014
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5015
0
            continue;
5016
0
        }
5017
5018
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
5019
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5020
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5021
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
5022
0
    }
5023
0
    return ret;
5024
0
}
5025
5026
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5027
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5028
4.26k
            .tag("instance_id", instance_id_)
5029
4.26k
            .tag("tablet_id", tablet_id);
5030
5031
4.26k
    if (should_recycle_versioned_keys()) {
5032
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5033
14
        if (ret != 0) {
5034
0
            return ret;
5035
0
        }
5036
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5037
        // during the recycle_versioned_tablet process.
5038
        //
5039
        // .. And remove restore job rowsets of this tablet too
5040
14
    }
5041
5042
4.26k
    int ret = 0;
5043
4.26k
    auto start_time = steady_clock::now();
5044
5045
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5046
5047
    // collect resource ids
5048
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5049
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5050
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5051
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5052
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5053
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5054
5055
260
    std::set<std::string> resource_ids;
5056
260
    int64_t recycle_rowsets_number = 0;
5057
260
    int64_t recycle_segments_number = 0;
5058
260
    int64_t recycle_rowsets_data_size = 0;
5059
260
    int64_t recycle_rowsets_index_size = 0;
5060
260
    int64_t recycle_restore_job_rowsets_number = 0;
5061
260
    int64_t recycle_restore_job_segments_number = 0;
5062
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
5063
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
5064
260
    int64_t max_rowset_version = 0;
5065
260
    int64_t min_rowset_creation_time = INT64_MAX;
5066
260
    int64_t max_rowset_creation_time = 0;
5067
260
    int64_t min_rowset_expiration_time = INT64_MAX;
5068
260
    int64_t max_rowset_expiration_time = 0;
5069
5070
260
    DORIS_CLOUD_DEFER {
5071
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5072
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5073
260
                .tag("instance_id", instance_id_)
5074
260
                .tag("tablet_id", tablet_id)
5075
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5076
260
                .tag("recycle segments number", recycle_segments_number)
5077
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5078
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5079
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5080
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5081
260
                .tag("all restore job rowsets recycle data size",
5082
260
                     recycle_restore_job_rowsets_data_size)
5083
260
                .tag("all restore job rowsets recycle index size",
5084
260
                     recycle_restore_job_rowsets_index_size)
5085
260
                .tag("max rowset version", max_rowset_version)
5086
260
                .tag("min rowset creation time", min_rowset_creation_time)
5087
260
                .tag("max rowset creation time", max_rowset_creation_time)
5088
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5089
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5090
260
                .tag("task type", metrics_context.operation_type)
5091
260
                .tag("ret", ret);
5092
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5070
260
    DORIS_CLOUD_DEFER {
5071
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5072
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5073
260
                .tag("instance_id", instance_id_)
5074
260
                .tag("tablet_id", tablet_id)
5075
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5076
260
                .tag("recycle segments number", recycle_segments_number)
5077
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5078
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5079
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5080
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5081
260
                .tag("all restore job rowsets recycle data size",
5082
260
                     recycle_restore_job_rowsets_data_size)
5083
260
                .tag("all restore job rowsets recycle index size",
5084
260
                     recycle_restore_job_rowsets_index_size)
5085
260
                .tag("max rowset version", max_rowset_version)
5086
260
                .tag("min rowset creation time", min_rowset_creation_time)
5087
260
                .tag("max rowset creation time", max_rowset_creation_time)
5088
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5089
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5090
260
                .tag("task type", metrics_context.operation_type)
5091
260
                .tag("ret", ret);
5092
260
    };
5093
5094
260
    std::unique_ptr<Transaction> txn;
5095
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5096
0
        LOG_WARNING("failed to recycle tablet ")
5097
0
                .tag("tablet id", tablet_id)
5098
0
                .tag("instance_id", instance_id_)
5099
0
                .tag("reason", "failed to create txn");
5100
0
        ret = -1;
5101
0
    }
5102
260
    GetRowsetResponse resp;
5103
260
    std::string msg;
5104
260
    MetaServiceCode code = MetaServiceCode::OK;
5105
    // get rowsets in tablet
5106
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5107
260
                        tablet_id, code, msg, &resp);
5108
260
    if (code != MetaServiceCode::OK) {
5109
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5110
0
                .tag("tablet id", tablet_id)
5111
0
                .tag("msg", msg)
5112
0
                .tag("code", code)
5113
0
                .tag("instance id", instance_id_);
5114
0
        ret = -1;
5115
0
    }
5116
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5117
5118
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5119
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5120
3
            if (rs_meta.num_segments() <= 0) {
5121
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5122
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5123
2
                        .tag("instance_id", instance_id_)
5124
2
                        .tag("tablet_id", tablet_id);
5125
2
                recycle_rowsets_number += 1;
5126
2
                continue;
5127
2
            }
5128
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5129
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5130
1
                    .tag("instance_id", instance_id_)
5131
1
                    .tag("tablet_id", tablet_id);
5132
1
            return -1;
5133
3
        }
5134
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5135
2
                << "rs_meta" << rs_meta.ShortDebugString();
5136
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5137
        // possible if the accessor is not initilized correctly
5138
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5139
1
            LOG_WARNING(
5140
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5141
1
                    "recycle process")
5142
1
                    .tag("tablet id", tablet_id)
5143
1
                    .tag("instance_id", instance_id_)
5144
1
                    .tag("resource_id", rs_meta.resource_id())
5145
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5146
1
            return -1;
5147
1
        }
5148
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5149
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5150
0
                    .tag("instance_id", instance_id_)
5151
0
                    .tag("tablet_id", tablet_id)
5152
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5153
0
            return -1;
5154
0
        }
5155
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5156
2.54k
                                                           nullptr) != 0) {
5157
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5158
0
                    .tag("instance_id", instance_id_)
5159
0
                    .tag("tablet_id", tablet_id)
5160
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5161
0
            return -1;
5162
0
        }
5163
2.54k
        recycle_rowsets_number += 1;
5164
2.54k
        recycle_segments_number += rs_meta.num_segments();
5165
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5166
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5167
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5168
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5169
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5170
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5171
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5172
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5173
2.54k
    }
5174
5175
    // get restore job rowset in tablet
5176
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5177
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5178
258
    if (code != MetaServiceCode::OK) {
5179
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5180
0
                .tag("tablet id", tablet_id)
5181
0
                .tag("msg", msg)
5182
0
                .tag("code", code)
5183
0
                .tag("instance id", instance_id_);
5184
0
        return -1;
5185
0
    }
5186
5187
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5188
0
        if (!rs_meta.has_resource_id()) {
5189
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5190
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5191
0
                    .tag("instance_id", instance_id_)
5192
0
                    .tag("tablet_id", tablet_id);
5193
0
            return -1;
5194
0
        }
5195
5196
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5197
        // possible if the accessor is not initilized correctly
5198
0
        if (it == accessor_map_.end()) [[unlikely]] {
5199
0
            LOG_WARNING(
5200
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5201
0
                    "recycle process")
5202
0
                    .tag("tablet id", tablet_id)
5203
0
                    .tag("instance_id", instance_id_)
5204
0
                    .tag("resource_id", rs_meta.resource_id())
5205
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5206
0
            return -1;
5207
0
        }
5208
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5209
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5210
0
                    .tag("instance_id", instance_id_)
5211
0
                    .tag("tablet_id", tablet_id)
5212
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5213
0
            return -1;
5214
0
        }
5215
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5216
0
                                                           nullptr) != 0) {
5217
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5218
0
                    .tag("instance_id", instance_id_)
5219
0
                    .tag("tablet_id", tablet_id)
5220
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5221
0
            return -1;
5222
0
        }
5223
0
        recycle_restore_job_rowsets_number += 1;
5224
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5225
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5226
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5227
0
        resource_ids.emplace(rs_meta.resource_id());
5228
0
    }
5229
5230
258
    LOG_INFO("recycle tablet start to delete object")
5231
258
            .tag("instance id", instance_id_)
5232
258
            .tag("tablet id", tablet_id)
5233
258
            .tag("recycle tablet resource ids are",
5234
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5235
258
                                 [](std::string rs_id, const auto& it) {
5236
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5237
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
5235
217
                                 [](std::string rs_id, const auto& it) {
5236
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5237
217
                                 }));
5238
5239
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5240
258
            _thread_pool_group.s3_producer_pool,
5241
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5242
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
5242
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5243
5244
    // delete all rowset data in this tablet
5245
    // ATTN: there may be data leak if not all accessor initilized successfully
5246
    //       partial data deleted if the tablet is stored cross-storage vault
5247
    //       vault id is not attached to TabletMeta...
5248
258
    for (const auto& resource_id : resource_ids) {
5249
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5250
217
        concurrent_delete_executor.add(
5251
217
                [&, rs_id = resource_id,
5252
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5253
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5254
217
                    if (res != 0) {
5255
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5256
3
                                     << " path=" << accessor_ptr->uri()
5257
3
                                     << " task type=" << metrics_context.operation_type;
5258
3
                        return std::make_pair(-1, rs_id);
5259
3
                    }
5260
214
                    return std::make_pair(0, rs_id);
5261
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5252
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5253
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5254
217
                    if (res != 0) {
5255
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5256
3
                                     << " path=" << accessor_ptr->uri()
5257
3
                                     << " task type=" << metrics_context.operation_type;
5258
3
                        return std::make_pair(-1, rs_id);
5259
3
                    }
5260
214
                    return std::make_pair(0, rs_id);
5261
217
                });
5262
217
    }
5263
5264
258
    bool finished = true;
5265
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5266
258
    for (auto& r : rets) {
5267
217
        if (r.first != 0) {
5268
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5269
3
            ret = -1;
5270
3
        }
5271
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5272
217
    }
5273
258
    ret = finished ? ret : -1;
5274
5275
258
    if (ret != 0) { // failed recycle tablet data
5276
3
        LOG_WARNING("ret!=0")
5277
3
                .tag("finished", finished)
5278
3
                .tag("ret", ret)
5279
3
                .tag("instance_id", instance_id_)
5280
3
                .tag("tablet_id", tablet_id);
5281
3
        return ret;
5282
3
    }
5283
5284
255
    tablet_metrics_context_.total_recycled_data_size +=
5285
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5286
255
    tablet_metrics_context_.total_recycled_num += 1;
5287
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5288
255
    segment_metrics_context_.total_recycled_data_size +=
5289
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5290
255
    metrics_context.total_recycled_data_size +=
5291
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5292
255
    tablet_metrics_context_.report();
5293
255
    segment_metrics_context_.report();
5294
255
    metrics_context.report();
5295
5296
255
    txn.reset();
5297
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5298
0
        LOG_WARNING("failed to recycle tablet ")
5299
0
                .tag("tablet id", tablet_id)
5300
0
                .tag("instance_id", instance_id_)
5301
0
                .tag("reason", "failed to create txn");
5302
0
        ret = -1;
5303
0
    }
5304
    // delete all rowset kv in this tablet
5305
255
    txn->remove(rs_key0, rs_key1);
5306
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5307
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5308
5309
    // remove delete bitmap for MoW table
5310
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5311
255
    txn->remove(pending_key);
5312
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5313
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5314
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5315
5316
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5317
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5318
255
    txn->remove(dbm_start_key, dbm_end_key);
5319
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5320
255
              << " end=" << hex(dbm_end_key);
5321
5322
255
    TxnErrorCode err = txn->commit();
5323
255
    if (err != TxnErrorCode::TXN_OK) {
5324
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5325
0
        ret = -1;
5326
0
    }
5327
5328
255
    if (ret == 0) {
5329
        // All object files under tablet have been deleted
5330
255
        std::lock_guard lock(recycled_tablets_mtx_);
5331
255
        recycled_tablets_.insert(tablet_id);
5332
255
    }
5333
5334
255
    return ret;
5335
258
}
5336
5337
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5338
14
                                               RecyclerMetricsContext& metrics_context) {
5339
14
    int ret = 0;
5340
14
    auto start_time = steady_clock::now();
5341
5342
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5343
5344
    // collect resource ids
5345
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5346
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5347
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5348
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5349
5350
11
    int64_t recycle_rowsets_number = 0;
5351
11
    int64_t recycle_segments_number = 0;
5352
11
    int64_t recycle_rowsets_data_size = 0;
5353
11
    int64_t recycle_rowsets_index_size = 0;
5354
11
    int64_t max_rowset_version = 0;
5355
11
    int64_t min_rowset_creation_time = INT64_MAX;
5356
11
    int64_t max_rowset_creation_time = 0;
5357
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5358
11
    int64_t max_rowset_expiration_time = 0;
5359
5360
11
    DORIS_CLOUD_DEFER {
5361
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5362
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5363
11
                .tag("instance_id", instance_id_)
5364
11
                .tag("tablet_id", tablet_id)
5365
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5366
11
                .tag("recycle segments number", recycle_segments_number)
5367
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5368
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5369
11
                .tag("max rowset version", max_rowset_version)
5370
11
                .tag("min rowset creation time", min_rowset_creation_time)
5371
11
                .tag("max rowset creation time", max_rowset_creation_time)
5372
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5373
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5374
11
                .tag("ret", ret);
5375
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5360
11
    DORIS_CLOUD_DEFER {
5361
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5362
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5363
11
                .tag("instance_id", instance_id_)
5364
11
                .tag("tablet_id", tablet_id)
5365
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5366
11
                .tag("recycle segments number", recycle_segments_number)
5367
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5368
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5369
11
                .tag("max rowset version", max_rowset_version)
5370
11
                .tag("min rowset creation time", min_rowset_creation_time)
5371
11
                .tag("max rowset creation time", max_rowset_creation_time)
5372
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5373
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5374
11
                .tag("ret", ret);
5375
11
    };
5376
5377
11
    std::unique_ptr<Transaction> txn;
5378
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5379
0
        LOG_WARNING("failed to recycle tablet ")
5380
0
                .tag("tablet id", tablet_id)
5381
0
                .tag("instance_id", instance_id_)
5382
0
                .tag("reason", "failed to create txn");
5383
0
        ret = -1;
5384
0
    }
5385
5386
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5387
    // by the related operation logs.
5388
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5389
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5390
11
    MetaReader meta_reader(instance_id_);
5391
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5392
11
    if (err == TxnErrorCode::TXN_OK) {
5393
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5394
11
    }
5395
11
    if (err != TxnErrorCode::TXN_OK) {
5396
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5397
0
                .tag("tablet id", tablet_id)
5398
0
                .tag("err", err)
5399
0
                .tag("instance id", instance_id_);
5400
0
        ret = -1;
5401
0
    }
5402
5403
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5404
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5405
11
            .tag("instance_id", instance_id_)
5406
11
            .tag("tablet_id", tablet_id);
5407
5408
11
    SyncExecutor<int> concurrent_delete_executor(
5409
11
            _thread_pool_group.s3_producer_pool,
5410
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5411
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
5412
5413
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5414
60
        recycle_rowsets_number += 1;
5415
60
        recycle_segments_number += rs_meta.num_segments();
5416
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5417
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5418
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5419
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5420
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5421
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5422
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5423
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5413
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5414
60
        recycle_rowsets_number += 1;
5415
60
        recycle_segments_number += rs_meta.num_segments();
5416
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5417
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5418
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5419
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5420
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5421
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5422
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5423
60
    };
5424
5425
11
    std::vector<RowsetDeleteTask> all_tasks;
5426
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5427
60
        update_rowset_stats(rs_meta);
5428
        // Version 0-1 rowset has no resource_id and no actual data files,
5429
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5430
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5431
60
        RowsetDeleteTask task;
5432
60
        task.rowset_meta = rs_meta;
5433
60
        task.versioned_rowset_key =
5434
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5435
60
        task.non_versioned_rowset_key =
5436
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5437
60
        task.versionstamp = versionstamp;
5438
60
        all_tasks.push_back(std::move(task));
5439
60
    }
5440
5441
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5442
0
        update_rowset_stats(rs_meta);
5443
        // Version 0-1 rowset has no resource_id and no actual data files,
5444
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5445
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5446
0
        RowsetDeleteTask task;
5447
0
        task.rowset_meta = rs_meta;
5448
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5449
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5450
0
        task.non_versioned_rowset_key =
5451
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5452
0
        task.versionstamp = versionstamp;
5453
0
        all_tasks.push_back(std::move(task));
5454
0
    }
5455
5456
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5457
0
        RecycleRowsetPB recycle_rowset;
5458
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5459
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5460
0
            return -1;
5461
0
        }
5462
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5463
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5464
                // in old version, keep this key-value pair and it needs to be checked manually
5465
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5466
0
                return -1;
5467
0
            }
5468
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5469
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5470
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5471
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5472
0
                return -1;
5473
0
            }
5474
            // decode rowset_id
5475
0
            auto k1 = k;
5476
0
            k1.remove_prefix(1);
5477
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5478
0
            decode_key(&k1, &out);
5479
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5480
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5481
0
            LOG_INFO("delete old-version rowset data")
5482
0
                    .tag("instance_id", instance_id_)
5483
0
                    .tag("tablet_id", tablet_id)
5484
0
                    .tag("rowset_id", rowset_id);
5485
5486
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5487
            // so we must use prefix deletion directly instead of batch delete.
5488
0
            concurrent_delete_executor.add(
5489
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5490
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5491
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5492
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
5493
0
        } else {
5494
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5495
            // Version 0-1 rowset has no resource_id and no actual data files,
5496
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5497
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5498
0
            RowsetDeleteTask task;
5499
0
            task.rowset_meta = rowset_meta;
5500
0
            task.recycle_rowset_key = k;
5501
0
            all_tasks.push_back(std::move(task));
5502
0
        }
5503
0
        return 0;
5504
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
5505
5506
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5507
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5508
0
                .tag("tablet id", tablet_id)
5509
0
                .tag("instance_id", instance_id_)
5510
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5511
0
        ret = -1;
5512
0
    }
5513
5514
    // Phase 1: Classify tasks by ref_count
5515
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5516
60
    for (auto& task : all_tasks) {
5517
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5518
60
        if (classify_ret < 0) {
5519
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5520
0
                    .tag("instance_id", instance_id_)
5521
0
                    .tag("tablet_id", tablet_id)
5522
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5523
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5524
0
                return recycle_rowset_meta_and_data(t);
5525
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5526
0
        }
5527
60
    }
5528
5529
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5530
5531
11
    LOG_INFO("batch delete plan created")
5532
11
            .tag("instance_id", instance_id_)
5533
11
            .tag("tablet_id", tablet_id)
5534
11
            .tag("plan_count", batch_delete_tasks.size());
5535
5536
    // Phase 2: Execute batch delete using existing delete_rowset_data
5537
11
    if (!batch_delete_tasks.empty()) {
5538
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5539
49
        for (const auto& task : batch_delete_tasks) {
5540
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5541
49
            if (task.rowset_meta.resource_id().empty()) {
5542
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5543
10
                        .tag("instance_id", instance_id_)
5544
10
                        .tag("tablet_id", tablet_id)
5545
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5546
10
                continue;
5547
10
            }
5548
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5549
39
        }
5550
5551
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5552
10
        bool delete_success = true;
5553
10
        if (!rowsets_to_delete.empty()) {
5554
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5555
9
                                                         "batch_delete_versioned_tablet");
5556
9
            int delete_ret = delete_rowset_data(
5557
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5558
9
            if (delete_ret != 0) {
5559
0
                LOG_WARNING("batch delete execution failed")
5560
0
                        .tag("instance_id", instance_id_)
5561
0
                        .tag("tablet_id", tablet_id);
5562
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5563
0
                ret = -1;
5564
0
                delete_success = false;
5565
0
            }
5566
9
        }
5567
5568
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5569
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5570
10
        if (delete_success) {
5571
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5572
10
            if (cleanup_ret != 0) {
5573
0
                LOG_WARNING("batch delete cleanup failed")
5574
0
                        .tag("instance_id", instance_id_)
5575
0
                        .tag("tablet_id", tablet_id);
5576
0
                ret = -1;
5577
0
            }
5578
10
        }
5579
10
    }
5580
5581
    // Always wait for fallback tasks to complete before returning
5582
11
    bool finished = true;
5583
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5584
11
    for (int r : rets) {
5585
0
        if (r != 0) {
5586
0
            ret = -1;
5587
0
        }
5588
0
    }
5589
5590
11
    ret = finished ? ret : -1;
5591
5592
11
    if (ret != 0) { // failed recycle tablet data
5593
0
        LOG_WARNING("recycle versioned tablet failed")
5594
0
                .tag("finished", finished)
5595
0
                .tag("ret", ret)
5596
0
                .tag("instance_id", instance_id_)
5597
0
                .tag("tablet_id", tablet_id);
5598
0
        return ret;
5599
0
    }
5600
5601
11
    tablet_metrics_context_.total_recycled_data_size +=
5602
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5603
11
    tablet_metrics_context_.total_recycled_num += 1;
5604
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5605
11
    segment_metrics_context_.total_recycled_data_size +=
5606
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5607
11
    metrics_context.total_recycled_data_size +=
5608
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5609
11
    tablet_metrics_context_.report();
5610
11
    segment_metrics_context_.report();
5611
11
    metrics_context.report();
5612
5613
11
    txn.reset();
5614
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5615
0
        LOG_WARNING("failed to recycle tablet ")
5616
0
                .tag("tablet id", tablet_id)
5617
0
                .tag("instance_id", instance_id_)
5618
0
                .tag("reason", "failed to create txn");
5619
0
        ret = -1;
5620
0
    }
5621
    // delete all rowset kv in this tablet
5622
11
    txn->remove(rs_key0, rs_key1);
5623
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5624
5625
    // remove delete bitmap for MoW table
5626
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5627
11
    txn->remove(pending_key);
5628
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5629
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5630
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5631
5632
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5633
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5634
11
    txn->remove(dbm_start_key, dbm_end_key);
5635
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5636
11
              << " end=" << hex(dbm_end_key);
5637
5638
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5639
11
    std::string tablet_index_val;
5640
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5641
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5642
0
        LOG_WARNING("failed to get tablet index kv")
5643
0
                .tag("instance_id", instance_id_)
5644
0
                .tag("tablet_id", tablet_id)
5645
0
                .tag("err", err);
5646
0
        ret = -1;
5647
11
    } else if (err == TxnErrorCode::TXN_OK) {
5648
        // If the tablet index kv exists, we need to delete it
5649
10
        TabletIndexPB tablet_index_pb;
5650
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5651
0
            LOG_WARNING("failed to parse tablet index pb")
5652
0
                    .tag("instance_id", instance_id_)
5653
0
                    .tag("tablet_id", tablet_id);
5654
0
            ret = -1;
5655
10
        } else {
5656
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5657
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5658
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5659
10
            txn->remove(versioned_inverted_idx_key);
5660
10
            txn->remove(versioned_idx_key);
5661
10
        }
5662
10
    }
5663
5664
11
    err = txn->commit();
5665
11
    if (err != TxnErrorCode::TXN_OK) {
5666
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5667
0
        ret = -1;
5668
0
    }
5669
5670
11
    if (ret == 0) {
5671
        // All object files under tablet have been deleted
5672
11
        std::lock_guard lock(recycled_tablets_mtx_);
5673
11
        recycled_tablets_.insert(tablet_id);
5674
11
    }
5675
5676
11
    return ret;
5677
11
}
5678
5679
87
int InstanceRecycler::recycle_rowsets() {
5680
87
    if (should_recycle_versioned_keys()) {
5681
5
        return recycle_versioned_rowsets();
5682
5
    }
5683
5684
82
    const std::string task_name = "recycle_rowsets";
5685
82
    int64_t num_scanned = 0;
5686
82
    int64_t num_expired = 0;
5687
82
    int64_t num_prepare = 0;
5688
82
    int64_t num_compacted = 0;
5689
82
    int64_t num_empty_rowset = 0;
5690
82
    size_t total_rowset_key_size = 0;
5691
82
    size_t total_rowset_value_size = 0;
5692
82
    size_t expired_rowset_size = 0;
5693
82
    std::atomic_long num_recycled = 0;
5694
82
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5695
5696
82
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5697
82
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5698
82
    std::string recyc_rs_key0;
5699
82
    std::string recyc_rs_key1;
5700
82
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5701
82
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5702
5703
82
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5704
5705
82
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5706
82
    register_recycle_task(task_name, start_time);
5707
5708
82
    DORIS_CLOUD_DEFER {
5709
82
        unregister_recycle_task(task_name);
5710
82
        int64_t cost =
5711
82
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5712
82
        metrics_context.finish_report();
5713
82
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5714
82
                .tag("instance_id", instance_id_)
5715
82
                .tag("num_scanned", num_scanned)
5716
82
                .tag("num_expired", num_expired)
5717
82
                .tag("num_recycled", num_recycled)
5718
82
                .tag("num_recycled.prepare", num_prepare)
5719
82
                .tag("num_recycled.compacted", num_compacted)
5720
82
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5721
82
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5722
82
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5723
82
                .tag("expired_rowset_meta_size", expired_rowset_size);
5724
82
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5708
7
    DORIS_CLOUD_DEFER {
5709
7
        unregister_recycle_task(task_name);
5710
7
        int64_t cost =
5711
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5712
7
        metrics_context.finish_report();
5713
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5714
7
                .tag("instance_id", instance_id_)
5715
7
                .tag("num_scanned", num_scanned)
5716
7
                .tag("num_expired", num_expired)
5717
7
                .tag("num_recycled", num_recycled)
5718
7
                .tag("num_recycled.prepare", num_prepare)
5719
7
                .tag("num_recycled.compacted", num_compacted)
5720
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5721
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5722
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5723
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5724
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5708
75
    DORIS_CLOUD_DEFER {
5709
75
        unregister_recycle_task(task_name);
5710
75
        int64_t cost =
5711
75
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5712
75
        metrics_context.finish_report();
5713
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5714
75
                .tag("instance_id", instance_id_)
5715
75
                .tag("num_scanned", num_scanned)
5716
75
                .tag("num_expired", num_expired)
5717
75
                .tag("num_recycled", num_recycled)
5718
75
                .tag("num_recycled.prepare", num_prepare)
5719
75
                .tag("num_recycled.compacted", num_compacted)
5720
75
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5721
75
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5722
75
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5723
75
                .tag("expired_rowset_meta_size", expired_rowset_size);
5724
75
    };
5725
5726
82
    struct RecycleRowsetEntry {
5727
82
        std::string key;
5728
82
        doris::RowsetMetaCloudPB meta;
5729
82
    };
5730
82
    struct RecycleRowsetDeleteJob {
5731
82
        std::vector<std::string> keys;
5732
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5733
82
    };
5734
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5735
82
    std::vector<RecycleRowsetEntry> rowsets;
5736
82
    int64_t current_tablet_id = -1;
5737
82
    int64_t recycled_rowset_count_for_current_tablet = 0;
5738
82
    bool current_tablet_skip_logged = false;
5739
82
    std::string next_scan_begin;
5740
82
    const int64_t rowset_batch_size_per_tablet =
5741
82
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5742
82
    const int64_t delete_rowset_batch_size =
5743
82
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5744
4.33k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5745
4.33k
        if (current_tablet_id != tablet_id) {
5746
48
            current_tablet_id = tablet_id;
5747
48
            recycled_rowset_count_for_current_tablet = 0;
5748
48
            current_tablet_skip_logged = false;
5749
48
        }
5750
4.33k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5751
7
            if (!current_tablet_skip_logged) {
5752
7
                LOG_INFO(
5753
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5754
7
                        .tag("instance_id", instance_id_)
5755
7
                        .tag("tablet_id", tablet_id)
5756
7
                        .tag("limit", rowset_batch_size_per_tablet);
5757
7
                current_tablet_skip_logged = true;
5758
7
            }
5759
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5760
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5761
7
            return false;
5762
7
        }
5763
4.32k
        ++recycled_rowset_count_for_current_tablet;
5764
4.32k
        return true;
5765
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5744
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5745
7
        if (current_tablet_id != tablet_id) {
5746
7
            current_tablet_id = tablet_id;
5747
7
            recycled_rowset_count_for_current_tablet = 0;
5748
7
            current_tablet_skip_logged = false;
5749
7
        }
5750
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5751
0
            if (!current_tablet_skip_logged) {
5752
0
                LOG_INFO(
5753
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5754
0
                        .tag("instance_id", instance_id_)
5755
0
                        .tag("tablet_id", tablet_id)
5756
0
                        .tag("limit", rowset_batch_size_per_tablet);
5757
0
                current_tablet_skip_logged = true;
5758
0
            }
5759
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5760
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5761
0
            return false;
5762
0
        }
5763
7
        ++recycled_rowset_count_for_current_tablet;
5764
7
        return true;
5765
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5744
4.32k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5745
4.32k
        if (current_tablet_id != tablet_id) {
5746
41
            current_tablet_id = tablet_id;
5747
41
            recycled_rowset_count_for_current_tablet = 0;
5748
41
            current_tablet_skip_logged = false;
5749
41
        }
5750
4.32k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5751
7
            if (!current_tablet_skip_logged) {
5752
7
                LOG_INFO(
5753
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5754
7
                        .tag("instance_id", instance_id_)
5755
7
                        .tag("tablet_id", tablet_id)
5756
7
                        .tag("limit", rowset_batch_size_per_tablet);
5757
7
                current_tablet_skip_logged = true;
5758
7
            }
5759
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5760
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5761
7
            return false;
5762
7
        }
5763
4.32k
        ++recycled_rowset_count_for_current_tablet;
5764
4.32k
        return true;
5765
4.32k
    };
5766
4.33k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5767
4.33k
        if (next_scan_begin.empty()) {
5768
4.32k
            return false;
5769
4.32k
        }
5770
7
        *begin = std::move(next_scan_begin);
5771
7
        next_scan_begin.clear();
5772
7
        return true;
5773
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5766
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5767
7
        if (next_scan_begin.empty()) {
5768
7
            return false;
5769
7
        }
5770
0
        *begin = std::move(next_scan_begin);
5771
0
        next_scan_begin.clear();
5772
0
        return true;
5773
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5766
4.32k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5767
4.32k
        if (next_scan_begin.empty()) {
5768
4.32k
            return false;
5769
4.32k
        }
5770
7
        *begin = std::move(next_scan_begin);
5771
7
        next_scan_begin.clear();
5772
7
        return true;
5773
4.32k
    };
5774
5775
82
    std::vector<std::string> rowset_keys_to_mark_recycled;
5776
82
    std::vector<std::string> rowset_keys_to_abort_job;
5777
5778
82
    std::mutex async_recycled_rowset_keys_mutex;
5779
82
    std::vector<std::string> async_recycled_rowset_keys;
5780
82
    std::vector<std::string> rowset_keys_without_data;
5781
82
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5782
82
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5783
82
    worker_pool->start();
5784
82
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5785
82
                                            int64_t partition_id, int64_t tablet_id,
5786
903
                                            const std::string& rowset_id) {
5787
        // Try to delete rowset data in background thread
5788
903
        int ret = worker_pool->submit_with_timeout(
5789
903
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5790
774
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5791
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5792
0
                        return;
5793
0
                    }
5794
774
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5795
774
                        0) {
5796
0
                        return;
5797
0
                    }
5798
774
                    std::vector<std::string> keys;
5799
774
                    {
5800
774
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5801
774
                        async_recycled_rowset_keys.push_back(std::move(key));
5802
774
                        if (async_recycled_rowset_keys.size() > 100) {
5803
5
                            keys.swap(async_recycled_rowset_keys);
5804
5
                        }
5805
774
                    }
5806
774
                    if (keys.empty()) return;
5807
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5808
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5809
0
                                     << instance_id_;
5810
5
                    } else {
5811
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5812
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5813
5
                                           num_recycled, start_time);
5814
5
                    }
5815
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5789
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5790
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5791
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5792
0
                        return;
5793
0
                    }
5794
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5795
1
                        0) {
5796
0
                        return;
5797
0
                    }
5798
1
                    std::vector<std::string> keys;
5799
1
                    {
5800
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5801
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5802
1
                        if (async_recycled_rowset_keys.size() > 100) {
5803
0
                            keys.swap(async_recycled_rowset_keys);
5804
0
                        }
5805
1
                    }
5806
1
                    if (keys.empty()) return;
5807
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5808
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5809
0
                                     << instance_id_;
5810
0
                    } else {
5811
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5812
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5813
0
                                           num_recycled, start_time);
5814
0
                    }
5815
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5789
773
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5790
773
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5791
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5792
0
                        return;
5793
0
                    }
5794
773
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5795
773
                        0) {
5796
0
                        return;
5797
0
                    }
5798
773
                    std::vector<std::string> keys;
5799
773
                    {
5800
773
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5801
773
                        async_recycled_rowset_keys.push_back(std::move(key));
5802
773
                        if (async_recycled_rowset_keys.size() > 100) {
5803
5
                            keys.swap(async_recycled_rowset_keys);
5804
5
                        }
5805
773
                    }
5806
773
                    if (keys.empty()) return;
5807
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5808
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5809
0
                                     << instance_id_;
5810
5
                    } else {
5811
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5812
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5813
5
                                           num_recycled, start_time);
5814
5
                    }
5815
5
                },
5816
903
                0);
5817
903
        if (ret == 0) return 0;
5818
        // Submit task failed, delete rowset data in current thread
5819
129
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5820
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5821
0
            return -1;
5822
0
        }
5823
129
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5824
0
            return -1;
5825
0
        }
5826
129
        rowset_keys_without_data.push_back(std::move(key));
5827
129
        return 0;
5828
129
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5786
1
                                            const std::string& rowset_id) {
5787
        // Try to delete rowset data in background thread
5788
1
        int ret = worker_pool->submit_with_timeout(
5789
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5790
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5791
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5792
1
                        return;
5793
1
                    }
5794
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5795
1
                        0) {
5796
1
                        return;
5797
1
                    }
5798
1
                    std::vector<std::string> keys;
5799
1
                    {
5800
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5801
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5802
1
                        if (async_recycled_rowset_keys.size() > 100) {
5803
1
                            keys.swap(async_recycled_rowset_keys);
5804
1
                        }
5805
1
                    }
5806
1
                    if (keys.empty()) return;
5807
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5808
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5809
1
                                     << instance_id_;
5810
1
                    } else {
5811
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5812
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5813
1
                                           num_recycled, start_time);
5814
1
                    }
5815
1
                },
5816
1
                0);
5817
1
        if (ret == 0) return 0;
5818
        // Submit task failed, delete rowset data in current thread
5819
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5820
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5821
0
            return -1;
5822
0
        }
5823
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5824
0
            return -1;
5825
0
        }
5826
0
        rowset_keys_without_data.push_back(std::move(key));
5827
0
        return 0;
5828
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5786
902
                                            const std::string& rowset_id) {
5787
        // Try to delete rowset data in background thread
5788
902
        int ret = worker_pool->submit_with_timeout(
5789
902
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5790
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5791
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5792
902
                        return;
5793
902
                    }
5794
902
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5795
902
                        0) {
5796
902
                        return;
5797
902
                    }
5798
902
                    std::vector<std::string> keys;
5799
902
                    {
5800
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5801
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5802
902
                        if (async_recycled_rowset_keys.size() > 100) {
5803
902
                            keys.swap(async_recycled_rowset_keys);
5804
902
                        }
5805
902
                    }
5806
902
                    if (keys.empty()) return;
5807
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5808
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5809
902
                                     << instance_id_;
5810
902
                    } else {
5811
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5812
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5813
902
                                           num_recycled, start_time);
5814
902
                    }
5815
902
                },
5816
902
                0);
5817
902
        if (ret == 0) return 0;
5818
        // Submit task failed, delete rowset data in current thread
5819
129
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5820
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5821
0
            return -1;
5822
0
        }
5823
129
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5824
0
            return -1;
5825
0
        }
5826
129
        rowset_keys_without_data.push_back(std::move(key));
5827
129
        return 0;
5828
129
    };
5829
5830
82
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5831
5832
4.33k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5833
4.33k
        ++num_scanned;
5834
4.33k
        total_rowset_key_size += k.size();
5835
4.33k
        total_rowset_value_size += v.size();
5836
4.33k
        RecycleRowsetPB rowset;
5837
4.33k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5838
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
5842
4.33k
        int64_t current_time = ::time(nullptr);
5843
4.33k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5844
5845
4.33k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5846
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5847
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5848
4.33k
        if (current_time < expiration) { // not expired
5849
0
            return 0;
5850
0
        }
5851
4.33k
        ++num_expired;
5852
4.33k
        expired_rowset_size += v.size();
5853
5854
4.33k
        int64_t tablet_id =
5855
4.33k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5856
4.33k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5857
7
            return 0;
5858
7
        }
5859
5860
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5861
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5862
                // in old version, keep this key-value pair and it needs to be checked manually
5863
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5864
0
                return -1;
5865
0
            }
5866
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5867
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5868
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5869
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5870
2
                rowset_keys_without_data.emplace_back(k);
5871
2
                return 0;
5872
2
            }
5873
            // decode rowset_id
5874
250
            auto k1 = k;
5875
250
            k1.remove_prefix(1);
5876
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5877
250
            decode_key(&k1, &out);
5878
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5879
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5880
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5881
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5882
250
                      << " task_type=" << metrics_context.operation_type;
5883
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5884
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5885
0
                return -1;
5886
0
            }
5887
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5888
250
            metrics_context.total_recycled_num++;
5889
250
            segment_metrics_context_.total_recycled_data_size +=
5890
250
                    rowset.rowset_meta().total_disk_size();
5891
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5892
250
            return 0;
5893
250
        }
5894
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5895
5896
        // TODO(plat1ko): check rowset not referenced
5897
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5898
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5899
0
                LOG_INFO("recycle rowset that has empty resource id");
5900
0
            } else {
5901
                // other situations, keep this key-value pair and it needs to be checked manually
5902
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5903
0
                return -1;
5904
0
            }
5905
0
        }
5906
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5907
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5908
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5909
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5910
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5911
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5912
4.07k
                  << " rowset_meta_size=" << v.size()
5913
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5914
4.07k
                  << " task_type=" << metrics_context.operation_type;
5915
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5916
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5917
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5918
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5919
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5920
13
                                 "kv "
5921
13
                                 "at next turn, instance_id="
5922
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5923
13
                              << " version=[" << rowset_meta->start_version() << '-'
5924
13
                              << rowset_meta->end_version() << "]";
5925
13
                    return 0;
5926
13
                }
5927
23
            }
5928
5929
925
            num_prepare += 1;
5930
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5931
925
                rowset_meta->end_version() != 1) {
5932
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5933
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5934
272
                                 "instance_id="
5935
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5936
272
                              << " version=[" << rowset_meta->start_version() << '-'
5937
272
                              << rowset_meta->end_version() << "]";
5938
272
                    rowset_keys_to_abort_job.emplace_back(k);
5939
272
                    return 0;
5940
272
                }
5941
273
            }
5942
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5943
653
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5944
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5945
0
                return -1;
5946
0
            }
5947
3.13k
        } else {
5948
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5949
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5950
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5951
3.13k
            } else {
5952
3
                ++num_empty_rowset;
5953
3
                rowset_keys_without_data.emplace_back(k);
5954
3
            }
5955
3.13k
        }
5956
3.79k
        return 0;
5957
4.07k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5832
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5833
7
        ++num_scanned;
5834
7
        total_rowset_key_size += k.size();
5835
7
        total_rowset_value_size += v.size();
5836
7
        RecycleRowsetPB rowset;
5837
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5838
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
5842
7
        int64_t current_time = ::time(nullptr);
5843
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5844
5845
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5846
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5847
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5848
7
        if (current_time < expiration) { // not expired
5849
0
            return 0;
5850
0
        }
5851
7
        ++num_expired;
5852
7
        expired_rowset_size += v.size();
5853
5854
7
        int64_t tablet_id =
5855
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5856
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5857
0
            return 0;
5858
0
        }
5859
5860
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5861
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5862
                // in old version, keep this key-value pair and it needs to be checked manually
5863
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5864
0
                return -1;
5865
0
            }
5866
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5867
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5868
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5869
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5870
0
                rowset_keys_without_data.emplace_back(k);
5871
0
                return 0;
5872
0
            }
5873
            // decode rowset_id
5874
0
            auto k1 = k;
5875
0
            k1.remove_prefix(1);
5876
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5877
0
            decode_key(&k1, &out);
5878
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5879
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5880
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5881
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5882
0
                      << " task_type=" << metrics_context.operation_type;
5883
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5884
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5885
0
                return -1;
5886
0
            }
5887
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5888
0
            metrics_context.total_recycled_num++;
5889
0
            segment_metrics_context_.total_recycled_data_size +=
5890
0
                    rowset.rowset_meta().total_disk_size();
5891
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5892
0
            return 0;
5893
0
        }
5894
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5895
5896
        // TODO(plat1ko): check rowset not referenced
5897
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5898
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5899
0
                LOG_INFO("recycle rowset that has empty resource id");
5900
0
            } else {
5901
                // other situations, keep this key-value pair and it needs to be checked manually
5902
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5903
0
                return -1;
5904
0
            }
5905
0
        }
5906
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5907
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5908
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5909
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5910
7
                  << "] txn_id=" << rowset_meta->txn_id()
5911
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5912
7
                  << " rowset_meta_size=" << v.size()
5913
7
                  << " creation_time=" << rowset_meta->creation_time()
5914
7
                  << " task_type=" << metrics_context.operation_type;
5915
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5916
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5917
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5918
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5919
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5920
4
                                 "kv "
5921
4
                                 "at next turn, instance_id="
5922
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5923
4
                              << " version=[" << rowset_meta->start_version() << '-'
5924
4
                              << rowset_meta->end_version() << "]";
5925
4
                    return 0;
5926
4
                }
5927
6
            }
5928
5929
3
            num_prepare += 1;
5930
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5931
3
                rowset_meta->end_version() != 1) {
5932
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5933
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5934
2
                                 "instance_id="
5935
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5936
2
                              << " version=[" << rowset_meta->start_version() << '-'
5937
2
                              << rowset_meta->end_version() << "]";
5938
2
                    rowset_keys_to_abort_job.emplace_back(k);
5939
2
                    return 0;
5940
2
                }
5941
2
            }
5942
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5943
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5944
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5945
0
                return -1;
5946
0
            }
5947
1
        } else {
5948
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5949
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5950
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5951
0
            } else {
5952
0
                ++num_empty_rowset;
5953
0
                rowset_keys_without_data.emplace_back(k);
5954
0
            }
5955
0
        }
5956
1
        return 0;
5957
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5832
4.32k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5833
4.32k
        ++num_scanned;
5834
4.32k
        total_rowset_key_size += k.size();
5835
4.32k
        total_rowset_value_size += v.size();
5836
4.32k
        RecycleRowsetPB rowset;
5837
4.32k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5838
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5839
0
            return -1;
5840
0
        }
5841
5842
4.32k
        int64_t current_time = ::time(nullptr);
5843
4.32k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5844
5845
4.32k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5846
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5847
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5848
4.32k
        if (current_time < expiration) { // not expired
5849
0
            return 0;
5850
0
        }
5851
4.32k
        ++num_expired;
5852
4.32k
        expired_rowset_size += v.size();
5853
5854
4.32k
        int64_t tablet_id =
5855
4.32k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5856
4.32k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5857
7
            return 0;
5858
7
        }
5859
5860
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5861
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5862
                // in old version, keep this key-value pair and it needs to be checked manually
5863
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5864
0
                return -1;
5865
0
            }
5866
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5867
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5868
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5869
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5870
2
                rowset_keys_without_data.emplace_back(k);
5871
2
                return 0;
5872
2
            }
5873
            // decode rowset_id
5874
250
            auto k1 = k;
5875
250
            k1.remove_prefix(1);
5876
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5877
250
            decode_key(&k1, &out);
5878
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5879
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5880
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5881
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5882
250
                      << " task_type=" << metrics_context.operation_type;
5883
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5884
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5885
0
                return -1;
5886
0
            }
5887
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5888
250
            metrics_context.total_recycled_num++;
5889
250
            segment_metrics_context_.total_recycled_data_size +=
5890
250
                    rowset.rowset_meta().total_disk_size();
5891
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5892
250
            return 0;
5893
250
        }
5894
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5895
5896
        // TODO(plat1ko): check rowset not referenced
5897
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5898
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5899
0
                LOG_INFO("recycle rowset that has empty resource id");
5900
0
            } else {
5901
                // other situations, keep this key-value pair and it needs to be checked manually
5902
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5903
0
                return -1;
5904
0
            }
5905
0
        }
5906
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5907
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5908
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5909
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5910
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5911
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5912
4.07k
                  << " rowset_meta_size=" << v.size()
5913
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5914
4.07k
                  << " task_type=" << metrics_context.operation_type;
5915
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5916
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5917
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5918
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5919
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5920
9
                                 "kv "
5921
9
                                 "at next turn, instance_id="
5922
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5923
9
                              << " version=[" << rowset_meta->start_version() << '-'
5924
9
                              << rowset_meta->end_version() << "]";
5925
9
                    return 0;
5926
9
                }
5927
17
            }
5928
5929
922
            num_prepare += 1;
5930
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5931
922
                rowset_meta->end_version() != 1) {
5932
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5933
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5934
270
                                 "instance_id="
5935
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5936
270
                              << " version=[" << rowset_meta->start_version() << '-'
5937
270
                              << rowset_meta->end_version() << "]";
5938
270
                    rowset_keys_to_abort_job.emplace_back(k);
5939
270
                    return 0;
5940
270
                }
5941
271
            }
5942
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5943
652
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5944
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5945
0
                return -1;
5946
0
            }
5947
3.13k
        } else {
5948
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5949
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
5950
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
5951
3.13k
            } else {
5952
3
                ++num_empty_rowset;
5953
3
                rowset_keys_without_data.emplace_back(k);
5954
3
            }
5955
3.13k
        }
5956
3.79k
        return 0;
5957
4.07k
    };
5958
5959
82
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
5960
82
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5961
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5962
23
                             rowsets_to_delete = std::move(rowsets)]() {
5963
23
            if (!rowsets_to_delete.empty() &&
5964
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5965
18
                                   metrics_context) != 0) {
5966
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5967
0
                return;
5968
0
            }
5969
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5970
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
5971
3.13k
                                                       rs.rowset_id_v2()) != 0) {
5972
0
                    return;
5973
0
                }
5974
3.13k
            }
5975
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5976
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5977
0
                return;
5978
0
            }
5979
5980
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5981
23
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEEENKUlvE_clEv
Line
Count
Source
5962
23
                             rowsets_to_delete = std::move(rowsets)]() {
5963
23
            if (!rowsets_to_delete.empty() &&
5964
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5965
18
                                   metrics_context) != 0) {
5966
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5967
0
                return;
5968
0
            }
5969
3.13k
            for (const auto& [_, rs] : rowsets_to_delete) {
5970
3.13k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
5971
3.13k
                                                       rs.rowset_id_v2()) != 0) {
5972
0
                    return;
5973
0
                }
5974
3.13k
            }
5975
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5976
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5977
0
                return;
5978
0
            }
5979
5980
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5981
23
        });
5982
23
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESt3mapIS9_NS_17RowsetMetaCloudPBESt4lessIS9_ESaISt4pairIKS9_SD_EEE
Line
Count
Source
5960
23
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
5961
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
5962
23
                             rowsets_to_delete = std::move(rowsets)]() {
5963
23
            if (!rowsets_to_delete.empty() &&
5964
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5965
23
                                   metrics_context) != 0) {
5966
23
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5967
23
                return;
5968
23
            }
5969
23
            for (const auto& [_, rs] : rowsets_to_delete) {
5970
23
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
5971
23
                                                       rs.rowset_id_v2()) != 0) {
5972
23
                    return;
5973
23
                }
5974
23
            }
5975
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5976
23
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5977
23
                return;
5978
23
            }
5979
5980
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5981
23
        });
5982
23
    };
5983
5984
82
    bool scan_finished = false;
5985
144
    auto loop_done = [&]() -> int {
5986
144
        std::vector<std::string> mark_keys_to_process;
5987
144
        std::vector<std::string> abort_job_keys_to_process;
5988
144
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5989
144
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5990
144
        if (!mark_keys_to_process.empty()) {
5991
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5992
11
                    *worker_pool, std::move(mark_keys_to_process));
5993
11
        }
5994
144
        if (!abort_job_keys_to_process.empty()) {
5995
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5996
15
                                               &num_recycled);
5997
15
        }
5998
144
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5999
62
            return 0;
6000
62
        }
6001
6002
82
        DORIS_CLOUD_DEFER {
6003
            // if return -1 in loop done, rowset info in memory is not cleared,
6004
            // it can lead to memory accumulation
6005
82
            rowset_keys_without_data.clear();
6006
82
            rowsets.clear();
6007
82
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
6002
7
        DORIS_CLOUD_DEFER {
6003
            // if return -1 in loop done, rowset info in memory is not cleared,
6004
            // it can lead to memory accumulation
6005
7
            rowset_keys_without_data.clear();
6006
7
            rowsets.clear();
6007
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
6002
75
        DORIS_CLOUD_DEFER {
6003
            // if return -1 in loop done, rowset info in memory is not cleared,
6004
            // it can lead to memory accumulation
6005
75
            rowset_keys_without_data.clear();
6006
75
            rowsets.clear();
6007
75
        };
6008
82
        std::random_device rd;
6009
82
        std::mt19937 g(rd());
6010
82
        std::ranges::shuffle(rowsets, g);
6011
6012
82
        std::vector<std::string> rowset_keys_to_delete;
6013
82
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6014
        // rowset_id -> rowset_meta
6015
        // store rowset id and meta for statistics rs size when delete
6016
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6017
6018
82
        size_t rowsets_per_batch_size = 0;
6019
3.13k
        for (auto& rowset : rowsets) {
6020
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6021
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6022
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6023
3.12k
                continue;
6024
3.12k
            }
6025
6026
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6027
8
                                          std::move(rowsets_to_delete));
6028
8
            rowsets_per_batch_size = 0;
6029
8
            rowset_keys_to_delete.clear();
6030
8
            rowsets_to_delete.clear();
6031
8
        }
6032
6033
82
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6034
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6035
10
                                          std::move(rowsets_to_delete));
6036
10
        }
6037
6038
87
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6039
5
            auto begin = rowset_keys_without_data.begin() + i;
6040
5
            auto end = rowset_keys_without_data.begin() +
6041
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6042
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6043
5
                                                           std::make_move_iterator(end));
6044
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6045
5
        }
6046
6047
82
        return 0;
6048
144
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5985
14
    auto loop_done = [&]() -> int {
5986
14
        std::vector<std::string> mark_keys_to_process;
5987
14
        std::vector<std::string> abort_job_keys_to_process;
5988
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5989
14
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5990
14
        if (!mark_keys_to_process.empty()) {
5991
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5992
4
                    *worker_pool, std::move(mark_keys_to_process));
5993
4
        }
5994
14
        if (!abort_job_keys_to_process.empty()) {
5995
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5996
2
                                               &num_recycled);
5997
2
        }
5998
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5999
7
            return 0;
6000
7
        }
6001
6002
7
        DORIS_CLOUD_DEFER {
6003
            // if return -1 in loop done, rowset info in memory is not cleared,
6004
            // it can lead to memory accumulation
6005
7
            rowset_keys_without_data.clear();
6006
7
            rowsets.clear();
6007
7
        };
6008
7
        std::random_device rd;
6009
7
        std::mt19937 g(rd());
6010
7
        std::ranges::shuffle(rowsets, g);
6011
6012
7
        std::vector<std::string> rowset_keys_to_delete;
6013
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6014
        // rowset_id -> rowset_meta
6015
        // store rowset id and meta for statistics rs size when delete
6016
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6017
6018
7
        size_t rowsets_per_batch_size = 0;
6019
7
        for (auto& rowset : rowsets) {
6020
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6021
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6022
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6023
0
                continue;
6024
0
            }
6025
6026
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6027
0
                                          std::move(rowsets_to_delete));
6028
0
            rowsets_per_batch_size = 0;
6029
0
            rowset_keys_to_delete.clear();
6030
0
            rowsets_to_delete.clear();
6031
0
        }
6032
6033
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6034
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6035
0
                                          std::move(rowsets_to_delete));
6036
0
        }
6037
6038
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6039
0
            auto begin = rowset_keys_without_data.begin() + i;
6040
0
            auto end = rowset_keys_without_data.begin() +
6041
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6042
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6043
0
                                                           std::make_move_iterator(end));
6044
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6045
0
        }
6046
6047
7
        return 0;
6048
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
5985
130
    auto loop_done = [&]() -> int {
5986
130
        std::vector<std::string> mark_keys_to_process;
5987
130
        std::vector<std::string> abort_job_keys_to_process;
5988
130
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5989
130
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5990
130
        if (!mark_keys_to_process.empty()) {
5991
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5992
7
                    *worker_pool, std::move(mark_keys_to_process));
5993
7
        }
5994
130
        if (!abort_job_keys_to_process.empty()) {
5995
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5996
13
                                               &num_recycled);
5997
13
        }
5998
130
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
5999
55
            return 0;
6000
55
        }
6001
6002
75
        DORIS_CLOUD_DEFER {
6003
            // if return -1 in loop done, rowset info in memory is not cleared,
6004
            // it can lead to memory accumulation
6005
75
            rowset_keys_without_data.clear();
6006
75
            rowsets.clear();
6007
75
        };
6008
75
        std::random_device rd;
6009
75
        std::mt19937 g(rd());
6010
75
        std::ranges::shuffle(rowsets, g);
6011
6012
75
        std::vector<std::string> rowset_keys_to_delete;
6013
75
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6014
        // rowset_id -> rowset_meta
6015
        // store rowset id and meta for statistics rs size when delete
6016
75
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6017
6018
75
        size_t rowsets_per_batch_size = 0;
6019
3.13k
        for (auto& rowset : rowsets) {
6020
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6021
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6022
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6023
3.12k
                continue;
6024
3.12k
            }
6025
6026
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6027
8
                                          std::move(rowsets_to_delete));
6028
8
            rowsets_per_batch_size = 0;
6029
8
            rowset_keys_to_delete.clear();
6030
8
            rowsets_to_delete.clear();
6031
8
        }
6032
6033
75
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6034
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6035
10
                                          std::move(rowsets_to_delete));
6036
10
        }
6037
6038
80
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6039
5
            auto begin = rowset_keys_without_data.begin() + i;
6040
5
            auto end = rowset_keys_without_data.begin() +
6041
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6042
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6043
5
                                                           std::make_move_iterator(end));
6044
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6045
5
        }
6046
6047
75
        return 0;
6048
130
    };
6049
6050
82
    if (config::enable_recycler_stats_metrics) {
6051
0
        scan_and_statistics_rowsets();
6052
0
    }
6053
    // recycle_func and loop_done for scan and recycle
6054
82
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
6055
82
                               std::move(next_scan_begin_getter));
6056
82
    scan_finished = true;
6057
    // if the size of rowsets is always less than delete_rowset_batch_size
6058
    // it need to submit the task directly
6059
    // else if the size of rowsets is greater than delete_rowset_batch_size,
6060
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
6061
82
    if (loop_done() != 0) {
6062
0
        ret = -1;
6063
0
    }
6064
6065
82
    worker_pool->stop();
6066
6067
82
    if (!async_recycled_rowset_keys.empty()) {
6068
6
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6069
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6070
0
            return -1;
6071
6
        } else {
6072
6
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6073
6
        }
6074
6
    }
6075
6076
    // Report final metrics after all concurrent tasks completed
6077
82
    segment_metrics_context_.report();
6078
82
    metrics_context.report();
6079
6080
82
    return ret;
6081
82
}
6082
6083
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
6084
1
                                                     int64_t tablet_id, std::string* next_key) {
6085
1
    DCHECK(next_key != nullptr);
6086
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
6087
0
        return -1;
6088
0
    }
6089
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
6090
1
    return 0;
6091
1
}
6092
6093
13
int InstanceRecycler::recycle_restore_jobs() {
6094
13
    const std::string task_name = "recycle_restore_jobs";
6095
13
    int64_t num_scanned = 0;
6096
13
    int64_t num_expired = 0;
6097
13
    int64_t num_recycled = 0;
6098
13
    int64_t num_aborted = 0;
6099
6100
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6101
6102
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6103
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6104
13
    std::string restore_job_key0;
6105
13
    std::string restore_job_key1;
6106
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6107
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6108
6109
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6110
6111
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6112
13
    register_recycle_task(task_name, start_time);
6113
6114
13
    DORIS_CLOUD_DEFER {
6115
13
        unregister_recycle_task(task_name);
6116
13
        int64_t cost =
6117
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6118
13
        metrics_context.finish_report();
6119
6120
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6121
13
                .tag("instance_id", instance_id_)
6122
13
                .tag("num_scanned", num_scanned)
6123
13
                .tag("num_expired", num_expired)
6124
13
                .tag("num_recycled", num_recycled)
6125
13
                .tag("num_aborted", num_aborted);
6126
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6114
13
    DORIS_CLOUD_DEFER {
6115
13
        unregister_recycle_task(task_name);
6116
13
        int64_t cost =
6117
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6118
13
        metrics_context.finish_report();
6119
6120
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6121
13
                .tag("instance_id", instance_id_)
6122
13
                .tag("num_scanned", num_scanned)
6123
13
                .tag("num_expired", num_expired)
6124
13
                .tag("num_recycled", num_recycled)
6125
13
                .tag("num_aborted", num_aborted);
6126
13
    };
6127
6128
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6129
6130
13
    std::vector<std::string_view> restore_job_keys;
6131
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6132
41
        ++num_scanned;
6133
41
        RestoreJobCloudPB restore_job_pb;
6134
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6135
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6136
0
            return -1;
6137
0
        }
6138
41
        int64_t expiration =
6139
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6140
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6141
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6142
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6143
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6144
0
                   << " state=" << restore_job_pb.state();
6145
41
        int64_t current_time = ::time(nullptr);
6146
41
        if (current_time < expiration) { // not expired
6147
0
            return 0;
6148
0
        }
6149
41
        ++num_expired;
6150
6151
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6152
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6153
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6154
6155
41
        std::unique_ptr<Transaction> txn;
6156
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6157
41
        if (err != TxnErrorCode::TXN_OK) {
6158
0
            LOG_WARNING("failed to recycle restore job")
6159
0
                    .tag("err", err)
6160
0
                    .tag("tablet id", tablet_id)
6161
0
                    .tag("instance_id", instance_id_)
6162
0
                    .tag("reason", "failed to create txn");
6163
0
            return -1;
6164
0
        }
6165
6166
41
        std::string val;
6167
41
        err = txn->get(k, &val);
6168
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6169
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6170
0
            return 0;
6171
0
        }
6172
41
        if (err != TxnErrorCode::TXN_OK) {
6173
0
            LOG_WARNING("failed to get kv");
6174
0
            return -1;
6175
0
        }
6176
41
        restore_job_pb.Clear();
6177
41
        if (!restore_job_pb.ParseFromString(val)) {
6178
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6179
0
            return -1;
6180
0
        }
6181
6182
        // PREPARED or COMMITTED, change state to DROPPED and return
6183
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6184
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6185
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6186
0
            restore_job_pb.set_need_recycle_data(true);
6187
0
            txn->put(k, restore_job_pb.SerializeAsString());
6188
0
            err = txn->commit();
6189
0
            if (err != TxnErrorCode::TXN_OK) {
6190
0
                LOG_WARNING("failed to commit txn: {}", err);
6191
0
                return -1;
6192
0
            }
6193
0
            num_aborted++;
6194
0
            return 0;
6195
0
        }
6196
6197
        // Change state to RECYCLING
6198
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6199
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6200
21
            txn->put(k, restore_job_pb.SerializeAsString());
6201
21
            err = txn->commit();
6202
21
            if (err != TxnErrorCode::TXN_OK) {
6203
0
                LOG_WARNING("failed to commit txn: {}", err);
6204
0
                return -1;
6205
0
            }
6206
21
            return 0;
6207
21
        }
6208
6209
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6210
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6211
6212
        // Recycle all data associated with the restore job.
6213
        // This includes rowsets, segments, and related resources.
6214
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6215
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6216
0
            LOG_WARNING("failed to recycle tablet")
6217
0
                    .tag("tablet_id", tablet_id)
6218
0
                    .tag("instance_id", instance_id_);
6219
0
            return -1;
6220
0
        }
6221
6222
        // delete all restore job rowset kv
6223
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6224
6225
20
        err = txn->commit();
6226
20
        if (err != TxnErrorCode::TXN_OK) {
6227
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6228
0
                    .tag("err", err)
6229
0
                    .tag("tablet id", tablet_id)
6230
0
                    .tag("instance_id", instance_id_)
6231
0
                    .tag("reason", "failed to commit txn");
6232
0
            return -1;
6233
0
        }
6234
6235
20
        metrics_context.total_recycled_num = ++num_recycled;
6236
20
        metrics_context.report();
6237
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6238
20
        restore_job_keys.push_back(k);
6239
6240
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6241
20
                  << " tablet_id=" << tablet_id;
6242
20
        return 0;
6243
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
6131
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6132
41
        ++num_scanned;
6133
41
        RestoreJobCloudPB restore_job_pb;
6134
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6135
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6136
0
            return -1;
6137
0
        }
6138
41
        int64_t expiration =
6139
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6140
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6141
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6142
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6143
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6144
0
                   << " state=" << restore_job_pb.state();
6145
41
        int64_t current_time = ::time(nullptr);
6146
41
        if (current_time < expiration) { // not expired
6147
0
            return 0;
6148
0
        }
6149
41
        ++num_expired;
6150
6151
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6152
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6153
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6154
6155
41
        std::unique_ptr<Transaction> txn;
6156
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6157
41
        if (err != TxnErrorCode::TXN_OK) {
6158
0
            LOG_WARNING("failed to recycle restore job")
6159
0
                    .tag("err", err)
6160
0
                    .tag("tablet id", tablet_id)
6161
0
                    .tag("instance_id", instance_id_)
6162
0
                    .tag("reason", "failed to create txn");
6163
0
            return -1;
6164
0
        }
6165
6166
41
        std::string val;
6167
41
        err = txn->get(k, &val);
6168
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6169
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6170
0
            return 0;
6171
0
        }
6172
41
        if (err != TxnErrorCode::TXN_OK) {
6173
0
            LOG_WARNING("failed to get kv");
6174
0
            return -1;
6175
0
        }
6176
41
        restore_job_pb.Clear();
6177
41
        if (!restore_job_pb.ParseFromString(val)) {
6178
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6179
0
            return -1;
6180
0
        }
6181
6182
        // PREPARED or COMMITTED, change state to DROPPED and return
6183
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6184
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6185
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6186
0
            restore_job_pb.set_need_recycle_data(true);
6187
0
            txn->put(k, restore_job_pb.SerializeAsString());
6188
0
            err = txn->commit();
6189
0
            if (err != TxnErrorCode::TXN_OK) {
6190
0
                LOG_WARNING("failed to commit txn: {}", err);
6191
0
                return -1;
6192
0
            }
6193
0
            num_aborted++;
6194
0
            return 0;
6195
0
        }
6196
6197
        // Change state to RECYCLING
6198
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6199
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6200
21
            txn->put(k, restore_job_pb.SerializeAsString());
6201
21
            err = txn->commit();
6202
21
            if (err != TxnErrorCode::TXN_OK) {
6203
0
                LOG_WARNING("failed to commit txn: {}", err);
6204
0
                return -1;
6205
0
            }
6206
21
            return 0;
6207
21
        }
6208
6209
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6210
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6211
6212
        // Recycle all data associated with the restore job.
6213
        // This includes rowsets, segments, and related resources.
6214
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6215
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6216
0
            LOG_WARNING("failed to recycle tablet")
6217
0
                    .tag("tablet_id", tablet_id)
6218
0
                    .tag("instance_id", instance_id_);
6219
0
            return -1;
6220
0
        }
6221
6222
        // delete all restore job rowset kv
6223
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6224
6225
20
        err = txn->commit();
6226
20
        if (err != TxnErrorCode::TXN_OK) {
6227
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6228
0
                    .tag("err", err)
6229
0
                    .tag("tablet id", tablet_id)
6230
0
                    .tag("instance_id", instance_id_)
6231
0
                    .tag("reason", "failed to commit txn");
6232
0
            return -1;
6233
0
        }
6234
6235
20
        metrics_context.total_recycled_num = ++num_recycled;
6236
20
        metrics_context.report();
6237
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6238
20
        restore_job_keys.push_back(k);
6239
6240
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6241
20
                  << " tablet_id=" << tablet_id;
6242
20
        return 0;
6243
20
    };
6244
6245
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6246
3
        if (restore_job_keys.empty()) return 0;
6247
1
        DORIS_CLOUD_DEFER {
6248
1
            restore_job_keys.clear();
6249
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6247
1
        DORIS_CLOUD_DEFER {
6248
1
            restore_job_keys.clear();
6249
1
        };
6250
6251
1
        std::unique_ptr<Transaction> txn;
6252
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6253
1
        if (err != TxnErrorCode::TXN_OK) {
6254
0
            LOG_WARNING("failed to recycle restore job")
6255
0
                    .tag("err", err)
6256
0
                    .tag("instance_id", instance_id_)
6257
0
                    .tag("reason", "failed to create txn");
6258
0
            return -1;
6259
0
        }
6260
20
        for (auto& k : restore_job_keys) {
6261
20
            txn->remove(k);
6262
20
        }
6263
1
        err = txn->commit();
6264
1
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_WARNING("failed to recycle restore job")
6266
0
                    .tag("err", err)
6267
0
                    .tag("instance_id", instance_id_)
6268
0
                    .tag("reason", "failed to commit txn");
6269
0
            return -1;
6270
0
        }
6271
1
        return 0;
6272
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6245
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6246
3
        if (restore_job_keys.empty()) return 0;
6247
1
        DORIS_CLOUD_DEFER {
6248
1
            restore_job_keys.clear();
6249
1
        };
6250
6251
1
        std::unique_ptr<Transaction> txn;
6252
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6253
1
        if (err != TxnErrorCode::TXN_OK) {
6254
0
            LOG_WARNING("failed to recycle restore job")
6255
0
                    .tag("err", err)
6256
0
                    .tag("instance_id", instance_id_)
6257
0
                    .tag("reason", "failed to create txn");
6258
0
            return -1;
6259
0
        }
6260
20
        for (auto& k : restore_job_keys) {
6261
20
            txn->remove(k);
6262
20
        }
6263
1
        err = txn->commit();
6264
1
        if (err != TxnErrorCode::TXN_OK) {
6265
0
            LOG_WARNING("failed to recycle restore job")
6266
0
                    .tag("err", err)
6267
0
                    .tag("instance_id", instance_id_)
6268
0
                    .tag("reason", "failed to commit txn");
6269
0
            return -1;
6270
0
        }
6271
1
        return 0;
6272
1
    };
6273
6274
13
    if (config::enable_recycler_stats_metrics) {
6275
0
        scan_and_statistics_restore_jobs();
6276
0
    }
6277
6278
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6279
13
                            std::move(loop_done));
6280
13
}
6281
6282
11
int InstanceRecycler::recycle_versioned_rowsets() {
6283
11
    const std::string task_name = "recycle_rowsets";
6284
11
    int64_t num_scanned = 0;
6285
11
    int64_t num_expired = 0;
6286
11
    int64_t num_prepare = 0;
6287
11
    int64_t num_compacted = 0;
6288
11
    int64_t num_empty_rowset = 0;
6289
11
    size_t total_rowset_key_size = 0;
6290
11
    size_t total_rowset_value_size = 0;
6291
11
    size_t expired_rowset_size = 0;
6292
11
    std::atomic_long num_recycled = 0;
6293
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6294
6295
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6296
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6297
11
    std::string recyc_rs_key0;
6298
11
    std::string recyc_rs_key1;
6299
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6300
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6301
6302
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6303
6304
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6305
11
    register_recycle_task(task_name, start_time);
6306
6307
11
    DORIS_CLOUD_DEFER {
6308
11
        unregister_recycle_task(task_name);
6309
11
        int64_t cost =
6310
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6311
11
        metrics_context.finish_report();
6312
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6313
11
                .tag("instance_id", instance_id_)
6314
11
                .tag("num_scanned", num_scanned)
6315
11
                .tag("num_expired", num_expired)
6316
11
                .tag("num_recycled", num_recycled)
6317
11
                .tag("num_recycled.prepare", num_prepare)
6318
11
                .tag("num_recycled.compacted", num_compacted)
6319
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6320
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6321
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6322
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6323
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6307
11
    DORIS_CLOUD_DEFER {
6308
11
        unregister_recycle_task(task_name);
6309
11
        int64_t cost =
6310
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6311
11
        metrics_context.finish_report();
6312
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6313
11
                .tag("instance_id", instance_id_)
6314
11
                .tag("num_scanned", num_scanned)
6315
11
                .tag("num_expired", num_expired)
6316
11
                .tag("num_recycled", num_recycled)
6317
11
                .tag("num_recycled.prepare", num_prepare)
6318
11
                .tag("num_recycled.compacted", num_compacted)
6319
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6320
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6321
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6322
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6323
11
    };
6324
6325
11
    std::vector<std::string> orphan_rowset_keys;
6326
6327
    // Store keys of rowset recycled by background workers
6328
11
    std::mutex async_recycled_rowset_keys_mutex;
6329
11
    std::vector<std::string> async_recycled_rowset_keys;
6330
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6331
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6332
11
    worker_pool->start();
6333
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6334
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6335
        // Try to delete rowset data in background thread
6336
400
        int ret = worker_pool->submit_with_timeout(
6337
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6338
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6339
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6340
400
                        return;
6341
400
                    }
6342
                    // The async recycled rowsets are staled format or has not been used,
6343
                    // so we don't need to check the rowset ref count key.
6344
0
                    std::vector<std::string> keys;
6345
0
                    {
6346
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6347
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6348
0
                        if (async_recycled_rowset_keys.size() > 100) {
6349
0
                            keys.swap(async_recycled_rowset_keys);
6350
0
                        }
6351
0
                    }
6352
0
                    if (keys.empty()) return;
6353
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6354
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6355
0
                                     << instance_id_;
6356
0
                    } else {
6357
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6358
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6359
0
                                           num_recycled, start_time);
6360
0
                    }
6361
0
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
6337
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6338
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6339
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6340
400
                        return;
6341
400
                    }
6342
                    // The async recycled rowsets are staled format or has not been used,
6343
                    // so we don't need to check the rowset ref count key.
6344
0
                    std::vector<std::string> keys;
6345
0
                    {
6346
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6347
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6348
0
                        if (async_recycled_rowset_keys.size() > 100) {
6349
0
                            keys.swap(async_recycled_rowset_keys);
6350
0
                        }
6351
0
                    }
6352
0
                    if (keys.empty()) return;
6353
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6354
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6355
0
                                     << instance_id_;
6356
0
                    } else {
6357
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6358
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6359
0
                                           num_recycled, start_time);
6360
0
                    }
6361
0
                },
6362
400
                0);
6363
400
        if (ret == 0) return 0;
6364
        // Submit task failed, delete rowset data in current thread
6365
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6366
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6367
0
            return -1;
6368
0
        }
6369
0
        orphan_rowset_keys.push_back(std::move(key));
6370
0
        return 0;
6371
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
6334
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6335
        // Try to delete rowset data in background thread
6336
400
        int ret = worker_pool->submit_with_timeout(
6337
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6338
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6339
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6340
400
                        return;
6341
400
                    }
6342
                    // The async recycled rowsets are staled format or has not been used,
6343
                    // so we don't need to check the rowset ref count key.
6344
400
                    std::vector<std::string> keys;
6345
400
                    {
6346
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6347
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6348
400
                        if (async_recycled_rowset_keys.size() > 100) {
6349
400
                            keys.swap(async_recycled_rowset_keys);
6350
400
                        }
6351
400
                    }
6352
400
                    if (keys.empty()) return;
6353
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6354
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6355
400
                                     << instance_id_;
6356
400
                    } else {
6357
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6358
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6359
400
                                           num_recycled, start_time);
6360
400
                    }
6361
400
                },
6362
400
                0);
6363
400
        if (ret == 0) return 0;
6364
        // Submit task failed, delete rowset data in current thread
6365
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6366
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6367
0
            return -1;
6368
0
        }
6369
0
        orphan_rowset_keys.push_back(std::move(key));
6370
0
        return 0;
6371
0
    };
6372
6373
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6374
6375
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6376
2.01k
        ++num_scanned;
6377
2.01k
        total_rowset_key_size += k.size();
6378
2.01k
        total_rowset_value_size += v.size();
6379
2.01k
        RecycleRowsetPB rowset;
6380
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6381
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6382
0
            return -1;
6383
0
        }
6384
6385
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6386
6387
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6388
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6389
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6390
2.01k
        int64_t current_time = ::time(nullptr);
6391
2.01k
        if (current_time < final_expiration) { // not expired
6392
0
            return 0;
6393
0
        }
6394
2.01k
        ++num_expired;
6395
2.01k
        expired_rowset_size += v.size();
6396
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6397
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6398
                // in old version, keep this key-value pair and it needs to be checked manually
6399
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6400
0
                return -1;
6401
0
            }
6402
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6403
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6404
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6405
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6406
0
                orphan_rowset_keys.emplace_back(k);
6407
0
                return -1;
6408
0
            }
6409
            // decode rowset_id
6410
0
            auto k1 = k;
6411
0
            k1.remove_prefix(1);
6412
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6413
0
            decode_key(&k1, &out);
6414
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6415
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6416
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6417
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6418
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6419
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6420
0
                return -1;
6421
0
            }
6422
0
            return 0;
6423
0
        }
6424
        // TODO(plat1ko): check rowset not referenced
6425
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6426
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6427
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6428
0
                LOG_INFO("recycle rowset that has empty resource id");
6429
0
            } else {
6430
                // other situations, keep this key-value pair and it needs to be checked manually
6431
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6432
0
                return -1;
6433
0
            }
6434
0
        }
6435
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6436
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6437
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6438
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6439
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6440
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6441
2.01k
                  << " rowset_meta_size=" << v.size()
6442
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6443
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6444
            // unable to calculate file path, can only be deleted by rowset id prefix
6445
400
            num_prepare += 1;
6446
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6447
400
                                             rowset_meta->tablet_id(),
6448
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6449
0
                return -1;
6450
0
            }
6451
1.61k
        } else {
6452
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6453
1.61k
            worker_pool->submit(
6454
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6455
                        // The load & compact rowset keys are recycled during recycling operation logs.
6456
1.61k
                        RowsetDeleteTask task;
6457
1.61k
                        task.rowset_meta = rowset_meta;
6458
1.61k
                        task.recycle_rowset_key = k;
6459
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6460
1.60k
                            return;
6461
1.60k
                        }
6462
13
                        num_compacted += is_compacted;
6463
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6464
13
                        if (rowset_meta.num_segments() == 0) {
6465
0
                            ++num_empty_rowset;
6466
0
                        }
6467
13
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
6454
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6455
                        // The load & compact rowset keys are recycled during recycling operation logs.
6456
1.61k
                        RowsetDeleteTask task;
6457
1.61k
                        task.rowset_meta = rowset_meta;
6458
1.61k
                        task.recycle_rowset_key = k;
6459
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6460
1.60k
                            return;
6461
1.60k
                        }
6462
13
                        num_compacted += is_compacted;
6463
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6464
13
                        if (rowset_meta.num_segments() == 0) {
6465
0
                            ++num_empty_rowset;
6466
0
                        }
6467
13
                    });
6468
1.61k
        }
6469
2.01k
        return 0;
6470
2.01k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6375
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6376
2.01k
        ++num_scanned;
6377
2.01k
        total_rowset_key_size += k.size();
6378
2.01k
        total_rowset_value_size += v.size();
6379
2.01k
        RecycleRowsetPB rowset;
6380
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6381
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6382
0
            return -1;
6383
0
        }
6384
6385
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6386
6387
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6388
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6389
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6390
2.01k
        int64_t current_time = ::time(nullptr);
6391
2.01k
        if (current_time < final_expiration) { // not expired
6392
0
            return 0;
6393
0
        }
6394
2.01k
        ++num_expired;
6395
2.01k
        expired_rowset_size += v.size();
6396
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6397
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6398
                // in old version, keep this key-value pair and it needs to be checked manually
6399
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6400
0
                return -1;
6401
0
            }
6402
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6403
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6404
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6405
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6406
0
                orphan_rowset_keys.emplace_back(k);
6407
0
                return -1;
6408
0
            }
6409
            // decode rowset_id
6410
0
            auto k1 = k;
6411
0
            k1.remove_prefix(1);
6412
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6413
0
            decode_key(&k1, &out);
6414
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6415
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6416
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6417
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6418
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6419
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6420
0
                return -1;
6421
0
            }
6422
0
            return 0;
6423
0
        }
6424
        // TODO(plat1ko): check rowset not referenced
6425
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6426
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6427
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6428
0
                LOG_INFO("recycle rowset that has empty resource id");
6429
0
            } else {
6430
                // other situations, keep this key-value pair and it needs to be checked manually
6431
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6432
0
                return -1;
6433
0
            }
6434
0
        }
6435
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6436
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6437
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6438
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6439
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6440
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6441
2.01k
                  << " rowset_meta_size=" << v.size()
6442
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6443
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6444
            // unable to calculate file path, can only be deleted by rowset id prefix
6445
400
            num_prepare += 1;
6446
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6447
400
                                             rowset_meta->tablet_id(),
6448
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6449
0
                return -1;
6450
0
            }
6451
1.61k
        } else {
6452
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6453
1.61k
            worker_pool->submit(
6454
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6455
                        // The load & compact rowset keys are recycled during recycling operation logs.
6456
1.61k
                        RowsetDeleteTask task;
6457
1.61k
                        task.rowset_meta = rowset_meta;
6458
1.61k
                        task.recycle_rowset_key = k;
6459
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6460
1.61k
                            return;
6461
1.61k
                        }
6462
1.61k
                        num_compacted += is_compacted;
6463
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6464
1.61k
                        if (rowset_meta.num_segments() == 0) {
6465
1.61k
                            ++num_empty_rowset;
6466
1.61k
                        }
6467
1.61k
                    });
6468
1.61k
        }
6469
2.01k
        return 0;
6470
2.01k
    };
6471
6472
11
    if (config::enable_recycler_stats_metrics) {
6473
0
        scan_and_statistics_rowsets();
6474
0
    }
6475
6476
11
    auto loop_done = [&]() -> int {
6477
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6478
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6479
0
        }
6480
6
        orphan_rowset_keys.clear();
6481
6
        return 0;
6482
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6476
6
    auto loop_done = [&]() -> int {
6477
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6478
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6479
0
        }
6480
6
        orphan_rowset_keys.clear();
6481
6
        return 0;
6482
6
    };
6483
6484
    // recycle_func and loop_done for scan and recycle
6485
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6486
11
                               std::move(loop_done));
6487
6488
11
    worker_pool->stop();
6489
6490
11
    if (!async_recycled_rowset_keys.empty()) {
6491
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6492
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6493
0
            return -1;
6494
0
        } else {
6495
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6496
0
        }
6497
0
    }
6498
6499
    // Report final metrics after all concurrent tasks completed
6500
11
    segment_metrics_context_.report();
6501
11
    metrics_context.report();
6502
6503
11
    return ret;
6504
11
}
6505
6506
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6507
1.61k
    constexpr int MAX_RETRY = 10;
6508
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6509
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6510
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6511
1.61k
    std::string_view reference_instance_id = instance_id_;
6512
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6513
8
        reference_instance_id = rowset_meta.reference_instance_id();
6514
8
    }
6515
6516
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6517
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6518
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6519
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6520
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6521
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6522
1.61k
        std::unique_ptr<Transaction> txn;
6523
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6524
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6525
0
            LOG_WARNING("failed to create txn").tag("err", err);
6526
0
            return -1;
6527
0
        }
6528
6529
1.61k
        std::string rowset_ref_count_key =
6530
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6531
1.61k
        int64_t ref_count = 0;
6532
1.61k
        {
6533
1.61k
            std::string value;
6534
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6535
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6536
                // This is the old version rowset, we could recycle it directly.
6537
1.60k
                ref_count = 1;
6538
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6539
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6540
0
                return -1;
6541
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6542
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6543
0
                return -1;
6544
0
            }
6545
1.61k
        }
6546
6547
1.61k
        if (ref_count == 1) {
6548
            // It would not be added since it is recycling.
6549
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6550
1.60k
                LOG_WARNING("failed to delete rowset data");
6551
1.60k
                return -1;
6552
1.60k
            }
6553
6554
            // Reset the transaction to avoid timeout.
6555
10
            err = txn_kv_->create_txn(&txn);
6556
10
            if (err != TxnErrorCode::TXN_OK) {
6557
0
                LOG_WARNING("failed to create txn").tag("err", err);
6558
0
                return -1;
6559
0
            }
6560
10
            txn->remove(rowset_ref_count_key);
6561
10
            LOG_INFO("delete rowset data ref count key")
6562
10
                    .tag("txn_id", rowset_meta.txn_id())
6563
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6564
6565
10
            std::string dbm_start_key =
6566
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6567
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6568
10
                    {reference_instance_id, tablet_id, rowset_id,
6569
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6570
10
            txn->remove(dbm_start_key, dbm_end_key);
6571
10
            LOG_INFO("remove delete bitmap kv")
6572
10
                    .tag("begin", hex(dbm_start_key))
6573
10
                    .tag("end", hex(dbm_end_key));
6574
6575
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6576
10
                    {reference_instance_id, tablet_id, rowset_id});
6577
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6578
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6579
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6580
10
            LOG_INFO("remove versioned delete bitmap kv")
6581
10
                    .tag("begin", hex(versioned_dbm_start_key))
6582
10
                    .tag("end", hex(versioned_dbm_end_key));
6583
10
        } else {
6584
            // Decrease the rowset ref count.
6585
            //
6586
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6587
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6588
3
            txn->atomic_add(rowset_ref_count_key, -1);
6589
3
            LOG_INFO("decrease rowset data ref count")
6590
3
                    .tag("txn_id", rowset_meta.txn_id())
6591
3
                    .tag("ref_count", ref_count - 1)
6592
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6593
3
        }
6594
6595
13
        if (!task.versioned_rowset_key.empty()) {
6596
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6597
0
                                                          task.versionstamp);
6598
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6599
0
        }
6600
6601
13
        if (!task.non_versioned_rowset_key.empty()) {
6602
0
            txn->remove(task.non_versioned_rowset_key);
6603
0
            LOG_INFO("remove non versioned rowset key")
6604
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6605
0
        }
6606
6607
        // empty when recycle ref rowsets for deleted instance
6608
13
        if (!task.recycle_rowset_key.empty()) {
6609
13
            txn->remove(task.recycle_rowset_key);
6610
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6611
13
        }
6612
6613
13
        err = txn->commit();
6614
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6615
            // The rowset ref count key has been changed, we need to retry.
6616
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6617
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6618
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6619
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6620
0
            continue;
6621
13
        } else if (err != TxnErrorCode::TXN_OK) {
6622
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6623
0
            return -1;
6624
0
        }
6625
13
        LOG_INFO("recycle rowset meta and data success");
6626
13
        return 0;
6627
13
    }
6628
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6629
0
            .tag("tablet_id", tablet_id)
6630
0
            .tag("rowset_id", rowset_id)
6631
0
            .tag("retry", MAX_RETRY);
6632
0
    return -1;
6633
1.61k
}
6634
6635
37
int InstanceRecycler::recycle_tmp_rowsets() {
6636
37
    const std::string task_name = "recycle_tmp_rowsets";
6637
37
    int64_t num_scanned = 0;
6638
37
    int64_t num_expired = 0;
6639
37
    std::atomic_long num_recycled = 0;
6640
37
    size_t expired_rowset_size = 0;
6641
37
    size_t total_rowset_key_size = 0;
6642
37
    size_t total_rowset_value_size = 0;
6643
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6644
6645
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6646
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6647
37
    std::string tmp_rs_key0;
6648
37
    std::string tmp_rs_key1;
6649
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6650
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6651
6652
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6653
6654
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6655
37
    register_recycle_task(task_name, start_time);
6656
6657
37
    DORIS_CLOUD_DEFER {
6658
37
        unregister_recycle_task(task_name);
6659
37
        int64_t cost =
6660
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6661
37
        metrics_context.finish_report();
6662
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6663
37
                .tag("instance_id", instance_id_)
6664
37
                .tag("num_scanned", num_scanned)
6665
37
                .tag("num_expired", num_expired)
6666
37
                .tag("num_recycled", num_recycled)
6667
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6668
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6669
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6670
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6657
12
    DORIS_CLOUD_DEFER {
6658
12
        unregister_recycle_task(task_name);
6659
12
        int64_t cost =
6660
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6661
12
        metrics_context.finish_report();
6662
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6663
12
                .tag("instance_id", instance_id_)
6664
12
                .tag("num_scanned", num_scanned)
6665
12
                .tag("num_expired", num_expired)
6666
12
                .tag("num_recycled", num_recycled)
6667
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6668
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6669
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6670
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6657
25
    DORIS_CLOUD_DEFER {
6658
25
        unregister_recycle_task(task_name);
6659
25
        int64_t cost =
6660
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6661
25
        metrics_context.finish_report();
6662
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6663
25
                .tag("instance_id", instance_id_)
6664
25
                .tag("num_scanned", num_scanned)
6665
25
                .tag("num_expired", num_expired)
6666
25
                .tag("num_recycled", num_recycled)
6667
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6668
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6669
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6670
25
    };
6671
6672
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6673
37
    std::vector<std::string> tmp_rowset_keys;
6674
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6675
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6676
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6677
6678
    // rowset_id -> rowset_meta
6679
    // store tmp_rowset id and meta for statistics rs size when delete
6680
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6681
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6682
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6683
37
    worker_pool->start();
6684
6685
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6686
6687
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6688
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6689
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6690
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6691
53.2k
                                    std::string_view k, std::string_view v) -> int {
6692
53.2k
        ++num_scanned;
6693
53.2k
        total_rowset_key_size += k.size();
6694
53.2k
        total_rowset_value_size += v.size();
6695
53.2k
        doris::RowsetMetaCloudPB rowset;
6696
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6697
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6701
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6702
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6703
0
                   << " txn_expiration=" << rowset.txn_expiration()
6704
0
                   << " rowset_creation_time=" << rowset.creation_time();
6705
53.2k
        int64_t current_time = ::time(nullptr);
6706
53.2k
        if (current_time < expiration) { // not expired
6707
0
            return 0;
6708
0
        }
6709
53.2k
        ++num_expired;
6710
53.2k
        expired_rowset_size += v.size();
6711
53.2k
        if (!rowset.has_resource_id()) {
6712
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6713
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6714
0
                return -1;
6715
0
            }
6716
            // might be a delete pred rowset
6717
0
            tmp_rowset_keys.emplace_back(k);
6718
0
            return 0;
6719
0
        }
6720
6721
        // TODO(plat1ko): check rowset not referenced
6722
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6723
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6724
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6725
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6726
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6727
53.2k
                  << " num_expired=" << num_expired
6728
53.2k
                  << " task_type=" << metrics_context.operation_type;
6729
6730
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6731
16
            if (need_mark_rowset_as_recycled(rowset)) {
6732
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6733
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6734
9
                             "at next turn, instance_id="
6735
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6736
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6737
9
                return 0;
6738
9
            }
6739
16
        }
6740
6741
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6742
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6743
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6744
261
                             "instance_id="
6745
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6746
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6747
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6748
261
                return 0;
6749
261
            }
6750
265
        }
6751
6752
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6753
        // Remove the rowset ref count key directly since it has not been used.
6754
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6755
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6756
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6757
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6758
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6759
6760
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6761
53.0k
        return 0;
6762
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6691
16
                                    std::string_view k, std::string_view v) -> int {
6692
16
        ++num_scanned;
6693
16
        total_rowset_key_size += k.size();
6694
16
        total_rowset_value_size += v.size();
6695
16
        doris::RowsetMetaCloudPB rowset;
6696
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6697
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6701
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6702
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6703
0
                   << " txn_expiration=" << rowset.txn_expiration()
6704
0
                   << " rowset_creation_time=" << rowset.creation_time();
6705
16
        int64_t current_time = ::time(nullptr);
6706
16
        if (current_time < expiration) { // not expired
6707
0
            return 0;
6708
0
        }
6709
16
        ++num_expired;
6710
16
        expired_rowset_size += v.size();
6711
16
        if (!rowset.has_resource_id()) {
6712
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6713
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6714
0
                return -1;
6715
0
            }
6716
            // might be a delete pred rowset
6717
0
            tmp_rowset_keys.emplace_back(k);
6718
0
            return 0;
6719
0
        }
6720
6721
        // TODO(plat1ko): check rowset not referenced
6722
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6723
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6724
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6725
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6726
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6727
16
                  << " num_expired=" << num_expired
6728
16
                  << " task_type=" << metrics_context.operation_type;
6729
6730
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6731
16
            if (need_mark_rowset_as_recycled(rowset)) {
6732
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6733
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6734
9
                             "at next turn, instance_id="
6735
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6736
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6737
9
                return 0;
6738
9
            }
6739
16
        }
6740
6741
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6742
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6743
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6744
3
                             "instance_id="
6745
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6746
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6747
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6748
3
                return 0;
6749
3
            }
6750
7
        }
6751
6752
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6753
        // Remove the rowset ref count key directly since it has not been used.
6754
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6755
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6756
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6757
4
                  << "key=" << hex(rowset_ref_count_key);
6758
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6759
6760
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6761
4
        return 0;
6762
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6691
53.2k
                                    std::string_view k, std::string_view v) -> int {
6692
53.2k
        ++num_scanned;
6693
53.2k
        total_rowset_key_size += k.size();
6694
53.2k
        total_rowset_value_size += v.size();
6695
53.2k
        doris::RowsetMetaCloudPB rowset;
6696
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6697
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6701
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6702
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6703
0
                   << " txn_expiration=" << rowset.txn_expiration()
6704
0
                   << " rowset_creation_time=" << rowset.creation_time();
6705
53.2k
        int64_t current_time = ::time(nullptr);
6706
53.2k
        if (current_time < expiration) { // not expired
6707
0
            return 0;
6708
0
        }
6709
53.2k
        ++num_expired;
6710
53.2k
        expired_rowset_size += v.size();
6711
53.2k
        if (!rowset.has_resource_id()) {
6712
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6713
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6714
0
                return -1;
6715
0
            }
6716
            // might be a delete pred rowset
6717
0
            tmp_rowset_keys.emplace_back(k);
6718
0
            return 0;
6719
0
        }
6720
6721
        // TODO(plat1ko): check rowset not referenced
6722
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6723
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6724
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6725
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6726
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6727
53.2k
                  << " num_expired=" << num_expired
6728
53.2k
                  << " task_type=" << metrics_context.operation_type;
6729
6730
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6731
0
            if (need_mark_rowset_as_recycled(rowset)) {
6732
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6733
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6734
0
                             "at next turn, instance_id="
6735
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6736
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6737
0
                return 0;
6738
0
            }
6739
0
        }
6740
6741
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6742
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6743
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6744
258
                             "instance_id="
6745
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6746
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6747
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6748
258
                return 0;
6749
258
            }
6750
258
        }
6751
6752
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6753
        // Remove the rowset ref count key directly since it has not been used.
6754
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6755
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6756
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6757
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6758
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6759
6760
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6761
53.0k
        return 0;
6762
53.2k
    };
6763
6764
37
    auto loop_done = [&]() -> int {
6765
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6766
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6767
24
        std::vector<std::string> mark_keys_to_process;
6768
24
        std::vector<std::string> abort_keys_to_process;
6769
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6770
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6771
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6772
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6773
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6774
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6775
24
        if (!mark_keys_to_process.empty()) {
6776
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6777
7
                    *worker_pool, std::move(mark_keys_to_process));
6778
7
        }
6779
24
        if (!abort_keys_to_process.empty()) {
6780
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6781
5
                                           &num_recycled, &metrics_context);
6782
5
        }
6783
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6784
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6785
24
                             tmp_rowset_ref_count_keys_to_delete =
6786
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6787
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6788
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6789
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6790
24
                                   metrics_context) != 0) {
6791
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6792
2
                return;
6793
2
            }
6794
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6795
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6796
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6797
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6798
0
                                 << rs.ShortDebugString();
6799
0
                    return;
6800
0
                }
6801
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6802
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6803
0
                                 << rs.ShortDebugString();
6804
0
                    return;
6805
0
                }
6806
51.0k
            }
6807
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6808
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6809
0
                return;
6810
0
            }
6811
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6812
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6813
0
                return;
6814
0
            }
6815
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6816
22
            return;
6817
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6788
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6789
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6790
12
                                   metrics_context) != 0) {
6791
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6792
0
                return;
6793
0
            }
6794
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6795
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6796
4
                                                       rs.rowset_id_v2()) != 0) {
6797
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6798
0
                                 << rs.ShortDebugString();
6799
0
                    return;
6800
0
                }
6801
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6802
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6803
0
                                 << rs.ShortDebugString();
6804
0
                    return;
6805
0
                }
6806
4
            }
6807
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6808
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6809
0
                return;
6810
0
            }
6811
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6812
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6813
0
                return;
6814
0
            }
6815
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6816
12
            return;
6817
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6788
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6789
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6790
12
                                   metrics_context) != 0) {
6791
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6792
2
                return;
6793
2
            }
6794
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6795
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6796
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6797
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6798
0
                                 << rs.ShortDebugString();
6799
0
                    return;
6800
0
                }
6801
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6802
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6803
0
                                 << rs.ShortDebugString();
6804
0
                    return;
6805
0
                }
6806
51.0k
            }
6807
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6808
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6809
0
                return;
6810
0
            }
6811
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6812
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6813
0
                return;
6814
0
            }
6815
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6816
10
            return;
6817
10
        });
6818
24
        return 0;
6819
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6764
12
    auto loop_done = [&]() -> int {
6765
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6766
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6767
12
        std::vector<std::string> mark_keys_to_process;
6768
12
        std::vector<std::string> abort_keys_to_process;
6769
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6770
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6771
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6772
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6773
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6774
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6775
12
        if (!mark_keys_to_process.empty()) {
6776
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6777
7
                    *worker_pool, std::move(mark_keys_to_process));
6778
7
        }
6779
12
        if (!abort_keys_to_process.empty()) {
6780
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6781
3
                                           &num_recycled, &metrics_context);
6782
3
        }
6783
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6784
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6785
12
                             tmp_rowset_ref_count_keys_to_delete =
6786
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6787
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6788
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6789
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6790
12
                                   metrics_context) != 0) {
6791
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6792
12
                return;
6793
12
            }
6794
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6795
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6796
12
                                                       rs.rowset_id_v2()) != 0) {
6797
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6798
12
                                 << rs.ShortDebugString();
6799
12
                    return;
6800
12
                }
6801
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6802
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6803
12
                                 << rs.ShortDebugString();
6804
12
                    return;
6805
12
                }
6806
12
            }
6807
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6808
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6809
12
                return;
6810
12
            }
6811
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6812
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6813
12
                return;
6814
12
            }
6815
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6816
12
            return;
6817
12
        });
6818
12
        return 0;
6819
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6764
12
    auto loop_done = [&]() -> int {
6765
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6766
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6767
12
        std::vector<std::string> mark_keys_to_process;
6768
12
        std::vector<std::string> abort_keys_to_process;
6769
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6770
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6771
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6772
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6773
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6774
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6775
12
        if (!mark_keys_to_process.empty()) {
6776
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6777
0
                    *worker_pool, std::move(mark_keys_to_process));
6778
0
        }
6779
12
        if (!abort_keys_to_process.empty()) {
6780
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6781
2
                                           &num_recycled, &metrics_context);
6782
2
        }
6783
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6784
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6785
12
                             tmp_rowset_ref_count_keys_to_delete =
6786
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6787
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6788
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6789
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6790
12
                                   metrics_context) != 0) {
6791
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6792
12
                return;
6793
12
            }
6794
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6795
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6796
12
                                                       rs.rowset_id_v2()) != 0) {
6797
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6798
12
                                 << rs.ShortDebugString();
6799
12
                    return;
6800
12
                }
6801
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6802
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6803
12
                                 << rs.ShortDebugString();
6804
12
                    return;
6805
12
                }
6806
12
            }
6807
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6808
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6809
12
                return;
6810
12
            }
6811
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6812
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6813
12
                return;
6814
12
            }
6815
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6816
12
            return;
6817
12
        });
6818
12
        return 0;
6819
12
    };
6820
6821
37
    if (config::enable_recycler_stats_metrics) {
6822
0
        scan_and_statistics_tmp_rowsets();
6823
0
    }
6824
    // recycle_func and loop_done for scan and recycle
6825
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6826
37
                               std::move(loop_done));
6827
6828
37
    worker_pool->stop();
6829
6830
    // Report final metrics after all concurrent tasks completed
6831
37
    segment_metrics_context_.report();
6832
37
    metrics_context.report();
6833
6834
37
    return ret;
6835
37
}
6836
6837
int InstanceRecycler::scan_and_recycle(
6838
        std::string begin, std::string_view end,
6839
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6840
366
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6841
366
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6842
366
    int ret = 0;
6843
366
    int64_t cnt = 0;
6844
366
    int get_range_retried = 0;
6845
366
    std::string err;
6846
366
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6847
366
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6848
366
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6849
366
                  << " ret=" << ret << " err=" << err;
6850
366
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6846
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6847
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6848
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6849
39
                  << " ret=" << ret << " err=" << err;
6850
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6846
327
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6847
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6848
327
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6849
327
                  << " ret=" << ret << " err=" << err;
6850
327
    };
6851
6852
366
    std::unique_ptr<RangeGetIterator> it;
6853
585
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6854
403
        if (get_range_retried > 1000) {
6855
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6856
0
            ret = -3;
6857
0
            return ret;
6858
0
        }
6859
403
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6860
403
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6861
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6862
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6863
0
                         << " get_range_retried=" << get_range_retried;
6864
0
            ++get_range_retried;
6865
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6866
0
            continue; // try again
6867
0
        }
6868
403
        if (!it->has_next()) {
6869
184
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6870
184
            break; // scan finished
6871
184
        }
6872
219
        bool begin_updated = false;
6873
219
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6874
219
                  << ") iterator->size()=" << it->size();
6875
118k
        while (it->has_next()) {
6876
118k
            ++cnt;
6877
            // recycle corresponding resources
6878
118k
            auto [k, v] = it->next();
6879
118k
            if (!it->has_next()) {
6880
213
                begin = k;
6881
213
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6882
213
            }
6883
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6884
118k
            if (recycle_func(k, v) != 0) {
6885
4.00k
                err = "recycle_func error";
6886
4.00k
                ret = -1;
6887
4.00k
            }
6888
118k
            if (next_begin_getter) {
6889
4.33k
                std::string next_begin;
6890
4.33k
                if (next_begin_getter(&next_begin)) {
6891
7
                    if (next_begin > k) {
6892
7
                        begin = std::move(next_begin);
6893
7
                        begin_updated = true;
6894
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6895
0
                                   << " after key=" << hex(k);
6896
7
                        break;
6897
7
                    }
6898
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6899
0
                            .tag("next_begin", hex(next_begin))
6900
0
                            .tag("current_key", hex(k));
6901
0
                }
6902
4.33k
            }
6903
118k
        }
6904
219
        if (!begin_updated) {
6905
212
            begin.push_back('\x00'); // Update to next smallest key for iteration
6906
212
        } else {
6907
7
            it.reset();
6908
7
        }
6909
6910
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6911
        // if we want to continue scanning, the recycle_func should not return non-zero
6912
219
        if (loop_done && loop_done() != 0) {
6913
5
            err = "loop_done error";
6914
5
            ret = -1;
6915
5
        }
6916
219
    }
6917
366
    return ret;
6918
366
}
6919
6920
19
int InstanceRecycler::abort_timeout_txn() {
6921
19
    const std::string task_name = "abort_timeout_txn";
6922
19
    int64_t num_scanned = 0;
6923
19
    int64_t num_timeout = 0;
6924
19
    int64_t num_abort = 0;
6925
19
    int64_t num_advance = 0;
6926
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6927
6928
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6929
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6930
19
    std::string begin_txn_running_key;
6931
19
    std::string end_txn_running_key;
6932
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6933
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6934
6935
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6936
6937
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6938
19
    register_recycle_task(task_name, start_time);
6939
6940
19
    DORIS_CLOUD_DEFER {
6941
19
        unregister_recycle_task(task_name);
6942
19
        int64_t cost =
6943
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6944
19
        metrics_context.finish_report();
6945
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6946
19
                .tag("instance_id", instance_id_)
6947
19
                .tag("num_scanned", num_scanned)
6948
19
                .tag("num_timeout", num_timeout)
6949
19
                .tag("num_abort", num_abort)
6950
19
                .tag("num_advance", num_advance);
6951
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6940
3
    DORIS_CLOUD_DEFER {
6941
3
        unregister_recycle_task(task_name);
6942
3
        int64_t cost =
6943
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6944
3
        metrics_context.finish_report();
6945
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6946
3
                .tag("instance_id", instance_id_)
6947
3
                .tag("num_scanned", num_scanned)
6948
3
                .tag("num_timeout", num_timeout)
6949
3
                .tag("num_abort", num_abort)
6950
3
                .tag("num_advance", num_advance);
6951
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6940
16
    DORIS_CLOUD_DEFER {
6941
16
        unregister_recycle_task(task_name);
6942
16
        int64_t cost =
6943
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6944
16
        metrics_context.finish_report();
6945
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6946
16
                .tag("instance_id", instance_id_)
6947
16
                .tag("num_scanned", num_scanned)
6948
16
                .tag("num_timeout", num_timeout)
6949
16
                .tag("num_abort", num_abort)
6950
16
                .tag("num_advance", num_advance);
6951
16
    };
6952
6953
19
    int64_t current_time =
6954
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6955
6956
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6957
19
                                  &current_time, &metrics_context,
6958
19
                                  this](std::string_view k, std::string_view v) -> int {
6959
9
        ++num_scanned;
6960
6961
9
        std::unique_ptr<Transaction> txn;
6962
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6963
9
        if (err != TxnErrorCode::TXN_OK) {
6964
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6965
0
            return -1;
6966
0
        }
6967
9
        std::string_view k1 = k;
6968
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6969
9
        k1.remove_prefix(1); // Remove key space
6970
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6971
9
        if (decode_key(&k1, &out) != 0) {
6972
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6976
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6977
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6978
        // Update txn_info
6979
9
        std::string txn_inf_key, txn_inf_val;
6980
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6981
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6982
9
        if (err != TxnErrorCode::TXN_OK) {
6983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6984
0
            return -1;
6985
0
        }
6986
9
        TxnInfoPB txn_info;
6987
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6989
0
            return -1;
6990
0
        }
6991
6992
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6993
3
            txn.reset();
6994
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6995
3
            std::shared_ptr<TxnLazyCommitTask> task =
6996
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6997
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6998
3
            if (ret.first != MetaServiceCode::OK) {
6999
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7000
0
                             << "msg=" << ret.second;
7001
0
                return -1;
7002
0
            }
7003
3
            ++num_advance;
7004
3
            return 0;
7005
6
        } else {
7006
6
            TxnRunningPB txn_running_pb;
7007
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7008
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7009
0
                return -1;
7010
0
            }
7011
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7012
4
                return 0;
7013
4
            }
7014
2
            ++num_timeout;
7015
7016
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7017
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7018
2
            txn_info.set_finish_time(current_time);
7019
2
            txn_info.set_reason("timeout");
7020
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7021
2
            txn_inf_val.clear();
7022
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7023
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7024
0
                return -1;
7025
0
            }
7026
2
            txn->put(txn_inf_key, txn_inf_val);
7027
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7028
            // Put recycle txn key
7029
2
            std::string recyc_txn_key, recyc_txn_val;
7030
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7031
2
            RecycleTxnPB recycle_txn_pb;
7032
2
            recycle_txn_pb.set_creation_time(current_time);
7033
2
            recycle_txn_pb.set_label(txn_info.label());
7034
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7035
0
                LOG_WARNING("failed to serialize txn recycle info")
7036
0
                        .tag("key", hex(k))
7037
0
                        .tag("db_id", db_id)
7038
0
                        .tag("txn_id", txn_id);
7039
0
                return -1;
7040
0
            }
7041
2
            txn->put(recyc_txn_key, recyc_txn_val);
7042
            // Remove txn running key
7043
2
            txn->remove(k);
7044
2
            err = txn->commit();
7045
2
            if (err != TxnErrorCode::TXN_OK) {
7046
0
                LOG_WARNING("failed to commit txn err={}", err)
7047
0
                        .tag("key", hex(k))
7048
0
                        .tag("db_id", db_id)
7049
0
                        .tag("txn_id", txn_id);
7050
0
                return -1;
7051
0
            }
7052
2
            metrics_context.total_recycled_num = ++num_abort;
7053
2
            metrics_context.report();
7054
2
        }
7055
7056
2
        return 0;
7057
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6958
3
                                  this](std::string_view k, std::string_view v) -> int {
6959
3
        ++num_scanned;
6960
6961
3
        std::unique_ptr<Transaction> txn;
6962
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6963
3
        if (err != TxnErrorCode::TXN_OK) {
6964
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6965
0
            return -1;
6966
0
        }
6967
3
        std::string_view k1 = k;
6968
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6969
3
        k1.remove_prefix(1); // Remove key space
6970
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6971
3
        if (decode_key(&k1, &out) != 0) {
6972
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6976
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6977
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6978
        // Update txn_info
6979
3
        std::string txn_inf_key, txn_inf_val;
6980
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6981
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6982
3
        if (err != TxnErrorCode::TXN_OK) {
6983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6984
0
            return -1;
6985
0
        }
6986
3
        TxnInfoPB txn_info;
6987
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6989
0
            return -1;
6990
0
        }
6991
6992
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6993
3
            txn.reset();
6994
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6995
3
            std::shared_ptr<TxnLazyCommitTask> task =
6996
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6997
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6998
3
            if (ret.first != MetaServiceCode::OK) {
6999
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7000
0
                             << "msg=" << ret.second;
7001
0
                return -1;
7002
0
            }
7003
3
            ++num_advance;
7004
3
            return 0;
7005
3
        } else {
7006
0
            TxnRunningPB txn_running_pb;
7007
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7008
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7009
0
                return -1;
7010
0
            }
7011
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7012
0
                return 0;
7013
0
            }
7014
0
            ++num_timeout;
7015
7016
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7017
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7018
0
            txn_info.set_finish_time(current_time);
7019
0
            txn_info.set_reason("timeout");
7020
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7021
0
            txn_inf_val.clear();
7022
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7023
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7024
0
                return -1;
7025
0
            }
7026
0
            txn->put(txn_inf_key, txn_inf_val);
7027
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7028
            // Put recycle txn key
7029
0
            std::string recyc_txn_key, recyc_txn_val;
7030
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7031
0
            RecycleTxnPB recycle_txn_pb;
7032
0
            recycle_txn_pb.set_creation_time(current_time);
7033
0
            recycle_txn_pb.set_label(txn_info.label());
7034
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7035
0
                LOG_WARNING("failed to serialize txn recycle info")
7036
0
                        .tag("key", hex(k))
7037
0
                        .tag("db_id", db_id)
7038
0
                        .tag("txn_id", txn_id);
7039
0
                return -1;
7040
0
            }
7041
0
            txn->put(recyc_txn_key, recyc_txn_val);
7042
            // Remove txn running key
7043
0
            txn->remove(k);
7044
0
            err = txn->commit();
7045
0
            if (err != TxnErrorCode::TXN_OK) {
7046
0
                LOG_WARNING("failed to commit txn err={}", err)
7047
0
                        .tag("key", hex(k))
7048
0
                        .tag("db_id", db_id)
7049
0
                        .tag("txn_id", txn_id);
7050
0
                return -1;
7051
0
            }
7052
0
            metrics_context.total_recycled_num = ++num_abort;
7053
0
            metrics_context.report();
7054
0
        }
7055
7056
0
        return 0;
7057
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6958
6
                                  this](std::string_view k, std::string_view v) -> int {
6959
6
        ++num_scanned;
6960
6961
6
        std::unique_ptr<Transaction> txn;
6962
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6963
6
        if (err != TxnErrorCode::TXN_OK) {
6964
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6965
0
            return -1;
6966
0
        }
6967
6
        std::string_view k1 = k;
6968
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6969
6
        k1.remove_prefix(1); // Remove key space
6970
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6971
6
        if (decode_key(&k1, &out) != 0) {
6972
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6976
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6977
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6978
        // Update txn_info
6979
6
        std::string txn_inf_key, txn_inf_val;
6980
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6981
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6982
6
        if (err != TxnErrorCode::TXN_OK) {
6983
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6984
0
            return -1;
6985
0
        }
6986
6
        TxnInfoPB txn_info;
6987
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6988
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6989
0
            return -1;
6990
0
        }
6991
6992
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6993
0
            txn.reset();
6994
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6995
0
            std::shared_ptr<TxnLazyCommitTask> task =
6996
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6997
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6998
0
            if (ret.first != MetaServiceCode::OK) {
6999
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7000
0
                             << "msg=" << ret.second;
7001
0
                return -1;
7002
0
            }
7003
0
            ++num_advance;
7004
0
            return 0;
7005
6
        } else {
7006
6
            TxnRunningPB txn_running_pb;
7007
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7008
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7009
0
                return -1;
7010
0
            }
7011
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7012
4
                return 0;
7013
4
            }
7014
2
            ++num_timeout;
7015
7016
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7017
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7018
2
            txn_info.set_finish_time(current_time);
7019
2
            txn_info.set_reason("timeout");
7020
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7021
2
            txn_inf_val.clear();
7022
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7023
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7024
0
                return -1;
7025
0
            }
7026
2
            txn->put(txn_inf_key, txn_inf_val);
7027
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7028
            // Put recycle txn key
7029
2
            std::string recyc_txn_key, recyc_txn_val;
7030
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7031
2
            RecycleTxnPB recycle_txn_pb;
7032
2
            recycle_txn_pb.set_creation_time(current_time);
7033
2
            recycle_txn_pb.set_label(txn_info.label());
7034
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7035
0
                LOG_WARNING("failed to serialize txn recycle info")
7036
0
                        .tag("key", hex(k))
7037
0
                        .tag("db_id", db_id)
7038
0
                        .tag("txn_id", txn_id);
7039
0
                return -1;
7040
0
            }
7041
2
            txn->put(recyc_txn_key, recyc_txn_val);
7042
            // Remove txn running key
7043
2
            txn->remove(k);
7044
2
            err = txn->commit();
7045
2
            if (err != TxnErrorCode::TXN_OK) {
7046
0
                LOG_WARNING("failed to commit txn err={}", err)
7047
0
                        .tag("key", hex(k))
7048
0
                        .tag("db_id", db_id)
7049
0
                        .tag("txn_id", txn_id);
7050
0
                return -1;
7051
0
            }
7052
2
            metrics_context.total_recycled_num = ++num_abort;
7053
2
            metrics_context.report();
7054
2
        }
7055
7056
2
        return 0;
7057
6
    };
7058
7059
19
    if (config::enable_recycler_stats_metrics) {
7060
0
        scan_and_statistics_abort_timeout_txn();
7061
0
    }
7062
    // recycle_func and loop_done for scan and recycle
7063
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7064
19
                            std::move(handle_txn_running_kv));
7065
19
}
7066
7067
19
int InstanceRecycler::recycle_expired_txn_label() {
7068
19
    const std::string task_name = "recycle_expired_txn_label";
7069
19
    int64_t num_scanned = 0;
7070
19
    int64_t num_expired = 0;
7071
19
    std::atomic_long num_recycled = 0;
7072
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7073
19
    int ret = 0;
7074
7075
19
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7076
19
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7077
19
    std::string begin_recycle_txn_key;
7078
19
    std::string end_recycle_txn_key;
7079
19
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7080
19
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7081
19
    std::vector<std::string> recycle_txn_info_keys;
7082
7083
19
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
7084
7085
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7086
19
    register_recycle_task(task_name, start_time);
7087
19
    DORIS_CLOUD_DEFER {
7088
19
        unregister_recycle_task(task_name);
7089
19
        int64_t cost =
7090
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7091
19
        metrics_context.finish_report();
7092
19
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7093
19
                .tag("instance_id", instance_id_)
7094
19
                .tag("num_scanned", num_scanned)
7095
19
                .tag("num_expired", num_expired)
7096
19
                .tag("num_recycled", num_recycled);
7097
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7087
1
    DORIS_CLOUD_DEFER {
7088
1
        unregister_recycle_task(task_name);
7089
1
        int64_t cost =
7090
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7091
1
        metrics_context.finish_report();
7092
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7093
1
                .tag("instance_id", instance_id_)
7094
1
                .tag("num_scanned", num_scanned)
7095
1
                .tag("num_expired", num_expired)
7096
1
                .tag("num_recycled", num_recycled);
7097
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7087
18
    DORIS_CLOUD_DEFER {
7088
18
        unregister_recycle_task(task_name);
7089
18
        int64_t cost =
7090
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7091
18
        metrics_context.finish_report();
7092
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7093
18
                .tag("instance_id", instance_id_)
7094
18
                .tag("num_scanned", num_scanned)
7095
18
                .tag("num_expired", num_expired)
7096
18
                .tag("num_recycled", num_recycled);
7097
18
    };
7098
7099
19
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7100
7101
19
    SyncExecutor<int> concurrent_delete_executor(
7102
19
            _thread_pool_group.s3_producer_pool,
7103
19
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7104
23.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7104
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7104
23.0k
            [](const int& ret) { return ret != 0; });
7105
7106
19
    int64_t current_time_ms =
7107
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7108
7109
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7110
30.0k
        ++num_scanned;
7111
30.0k
        RecycleTxnPB recycle_txn_pb;
7112
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7113
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7114
0
            return -1;
7115
0
        }
7116
30.0k
        if ((config::force_immediate_recycle) ||
7117
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7118
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7119
30.0k
             current_time_ms)) {
7120
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7121
23.0k
            num_expired++;
7122
23.0k
            recycle_txn_info_keys.emplace_back(k);
7123
23.0k
        }
7124
30.0k
        return 0;
7125
30.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7109
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7110
1
        ++num_scanned;
7111
1
        RecycleTxnPB recycle_txn_pb;
7112
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7113
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7114
0
            return -1;
7115
0
        }
7116
1
        if ((config::force_immediate_recycle) ||
7117
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7118
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7119
1
             current_time_ms)) {
7120
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7121
1
            num_expired++;
7122
1
            recycle_txn_info_keys.emplace_back(k);
7123
1
        }
7124
1
        return 0;
7125
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7109
30.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7110
30.0k
        ++num_scanned;
7111
30.0k
        RecycleTxnPB recycle_txn_pb;
7112
30.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7113
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7114
0
            return -1;
7115
0
        }
7116
30.0k
        if ((config::force_immediate_recycle) ||
7117
30.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7118
30.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7119
30.0k
             current_time_ms)) {
7120
23.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7121
23.0k
            num_expired++;
7122
23.0k
            recycle_txn_info_keys.emplace_back(k);
7123
23.0k
        }
7124
30.0k
        return 0;
7125
30.0k
    };
7126
7127
    // int 0 for success, 1 for conflict, -1 for error
7128
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7129
23.0k
        std::string_view k1 = k;
7130
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7131
23.0k
        k1.remove_prefix(1); // Remove key space
7132
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7133
23.0k
        int ret = decode_key(&k1, &out);
7134
23.0k
        if (ret != 0) {
7135
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7136
0
            return -1;
7137
0
        }
7138
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7139
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7140
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7141
23.0k
        std::unique_ptr<Transaction> txn;
7142
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7143
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7144
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7145
0
            return -1;
7146
0
        }
7147
        // Remove txn index kv
7148
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7149
23.0k
        txn->remove(index_key);
7150
        // Remove txn info kv
7151
23.0k
        std::string info_key, info_val;
7152
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7153
23.0k
        err = txn->get(info_key, &info_val);
7154
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7155
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7156
0
            return -1;
7157
0
        }
7158
23.0k
        TxnInfoPB txn_info;
7159
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7160
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7161
0
            return -1;
7162
0
        }
7163
23.0k
        txn->remove(info_key);
7164
        // Remove sub txn index kvs
7165
23.0k
        std::vector<std::string> sub_txn_index_keys;
7166
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7167
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7168
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7169
23.0k
        }
7170
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7171
22.9k
            txn->remove(sub_txn_index_key);
7172
22.9k
        }
7173
        // Update txn label
7174
23.0k
        std::string label_key, label_val;
7175
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7176
23.0k
        err = txn->get(label_key, &label_val);
7177
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7178
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7179
0
                         << " err=" << err;
7180
0
            return -1;
7181
0
        }
7182
23.0k
        TxnLabelPB txn_label;
7183
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7184
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7185
0
            return -1;
7186
0
        }
7187
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7188
23.0k
        if (it != txn_label.txn_ids().end()) {
7189
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7190
23.0k
        }
7191
23.0k
        if (txn_label.txn_ids().empty()) {
7192
23.0k
            txn->remove(label_key);
7193
23.0k
            TEST_SYNC_POINT_CALLBACK(
7194
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7195
23.0k
        } else {
7196
73
            if (!txn_label.SerializeToString(&label_val)) {
7197
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7198
0
                return -1;
7199
0
            }
7200
73
            TEST_SYNC_POINT_CALLBACK(
7201
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7202
73
            txn->atomic_set_ver_value(label_key, label_val);
7203
73
            TEST_SYNC_POINT_CALLBACK(
7204
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7205
73
        }
7206
        // Remove recycle txn kv
7207
23.0k
        txn->remove(k);
7208
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7209
23.0k
        err = txn->commit();
7210
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7211
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7212
62
                TEST_SYNC_POINT_CALLBACK(
7213
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7214
                // log the txn_id and label
7215
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7216
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7217
62
                             << " txn_label=" << txn_info.label();
7218
62
                return 1;
7219
62
            }
7220
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7221
0
            return -1;
7222
62
        }
7223
23.0k
        ++num_recycled;
7224
7225
23.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7226
23.0k
        return 0;
7227
23.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7128
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7129
1
        std::string_view k1 = k;
7130
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7131
1
        k1.remove_prefix(1); // Remove key space
7132
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7133
1
        int ret = decode_key(&k1, &out);
7134
1
        if (ret != 0) {
7135
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7136
0
            return -1;
7137
0
        }
7138
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7139
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7140
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7141
1
        std::unique_ptr<Transaction> txn;
7142
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7143
1
        if (err != TxnErrorCode::TXN_OK) {
7144
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7145
0
            return -1;
7146
0
        }
7147
        // Remove txn index kv
7148
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7149
1
        txn->remove(index_key);
7150
        // Remove txn info kv
7151
1
        std::string info_key, info_val;
7152
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7153
1
        err = txn->get(info_key, &info_val);
7154
1
        if (err != TxnErrorCode::TXN_OK) {
7155
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7156
0
            return -1;
7157
0
        }
7158
1
        TxnInfoPB txn_info;
7159
1
        if (!txn_info.ParseFromString(info_val)) {
7160
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7161
0
            return -1;
7162
0
        }
7163
1
        txn->remove(info_key);
7164
        // Remove sub txn index kvs
7165
1
        std::vector<std::string> sub_txn_index_keys;
7166
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7167
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7168
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7169
0
        }
7170
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7171
0
            txn->remove(sub_txn_index_key);
7172
0
        }
7173
        // Update txn label
7174
1
        std::string label_key, label_val;
7175
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7176
1
        err = txn->get(label_key, &label_val);
7177
1
        if (err != TxnErrorCode::TXN_OK) {
7178
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7179
0
                         << " err=" << err;
7180
0
            return -1;
7181
0
        }
7182
1
        TxnLabelPB txn_label;
7183
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7184
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7185
0
            return -1;
7186
0
        }
7187
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7188
1
        if (it != txn_label.txn_ids().end()) {
7189
1
            txn_label.mutable_txn_ids()->erase(it);
7190
1
        }
7191
1
        if (txn_label.txn_ids().empty()) {
7192
1
            txn->remove(label_key);
7193
1
            TEST_SYNC_POINT_CALLBACK(
7194
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7195
1
        } else {
7196
0
            if (!txn_label.SerializeToString(&label_val)) {
7197
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7198
0
                return -1;
7199
0
            }
7200
0
            TEST_SYNC_POINT_CALLBACK(
7201
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7202
0
            txn->atomic_set_ver_value(label_key, label_val);
7203
0
            TEST_SYNC_POINT_CALLBACK(
7204
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7205
0
        }
7206
        // Remove recycle txn kv
7207
1
        txn->remove(k);
7208
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7209
1
        err = txn->commit();
7210
1
        if (err != TxnErrorCode::TXN_OK) {
7211
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7212
0
                TEST_SYNC_POINT_CALLBACK(
7213
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7214
                // log the txn_id and label
7215
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7216
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7217
0
                             << " txn_label=" << txn_info.label();
7218
0
                return 1;
7219
0
            }
7220
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7221
0
            return -1;
7222
0
        }
7223
1
        ++num_recycled;
7224
7225
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7226
1
        return 0;
7227
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7128
23.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7129
23.0k
        std::string_view k1 = k;
7130
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7131
23.0k
        k1.remove_prefix(1); // Remove key space
7132
23.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7133
23.0k
        int ret = decode_key(&k1, &out);
7134
23.0k
        if (ret != 0) {
7135
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7136
0
            return -1;
7137
0
        }
7138
23.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7139
23.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7140
23.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7141
23.0k
        std::unique_ptr<Transaction> txn;
7142
23.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7143
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7144
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7145
0
            return -1;
7146
0
        }
7147
        // Remove txn index kv
7148
23.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7149
23.0k
        txn->remove(index_key);
7150
        // Remove txn info kv
7151
23.0k
        std::string info_key, info_val;
7152
23.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7153
23.0k
        err = txn->get(info_key, &info_val);
7154
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7155
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7156
0
            return -1;
7157
0
        }
7158
23.0k
        TxnInfoPB txn_info;
7159
23.0k
        if (!txn_info.ParseFromString(info_val)) {
7160
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7161
0
            return -1;
7162
0
        }
7163
23.0k
        txn->remove(info_key);
7164
        // Remove sub txn index kvs
7165
23.0k
        std::vector<std::string> sub_txn_index_keys;
7166
23.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7167
23.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7168
23.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7169
23.0k
        }
7170
23.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7171
22.9k
            txn->remove(sub_txn_index_key);
7172
22.9k
        }
7173
        // Update txn label
7174
23.0k
        std::string label_key, label_val;
7175
23.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7176
23.0k
        err = txn->get(label_key, &label_val);
7177
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7178
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7179
0
                         << " err=" << err;
7180
0
            return -1;
7181
0
        }
7182
23.0k
        TxnLabelPB txn_label;
7183
23.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7184
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7185
0
            return -1;
7186
0
        }
7187
23.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7188
23.0k
        if (it != txn_label.txn_ids().end()) {
7189
23.0k
            txn_label.mutable_txn_ids()->erase(it);
7190
23.0k
        }
7191
23.0k
        if (txn_label.txn_ids().empty()) {
7192
23.0k
            txn->remove(label_key);
7193
23.0k
            TEST_SYNC_POINT_CALLBACK(
7194
23.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7195
23.0k
        } else {
7196
73
            if (!txn_label.SerializeToString(&label_val)) {
7197
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7198
0
                return -1;
7199
0
            }
7200
73
            TEST_SYNC_POINT_CALLBACK(
7201
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7202
73
            txn->atomic_set_ver_value(label_key, label_val);
7203
73
            TEST_SYNC_POINT_CALLBACK(
7204
73
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7205
73
        }
7206
        // Remove recycle txn kv
7207
23.0k
        txn->remove(k);
7208
23.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7209
23.0k
        err = txn->commit();
7210
23.0k
        if (err != TxnErrorCode::TXN_OK) {
7211
62
            if (err == TxnErrorCode::TXN_CONFLICT) {
7212
62
                TEST_SYNC_POINT_CALLBACK(
7213
62
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7214
                // log the txn_id and label
7215
62
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7216
62
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7217
62
                             << " txn_label=" << txn_info.label();
7218
62
                return 1;
7219
62
            }
7220
62
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7221
0
            return -1;
7222
62
        }
7223
23.0k
        ++num_recycled;
7224
7225
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7226
23.0k
        return 0;
7227
23.0k
    };
7228
7229
19
    auto loop_done = [&]() -> int {
7230
10
        DORIS_CLOUD_DEFER {
7231
10
            recycle_txn_info_keys.clear();
7232
10
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7230
1
        DORIS_CLOUD_DEFER {
7231
1
            recycle_txn_info_keys.clear();
7232
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7230
9
        DORIS_CLOUD_DEFER {
7231
9
            recycle_txn_info_keys.clear();
7232
9
        };
7233
10
        TEST_SYNC_POINT_CALLBACK(
7234
10
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7235
10
                &recycle_txn_info_keys);
7236
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7237
23.0k
            concurrent_delete_executor.add([&]() {
7238
23.0k
                int ret = delete_recycle_txn_kv(k);
7239
23.0k
                if (ret == 1) {
7240
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7241
54
                    for (int i = 1; i <= max_retry; ++i) {
7242
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7243
54
                        ret = delete_recycle_txn_kv(k);
7244
                        // clang-format off
7245
54
                        TEST_SYNC_POINT_CALLBACK(
7246
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7247
                        // clang-format off
7248
54
                        if (ret != 1) {
7249
18
                            break;
7250
18
                        }
7251
                        // random sleep 0-100 ms to retry
7252
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7253
36
                    }
7254
18
                }
7255
23.0k
                if (ret != 0) {
7256
9
                    LOG_WARNING("failed to delete recycle txn kv")
7257
9
                            .tag("instance id", instance_id_)
7258
9
                            .tag("key", hex(k));
7259
9
                    return -1;
7260
9
                }
7261
23.0k
                return 0;
7262
23.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7237
1
            concurrent_delete_executor.add([&]() {
7238
1
                int ret = delete_recycle_txn_kv(k);
7239
1
                if (ret == 1) {
7240
0
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7241
0
                    for (int i = 1; i <= max_retry; ++i) {
7242
0
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7243
0
                        ret = delete_recycle_txn_kv(k);
7244
                        // clang-format off
7245
0
                        TEST_SYNC_POINT_CALLBACK(
7246
0
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7247
                        // clang-format off
7248
0
                        if (ret != 1) {
7249
0
                            break;
7250
0
                        }
7251
                        // random sleep 0-100 ms to retry
7252
0
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7253
0
                    }
7254
0
                }
7255
1
                if (ret != 0) {
7256
0
                    LOG_WARNING("failed to delete recycle txn kv")
7257
0
                            .tag("instance id", instance_id_)
7258
0
                            .tag("key", hex(k));
7259
0
                    return -1;
7260
0
                }
7261
1
                return 0;
7262
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7237
23.0k
            concurrent_delete_executor.add([&]() {
7238
23.0k
                int ret = delete_recycle_txn_kv(k);
7239
23.0k
                if (ret == 1) {
7240
18
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7241
54
                    for (int i = 1; i <= max_retry; ++i) {
7242
54
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7243
54
                        ret = delete_recycle_txn_kv(k);
7244
                        // clang-format off
7245
54
                        TEST_SYNC_POINT_CALLBACK(
7246
54
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7247
                        // clang-format off
7248
54
                        if (ret != 1) {
7249
18
                            break;
7250
18
                        }
7251
                        // random sleep 0-100 ms to retry
7252
36
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7253
36
                    }
7254
18
                }
7255
23.0k
                if (ret != 0) {
7256
9
                    LOG_WARNING("failed to delete recycle txn kv")
7257
9
                            .tag("instance id", instance_id_)
7258
9
                            .tag("key", hex(k));
7259
9
                    return -1;
7260
9
                }
7261
23.0k
                return 0;
7262
23.0k
            });
7263
23.0k
        }
7264
10
        bool finished = true;
7265
10
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7266
23.0k
        for (int r : rets) {
7267
23.0k
            if (r != 0) {
7268
9
                ret = -1;
7269
9
            }
7270
23.0k
        }
7271
7272
10
        ret = finished ? ret : -1;
7273
7274
        // Update metrics after all concurrent tasks completed
7275
10
        metrics_context.total_recycled_num = num_recycled.load();
7276
10
        metrics_context.report();
7277
7278
10
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7279
7280
10
        if (ret != 0) {
7281
3
            LOG_WARNING("recycle txn kv ret!=0")
7282
3
                    .tag("finished", finished)
7283
3
                    .tag("ret", ret)
7284
3
                    .tag("instance_id", instance_id_);
7285
3
            return ret;
7286
3
        }
7287
7
        return ret;
7288
10
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7229
1
    auto loop_done = [&]() -> int {
7230
1
        DORIS_CLOUD_DEFER {
7231
1
            recycle_txn_info_keys.clear();
7232
1
        };
7233
1
        TEST_SYNC_POINT_CALLBACK(
7234
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7235
1
                &recycle_txn_info_keys);
7236
1
        for (const auto& k : recycle_txn_info_keys) {
7237
1
            concurrent_delete_executor.add([&]() {
7238
1
                int ret = delete_recycle_txn_kv(k);
7239
1
                if (ret == 1) {
7240
1
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7241
1
                    for (int i = 1; i <= max_retry; ++i) {
7242
1
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7243
1
                        ret = delete_recycle_txn_kv(k);
7244
                        // clang-format off
7245
1
                        TEST_SYNC_POINT_CALLBACK(
7246
1
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7247
                        // clang-format off
7248
1
                        if (ret != 1) {
7249
1
                            break;
7250
1
                        }
7251
                        // random sleep 0-100 ms to retry
7252
1
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7253
1
                    }
7254
1
                }
7255
1
                if (ret != 0) {
7256
1
                    LOG_WARNING("failed to delete recycle txn kv")
7257
1
                            .tag("instance id", instance_id_)
7258
1
                            .tag("key", hex(k));
7259
1
                    return -1;
7260
1
                }
7261
1
                return 0;
7262
1
            });
7263
1
        }
7264
1
        bool finished = true;
7265
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7266
1
        for (int r : rets) {
7267
1
            if (r != 0) {
7268
0
                ret = -1;
7269
0
            }
7270
1
        }
7271
7272
1
        ret = finished ? ret : -1;
7273
7274
        // Update metrics after all concurrent tasks completed
7275
1
        metrics_context.total_recycled_num = num_recycled.load();
7276
1
        metrics_context.report();
7277
7278
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7279
7280
1
        if (ret != 0) {
7281
0
            LOG_WARNING("recycle txn kv ret!=0")
7282
0
                    .tag("finished", finished)
7283
0
                    .tag("ret", ret)
7284
0
                    .tag("instance_id", instance_id_);
7285
0
            return ret;
7286
0
        }
7287
1
        return ret;
7288
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7229
9
    auto loop_done = [&]() -> int {
7230
9
        DORIS_CLOUD_DEFER {
7231
9
            recycle_txn_info_keys.clear();
7232
9
        };
7233
9
        TEST_SYNC_POINT_CALLBACK(
7234
9
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_info_keys",
7235
9
                &recycle_txn_info_keys);
7236
23.0k
        for (const auto& k : recycle_txn_info_keys) {
7237
23.0k
            concurrent_delete_executor.add([&]() {
7238
23.0k
                int ret = delete_recycle_txn_kv(k);
7239
23.0k
                if (ret == 1) {
7240
23.0k
                    const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7241
23.0k
                    for (int i = 1; i <= max_retry; ++i) {
7242
23.0k
                        LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7243
23.0k
                        ret = delete_recycle_txn_kv(k);
7244
                        // clang-format off
7245
23.0k
                        TEST_SYNC_POINT_CALLBACK(
7246
23.0k
                                "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error", &ret);
7247
                        // clang-format off
7248
23.0k
                        if (ret != 1) {
7249
23.0k
                            break;
7250
23.0k
                        }
7251
                        // random sleep 0-100 ms to retry
7252
23.0k
                        std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7253
23.0k
                    }
7254
23.0k
                }
7255
23.0k
                if (ret != 0) {
7256
23.0k
                    LOG_WARNING("failed to delete recycle txn kv")
7257
23.0k
                            .tag("instance id", instance_id_)
7258
23.0k
                            .tag("key", hex(k));
7259
23.0k
                    return -1;
7260
23.0k
                }
7261
23.0k
                return 0;
7262
23.0k
            });
7263
23.0k
        }
7264
9
        bool finished = true;
7265
9
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7266
23.0k
        for (int r : rets) {
7267
23.0k
            if (r != 0) {
7268
9
                ret = -1;
7269
9
            }
7270
23.0k
        }
7271
7272
9
        ret = finished ? ret : -1;
7273
7274
        // Update metrics after all concurrent tasks completed
7275
9
        metrics_context.total_recycled_num = num_recycled.load();
7276
9
        metrics_context.report();
7277
7278
9
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7279
7280
9
        if (ret != 0) {
7281
3
            LOG_WARNING("recycle txn kv ret!=0")
7282
3
                    .tag("finished", finished)
7283
3
                    .tag("ret", ret)
7284
3
                    .tag("instance_id", instance_id_);
7285
3
            return ret;
7286
3
        }
7287
6
        return ret;
7288
9
    };
7289
7290
19
    if (config::enable_recycler_stats_metrics) {
7291
0
        scan_and_statistics_expired_txn_label();
7292
0
    }
7293
    // recycle_func and loop_done for scan and recycle
7294
19
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7295
19
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7296
19
}
7297
7298
struct CopyJobIdTuple {
7299
    std::string instance_id;
7300
    std::string stage_id;
7301
    long table_id;
7302
    std::string copy_id;
7303
    std::string stage_path;
7304
};
7305
struct BatchObjStoreAccessor {
7306
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7307
                          TxnKv* txn_kv)
7308
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7309
3
    ~BatchObjStoreAccessor() {
7310
3
        if (!paths_.empty()) {
7311
3
            consume();
7312
3
        }
7313
3
    }
7314
7315
    /**
7316
    * To implicitely do batch work and submit the batch delete task to s3
7317
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7318
    *
7319
    * @param copy_job The protubuf struct consists of the copy job files.
7320
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7321
    *            it would last until we finish the delete task, here we need pass one string value
7322
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7323
    */
7324
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7325
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7326
5
        auto& file_keys = copy_file_keys_[key];
7327
5
        file_keys.log_trace =
7328
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7329
5
                            instance_id, stage_id, table_id, copy_id, path);
7330
5
        std::string_view log_trace = file_keys.log_trace;
7331
2.03k
        for (const auto& file : copy_job.object_files()) {
7332
2.03k
            auto relative_path = file.relative_path();
7333
2.03k
            paths_.push_back(relative_path);
7334
2.03k
            file_keys.keys.push_back(copy_file_key(
7335
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7336
2.03k
            LOG_INFO(log_trace)
7337
2.03k
                    .tag("relative_path", relative_path)
7338
2.03k
                    .tag("batch_count", batch_count_);
7339
2.03k
        }
7340
5
        LOG_INFO(log_trace)
7341
5
                .tag("objects_num", copy_job.object_files().size())
7342
5
                .tag("batch_count", batch_count_);
7343
        // 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
7344
        // recommend using delete objects when objects num is less than 10)
7345
5
        if (paths_.size() < 1000) {
7346
3
            return;
7347
3
        }
7348
2
        consume();
7349
2
    }
7350
7351
private:
7352
5
    void consume() {
7353
5
        DORIS_CLOUD_DEFER {
7354
5
            paths_.clear();
7355
5
            copy_file_keys_.clear();
7356
5
            batch_count_++;
7357
7358
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7359
5
                        batch_count_);
7360
5
        };
7361
7362
5
        StopWatch sw;
7363
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7364
5
        if (0 != accessor_->delete_files(paths_)) {
7365
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7366
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7367
2
            return;
7368
2
        }
7369
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7370
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7371
        // delete fdb's keys
7372
3
        for (auto& file_keys : copy_file_keys_) {
7373
3
            auto& [log_trace, keys] = file_keys.second;
7374
3
            std::unique_ptr<Transaction> txn;
7375
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7376
0
                LOG(WARNING) << "failed to create txn";
7377
0
                continue;
7378
0
            }
7379
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7380
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7381
            // limited, should not cause the txn commit failed.
7382
1.02k
            for (const auto& key : keys) {
7383
1.02k
                txn->remove(key);
7384
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7385
1.02k
            }
7386
3
            txn->remove(file_keys.first);
7387
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7388
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7389
0
                continue;
7390
0
            }
7391
3
        }
7392
3
    }
7393
    std::shared_ptr<StorageVaultAccessor> accessor_;
7394
    // the path of the s3 files to be deleted
7395
    std::vector<std::string> paths_;
7396
    struct CopyFiles {
7397
        std::string log_trace;
7398
        std::vector<std::string> keys;
7399
    };
7400
    // pair<std::string, std::vector<std::string>>
7401
    // first: instance_id_ stage_id table_id query_id
7402
    // second: keys to be deleted
7403
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7404
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7405
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7406
    // which can together uniquely identifies different tasks for tracing log
7407
    uint64_t& batch_count_;
7408
    TxnKv* txn_kv_;
7409
};
7410
7411
13
int InstanceRecycler::recycle_copy_jobs() {
7412
13
    int64_t num_scanned = 0;
7413
13
    int64_t num_finished = 0;
7414
13
    int64_t num_expired = 0;
7415
13
    int64_t num_recycled = 0;
7416
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7417
13
    uint64_t batch_count = 0;
7418
13
    const std::string task_name = "recycle_copy_jobs";
7419
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7420
7421
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7422
7423
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7424
13
    register_recycle_task(task_name, start_time);
7425
7426
13
    DORIS_CLOUD_DEFER {
7427
13
        unregister_recycle_task(task_name);
7428
13
        int64_t cost =
7429
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7430
13
        metrics_context.finish_report();
7431
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7432
13
                .tag("instance_id", instance_id_)
7433
13
                .tag("num_scanned", num_scanned)
7434
13
                .tag("num_finished", num_finished)
7435
13
                .tag("num_expired", num_expired)
7436
13
                .tag("num_recycled", num_recycled);
7437
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7426
13
    DORIS_CLOUD_DEFER {
7427
13
        unregister_recycle_task(task_name);
7428
13
        int64_t cost =
7429
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7430
13
        metrics_context.finish_report();
7431
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7432
13
                .tag("instance_id", instance_id_)
7433
13
                .tag("num_scanned", num_scanned)
7434
13
                .tag("num_finished", num_finished)
7435
13
                .tag("num_expired", num_expired)
7436
13
                .tag("num_recycled", num_recycled);
7437
13
    };
7438
7439
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7440
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7441
13
    std::string key0;
7442
13
    std::string key1;
7443
13
    copy_job_key(key_info0, &key0);
7444
13
    copy_job_key(key_info1, &key1);
7445
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7446
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7447
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7448
16
                         this](std::string_view k, std::string_view v) -> int {
7449
16
        ++num_scanned;
7450
16
        CopyJobPB copy_job;
7451
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7452
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7453
0
            return -1;
7454
0
        }
7455
7456
        // decode copy job key
7457
16
        auto k1 = k;
7458
16
        k1.remove_prefix(1);
7459
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7460
16
        decode_key(&k1, &out);
7461
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7462
        // -> CopyJobPB
7463
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7464
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7465
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7466
7467
16
        bool check_storage = true;
7468
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7469
12
            ++num_finished;
7470
7471
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7472
7
                auto it = stage_accessor_map.find(stage_id);
7473
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7474
7
                std::string_view path;
7475
7
                if (it != stage_accessor_map.end()) {
7476
2
                    accessor = it->second;
7477
5
                } else {
7478
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7479
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7480
5
                                                      &inner_accessor);
7481
5
                    if (ret < 0) { // error
7482
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7483
0
                        return -1;
7484
5
                    } else if (ret == 0) {
7485
3
                        path = inner_accessor->uri();
7486
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7487
3
                                inner_accessor, batch_count, txn_kv_.get());
7488
3
                        stage_accessor_map.emplace(stage_id, accessor);
7489
3
                    } else { // stage not found, skip check storage
7490
2
                        check_storage = false;
7491
2
                    }
7492
5
                }
7493
7
                if (check_storage) {
7494
                    // TODO delete objects with key and etag is not supported
7495
5
                    accessor->add(std::move(copy_job), std::string(k),
7496
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7497
5
                    return 0;
7498
5
                }
7499
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7500
5
                int64_t current_time =
7501
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7502
5
                if (copy_job.finish_time_ms() > 0) {
7503
2
                    if (!config::force_immediate_recycle &&
7504
2
                        current_time < copy_job.finish_time_ms() +
7505
2
                                               config::copy_job_max_retention_second * 1000) {
7506
1
                        return 0;
7507
1
                    }
7508
3
                } else {
7509
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7510
3
                    if (!config::force_immediate_recycle &&
7511
3
                        current_time < copy_job.start_time_ms() +
7512
3
                                               config::copy_job_max_retention_second * 1000) {
7513
1
                        return 0;
7514
1
                    }
7515
3
                }
7516
5
            }
7517
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7518
4
            int64_t current_time =
7519
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7520
            // if copy job is timeout: delete all copy file kvs and copy job kv
7521
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7522
2
                return 0;
7523
2
            }
7524
2
            ++num_expired;
7525
2
        }
7526
7527
        // delete all copy files
7528
7
        std::vector<std::string> copy_file_keys;
7529
70
        for (auto& file : copy_job.object_files()) {
7530
70
            copy_file_keys.push_back(copy_file_key(
7531
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7532
70
        }
7533
7
        std::unique_ptr<Transaction> txn;
7534
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7535
0
            LOG(WARNING) << "failed to create txn";
7536
0
            return -1;
7537
0
        }
7538
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7539
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7540
        // limited, should not cause the txn commit failed.
7541
70
        for (const auto& key : copy_file_keys) {
7542
70
            txn->remove(key);
7543
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7544
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7545
70
                      << ", query_id=" << copy_id;
7546
70
        }
7547
7
        txn->remove(k);
7548
7
        TxnErrorCode err = txn->commit();
7549
7
        if (err != TxnErrorCode::TXN_OK) {
7550
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7551
0
            return -1;
7552
0
        }
7553
7554
7
        metrics_context.total_recycled_num = ++num_recycled;
7555
7
        metrics_context.report();
7556
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7557
7
        return 0;
7558
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
7448
16
                         this](std::string_view k, std::string_view v) -> int {
7449
16
        ++num_scanned;
7450
16
        CopyJobPB copy_job;
7451
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7452
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7453
0
            return -1;
7454
0
        }
7455
7456
        // decode copy job key
7457
16
        auto k1 = k;
7458
16
        k1.remove_prefix(1);
7459
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7460
16
        decode_key(&k1, &out);
7461
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7462
        // -> CopyJobPB
7463
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7464
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7465
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7466
7467
16
        bool check_storage = true;
7468
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7469
12
            ++num_finished;
7470
7471
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7472
7
                auto it = stage_accessor_map.find(stage_id);
7473
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7474
7
                std::string_view path;
7475
7
                if (it != stage_accessor_map.end()) {
7476
2
                    accessor = it->second;
7477
5
                } else {
7478
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7479
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7480
5
                                                      &inner_accessor);
7481
5
                    if (ret < 0) { // error
7482
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7483
0
                        return -1;
7484
5
                    } else if (ret == 0) {
7485
3
                        path = inner_accessor->uri();
7486
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7487
3
                                inner_accessor, batch_count, txn_kv_.get());
7488
3
                        stage_accessor_map.emplace(stage_id, accessor);
7489
3
                    } else { // stage not found, skip check storage
7490
2
                        check_storage = false;
7491
2
                    }
7492
5
                }
7493
7
                if (check_storage) {
7494
                    // TODO delete objects with key and etag is not supported
7495
5
                    accessor->add(std::move(copy_job), std::string(k),
7496
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7497
5
                    return 0;
7498
5
                }
7499
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7500
5
                int64_t current_time =
7501
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7502
5
                if (copy_job.finish_time_ms() > 0) {
7503
2
                    if (!config::force_immediate_recycle &&
7504
2
                        current_time < copy_job.finish_time_ms() +
7505
2
                                               config::copy_job_max_retention_second * 1000) {
7506
1
                        return 0;
7507
1
                    }
7508
3
                } else {
7509
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7510
3
                    if (!config::force_immediate_recycle &&
7511
3
                        current_time < copy_job.start_time_ms() +
7512
3
                                               config::copy_job_max_retention_second * 1000) {
7513
1
                        return 0;
7514
1
                    }
7515
3
                }
7516
5
            }
7517
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7518
4
            int64_t current_time =
7519
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7520
            // if copy job is timeout: delete all copy file kvs and copy job kv
7521
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7522
2
                return 0;
7523
2
            }
7524
2
            ++num_expired;
7525
2
        }
7526
7527
        // delete all copy files
7528
7
        std::vector<std::string> copy_file_keys;
7529
70
        for (auto& file : copy_job.object_files()) {
7530
70
            copy_file_keys.push_back(copy_file_key(
7531
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7532
70
        }
7533
7
        std::unique_ptr<Transaction> txn;
7534
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7535
0
            LOG(WARNING) << "failed to create txn";
7536
0
            return -1;
7537
0
        }
7538
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7539
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7540
        // limited, should not cause the txn commit failed.
7541
70
        for (const auto& key : copy_file_keys) {
7542
70
            txn->remove(key);
7543
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7544
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7545
70
                      << ", query_id=" << copy_id;
7546
70
        }
7547
7
        txn->remove(k);
7548
7
        TxnErrorCode err = txn->commit();
7549
7
        if (err != TxnErrorCode::TXN_OK) {
7550
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7551
0
            return -1;
7552
0
        }
7553
7554
7
        metrics_context.total_recycled_num = ++num_recycled;
7555
7
        metrics_context.report();
7556
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7557
7
        return 0;
7558
7
    };
7559
7560
13
    if (config::enable_recycler_stats_metrics) {
7561
0
        scan_and_statistics_copy_jobs();
7562
0
    }
7563
    // recycle_func and loop_done for scan and recycle
7564
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7565
13
}
7566
7567
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7568
                                             const StagePB::StageType& stage_type,
7569
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7570
5
#ifdef UNIT_TEST
7571
    // In unit test, external use the same accessor as the internal stage
7572
5
    auto it = accessor_map_.find(stage_id);
7573
5
    if (it != accessor_map_.end()) {
7574
3
        *accessor = it->second;
7575
3
    } else {
7576
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7577
2
        return 1;
7578
2
    }
7579
#else
7580
    // init s3 accessor and add to accessor map
7581
    auto stage_it =
7582
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7583
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7584
7585
    if (stage_it == instance_info_.stages().end()) {
7586
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7587
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7588
        return 1;
7589
    }
7590
7591
    const auto& object_store_info = stage_it->obj_info();
7592
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7593
7594
    S3Conf s3_conf;
7595
    if (stage_type == StagePB::EXTERNAL) {
7596
        if (stage_access_type == StagePB::AKSK) {
7597
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7598
            if (!conf) {
7599
                return -1;
7600
            }
7601
7602
            s3_conf = std::move(*conf);
7603
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7604
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7605
            if (!conf) {
7606
                return -1;
7607
            }
7608
7609
            s3_conf = std::move(*conf);
7610
            if (instance_info_.ram_user().has_encryption_info()) {
7611
                AkSkPair plain_ak_sk_pair;
7612
                int ret = decrypt_ak_sk_helper(
7613
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7614
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7615
                if (ret != 0) {
7616
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7617
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7618
                    return -1;
7619
                }
7620
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7621
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7622
            } else {
7623
                s3_conf.ak = instance_info_.ram_user().ak();
7624
                s3_conf.sk = instance_info_.ram_user().sk();
7625
            }
7626
        } else {
7627
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7628
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7629
            return -1;
7630
        }
7631
    } else if (stage_type == StagePB::INTERNAL) {
7632
        int idx = stoi(object_store_info.id());
7633
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7634
            LOG(WARNING) << "invalid idx: " << idx;
7635
            return -1;
7636
        }
7637
7638
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7639
        auto conf = S3Conf::from_obj_store_info(old_obj);
7640
        if (!conf) {
7641
            return -1;
7642
        }
7643
7644
        s3_conf = std::move(*conf);
7645
        s3_conf.prefix = object_store_info.prefix();
7646
    } else {
7647
        LOG(WARNING) << "unknown stage type " << stage_type;
7648
        return -1;
7649
    }
7650
7651
    std::shared_ptr<S3Accessor> s3_accessor;
7652
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7653
    if (ret != 0) {
7654
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7655
        return -1;
7656
    }
7657
7658
    *accessor = std::move(s3_accessor);
7659
#endif
7660
3
    return 0;
7661
5
}
7662
7663
11
int InstanceRecycler::recycle_stage() {
7664
11
    int64_t num_scanned = 0;
7665
11
    int64_t num_recycled = 0;
7666
11
    const std::string task_name = "recycle_stage";
7667
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7668
7669
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7670
7671
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7672
11
    register_recycle_task(task_name, start_time);
7673
7674
11
    DORIS_CLOUD_DEFER {
7675
11
        unregister_recycle_task(task_name);
7676
11
        int64_t cost =
7677
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7678
11
        metrics_context.finish_report();
7679
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7680
11
                .tag("instance_id", instance_id_)
7681
11
                .tag("num_scanned", num_scanned)
7682
11
                .tag("num_recycled", num_recycled);
7683
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7674
11
    DORIS_CLOUD_DEFER {
7675
11
        unregister_recycle_task(task_name);
7676
11
        int64_t cost =
7677
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7678
11
        metrics_context.finish_report();
7679
        LOG_WARNING("recycle stage, cost={}s", cost)
7680
11
                .tag("instance_id", instance_id_)
7681
11
                .tag("num_scanned", num_scanned)
7682
11
                .tag("num_recycled", num_recycled);
7683
11
    };
7684
7685
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7686
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7687
11
    std::string key0 = recycle_stage_key(key_info0);
7688
11
    std::string key1 = recycle_stage_key(key_info1);
7689
7690
11
    std::vector<std::string_view> stage_keys;
7691
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7692
11
                         this](std::string_view k, std::string_view v) -> int {
7693
1
        ++num_scanned;
7694
1
        RecycleStagePB recycle_stage;
7695
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7696
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7697
0
            return -1;
7698
0
        }
7699
7700
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7701
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7702
0
            LOG(WARNING) << "invalid idx: " << idx;
7703
0
            return -1;
7704
0
        }
7705
7706
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7707
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7708
1
                [&] {
7709
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7710
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7711
1
                    if (!s3_conf) {
7712
1
                        return -1;
7713
1
                    }
7714
7715
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7716
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7717
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7718
1
                    if (ret != 0) {
7719
1
                        return -1;
7720
1
                    }
7721
7722
1
                    accessor = std::move(s3_accessor);
7723
1
                    return 0;
7724
1
                }(),
7725
1
                "recycle_stage:get_accessor", &accessor);
7726
7727
1
        if (ret != 0) {
7728
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7729
0
            return ret;
7730
0
        }
7731
7732
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7733
1
                .tag("instance_id", instance_id_)
7734
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7735
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7736
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7737
1
                .tag("obj_info_id", idx)
7738
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7739
1
        ret = accessor->delete_all();
7740
1
        if (ret != 0) {
7741
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7742
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7743
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7744
0
                         << ", ret=" << ret;
7745
0
            return -1;
7746
0
        }
7747
1
        metrics_context.total_recycled_num = ++num_recycled;
7748
1
        metrics_context.report();
7749
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7750
1
        stage_keys.push_back(k);
7751
1
        return 0;
7752
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7692
1
                         this](std::string_view k, std::string_view v) -> int {
7693
1
        ++num_scanned;
7694
1
        RecycleStagePB recycle_stage;
7695
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7696
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7697
0
            return -1;
7698
0
        }
7699
7700
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7701
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7702
0
            LOG(WARNING) << "invalid idx: " << idx;
7703
0
            return -1;
7704
0
        }
7705
7706
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7707
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7708
1
                [&] {
7709
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7710
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7711
1
                    if (!s3_conf) {
7712
1
                        return -1;
7713
1
                    }
7714
7715
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7716
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7717
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7718
1
                    if (ret != 0) {
7719
1
                        return -1;
7720
1
                    }
7721
7722
1
                    accessor = std::move(s3_accessor);
7723
1
                    return 0;
7724
1
                }(),
7725
1
                "recycle_stage:get_accessor", &accessor);
7726
7727
1
        if (ret != 0) {
7728
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7729
0
            return ret;
7730
0
        }
7731
7732
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7733
1
                .tag("instance_id", instance_id_)
7734
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7735
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7736
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7737
1
                .tag("obj_info_id", idx)
7738
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7739
1
        ret = accessor->delete_all();
7740
1
        if (ret != 0) {
7741
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7742
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7743
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7744
0
                         << ", ret=" << ret;
7745
0
            return -1;
7746
0
        }
7747
1
        metrics_context.total_recycled_num = ++num_recycled;
7748
1
        metrics_context.report();
7749
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7750
1
        stage_keys.push_back(k);
7751
1
        return 0;
7752
1
    };
7753
7754
11
    auto loop_done = [&stage_keys, this]() -> int {
7755
1
        if (stage_keys.empty()) return 0;
7756
1
        DORIS_CLOUD_DEFER {
7757
1
            stage_keys.clear();
7758
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7756
1
        DORIS_CLOUD_DEFER {
7757
1
            stage_keys.clear();
7758
1
        };
7759
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7760
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7761
0
            return -1;
7762
0
        }
7763
1
        return 0;
7764
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7754
1
    auto loop_done = [&stage_keys, this]() -> int {
7755
1
        if (stage_keys.empty()) return 0;
7756
1
        DORIS_CLOUD_DEFER {
7757
1
            stage_keys.clear();
7758
1
        };
7759
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7760
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7761
0
            return -1;
7762
0
        }
7763
1
        return 0;
7764
1
    };
7765
11
    if (config::enable_recycler_stats_metrics) {
7766
0
        scan_and_statistics_stage();
7767
0
    }
7768
    // recycle_func and loop_done for scan and recycle
7769
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7770
11
}
7771
7772
10
int InstanceRecycler::recycle_expired_stage_objects() {
7773
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7774
7775
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7776
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7777
7778
10
    DORIS_CLOUD_DEFER {
7779
10
        int64_t cost =
7780
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7781
10
        metrics_context.finish_report();
7782
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7783
10
                .tag("instance_id", instance_id_);
7784
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7778
10
    DORIS_CLOUD_DEFER {
7779
10
        int64_t cost =
7780
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7781
10
        metrics_context.finish_report();
7782
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7783
10
                .tag("instance_id", instance_id_);
7784
10
    };
7785
7786
10
    int ret = 0;
7787
7788
10
    if (config::enable_recycler_stats_metrics) {
7789
0
        scan_and_statistics_expired_stage_objects();
7790
0
    }
7791
7792
10
    for (const auto& stage : instance_info_.stages()) {
7793
0
        std::stringstream ss;
7794
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7795
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7796
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7797
0
           << ", prefix=" << stage.obj_info().prefix();
7798
7799
0
        if (stopped()) {
7800
0
            break;
7801
0
        }
7802
0
        if (stage.type() == StagePB::EXTERNAL) {
7803
0
            continue;
7804
0
        }
7805
0
        int idx = stoi(stage.obj_info().id());
7806
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7807
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7808
0
            continue;
7809
0
        }
7810
7811
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7812
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7813
0
        if (!s3_conf) {
7814
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7815
0
            continue;
7816
0
        }
7817
7818
0
        s3_conf->prefix = stage.obj_info().prefix();
7819
0
        std::shared_ptr<S3Accessor> accessor;
7820
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7821
0
        if (ret1 != 0) {
7822
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7823
0
            ret = -1;
7824
0
            continue;
7825
0
        }
7826
7827
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7828
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7829
0
            ret = -1;
7830
0
            continue;
7831
0
        }
7832
7833
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7834
0
        int64_t expiration_time =
7835
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7836
0
                config::internal_stage_objects_expire_time_second;
7837
0
        if (config::force_immediate_recycle) {
7838
0
            expiration_time = INT64_MAX;
7839
0
        }
7840
0
        ret1 = accessor->delete_all(expiration_time);
7841
0
        if (ret1 != 0) {
7842
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7843
0
                         << ss.str();
7844
0
            ret = -1;
7845
0
            continue;
7846
0
        }
7847
0
        metrics_context.total_recycled_num++;
7848
0
        metrics_context.report();
7849
0
    }
7850
10
    return ret;
7851
10
}
7852
7853
264
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7854
264
    std::lock_guard lock(recycle_tasks_mutex);
7855
264
    running_recycle_tasks[task_name] = start_time;
7856
264
}
7857
7858
265
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7859
265
    std::lock_guard lock(recycle_tasks_mutex);
7860
265
    DCHECK(running_recycle_tasks[task_name] > 0);
7861
265
    running_recycle_tasks.erase(task_name);
7862
265
}
7863
7864
3
bool InstanceRecycler::check_recycle_tasks() {
7865
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7866
3
    {
7867
3
        std::lock_guard lock(recycle_tasks_mutex);
7868
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7869
3
    }
7870
7871
3
    bool found = false;
7872
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7873
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7874
2
        int64_t cost = now - start_time;
7875
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7876
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7877
2
                    .tag("instance_id", instance_id_)
7878
2
                    .tag("task", task_name);
7879
2
            found = true;
7880
2
        }
7881
2
    }
7882
7883
3
    return found;
7884
3
}
7885
7886
// Scan and statistics indexes that need to be recycled
7887
1
int InstanceRecycler::scan_and_statistics_indexes() {
7888
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7889
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7890
7891
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7892
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7893
1
    std::string index_key0;
7894
1
    std::string index_key1;
7895
1
    recycle_index_key(index_key_info0, &index_key0);
7896
1
    recycle_index_key(index_key_info1, &index_key1);
7897
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7898
7899
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7900
1
        RecycleIndexPB index_pb;
7901
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7902
0
            return 0;
7903
0
        }
7904
1
        int64_t current_time = ::time(nullptr);
7905
1
        if (current_time <
7906
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7907
0
            return 0;
7908
0
        }
7909
        // decode index_id
7910
1
        auto k1 = k;
7911
1
        k1.remove_prefix(1);
7912
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7913
1
        decode_key(&k1, &out);
7914
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7915
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7916
1
        std::unique_ptr<Transaction> txn;
7917
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7918
1
        if (err != TxnErrorCode::TXN_OK) {
7919
0
            return 0;
7920
0
        }
7921
1
        std::string val;
7922
1
        err = txn->get(k, &val);
7923
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7924
0
            return 0;
7925
0
        }
7926
1
        if (err != TxnErrorCode::TXN_OK) {
7927
0
            return 0;
7928
0
        }
7929
1
        index_pb.Clear();
7930
1
        if (!index_pb.ParseFromString(val)) {
7931
0
            return 0;
7932
0
        }
7933
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7934
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7935
0
                LOG_WARNING("table stream recycle index is missing binding")
7936
0
                        .tag("instance_id", instance_id_)
7937
0
                        .tag("stream_id", index_id);
7938
0
                return 0;
7939
0
            }
7940
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7941
2
                std::string end = prefix;
7942
2
                end.push_back('\xff');
7943
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7944
6
                                                              std::string_view value) {
7945
6
                    stream_metrics_context.total_need_recycle_num++;
7946
6
                    stream_metrics_context.total_need_recycle_data_size +=
7947
6
                            key.size() + value.size();
7948
6
                    return 0;
7949
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7944
6
                                                              std::string_view value) {
7945
6
                    stream_metrics_context.total_need_recycle_num++;
7946
6
                    stream_metrics_context.total_need_recycle_data_size +=
7947
6
                            key.size() + value.size();
7948
6
                    return 0;
7949
6
                };
7950
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7951
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7940
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7941
2
                std::string end = prefix;
7942
2
                end.push_back('\xff');
7943
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7944
2
                                                              std::string_view value) {
7945
2
                    stream_metrics_context.total_need_recycle_num++;
7946
2
                    stream_metrics_context.total_need_recycle_data_size +=
7947
2
                            key.size() + value.size();
7948
2
                    return 0;
7949
2
                };
7950
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7951
2
            };
7952
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7953
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7954
1
                    index_id);
7955
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7956
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7957
1
                    index_id);
7958
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7959
1
                scan_offset_prefix(versioned_prefix) != 0) {
7960
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7961
0
                        .tag("instance_id", instance_id_)
7962
0
                        .tag("stream_id", index_id);
7963
0
            }
7964
1
            return 0;
7965
1
        }
7966
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7967
0
            return 0;
7968
0
        }
7969
0
        metrics_context.total_need_recycle_num++;
7970
0
        return 0;
7971
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7899
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7900
1
        RecycleIndexPB index_pb;
7901
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7902
0
            return 0;
7903
0
        }
7904
1
        int64_t current_time = ::time(nullptr);
7905
1
        if (current_time <
7906
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7907
0
            return 0;
7908
0
        }
7909
        // decode index_id
7910
1
        auto k1 = k;
7911
1
        k1.remove_prefix(1);
7912
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7913
1
        decode_key(&k1, &out);
7914
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7915
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7916
1
        std::unique_ptr<Transaction> txn;
7917
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7918
1
        if (err != TxnErrorCode::TXN_OK) {
7919
0
            return 0;
7920
0
        }
7921
1
        std::string val;
7922
1
        err = txn->get(k, &val);
7923
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7924
0
            return 0;
7925
0
        }
7926
1
        if (err != TxnErrorCode::TXN_OK) {
7927
0
            return 0;
7928
0
        }
7929
1
        index_pb.Clear();
7930
1
        if (!index_pb.ParseFromString(val)) {
7931
0
            return 0;
7932
0
        }
7933
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7934
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7935
0
                LOG_WARNING("table stream recycle index is missing binding")
7936
0
                        .tag("instance_id", instance_id_)
7937
0
                        .tag("stream_id", index_id);
7938
0
                return 0;
7939
0
            }
7940
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7941
1
                std::string end = prefix;
7942
1
                end.push_back('\xff');
7943
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7944
1
                                                              std::string_view value) {
7945
1
                    stream_metrics_context.total_need_recycle_num++;
7946
1
                    stream_metrics_context.total_need_recycle_data_size +=
7947
1
                            key.size() + value.size();
7948
1
                    return 0;
7949
1
                };
7950
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7951
1
            };
7952
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7953
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7954
1
                    index_id);
7955
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7956
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7957
1
                    index_id);
7958
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7959
1
                scan_offset_prefix(versioned_prefix) != 0) {
7960
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7961
0
                        .tag("instance_id", instance_id_)
7962
0
                        .tag("stream_id", index_id);
7963
0
            }
7964
1
            return 0;
7965
1
        }
7966
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7967
0
            return 0;
7968
0
        }
7969
0
        metrics_context.total_need_recycle_num++;
7970
0
        return 0;
7971
0
    };
7972
7973
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7974
1
    metrics_context.report(true);
7975
1
    stream_metrics_context.report(true);
7976
1
    segment_metrics_context_.report(true);
7977
1
    tablet_metrics_context_.report(true);
7978
1
    return ret;
7979
1
}
7980
7981
// Scan and statistics partitions that need to be recycled
7982
0
int InstanceRecycler::scan_and_statistics_partitions() {
7983
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7984
7985
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7986
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7987
0
    std::string part_key0;
7988
0
    std::string part_key1;
7989
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7990
7991
0
    recycle_partition_key(part_key_info0, &part_key0);
7992
0
    recycle_partition_key(part_key_info1, &part_key1);
7993
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7994
0
        RecyclePartitionPB part_pb;
7995
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7996
0
            return 0;
7997
0
        }
7998
0
        int64_t current_time = ::time(nullptr);
7999
0
        if (current_time <
8000
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
8001
0
            return 0;
8002
0
        }
8003
        // decode partition_id
8004
0
        auto k1 = k;
8005
0
        k1.remove_prefix(1);
8006
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8007
0
        decode_key(&k1, &out);
8008
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
8009
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
8010
        // Change state to RECYCLING
8011
0
        std::unique_ptr<Transaction> txn;
8012
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8013
0
        if (err != TxnErrorCode::TXN_OK) {
8014
0
            return 0;
8015
0
        }
8016
0
        std::string val;
8017
0
        err = txn->get(k, &val);
8018
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8019
0
            return 0;
8020
0
        }
8021
0
        if (err != TxnErrorCode::TXN_OK) {
8022
0
            return 0;
8023
0
        }
8024
0
        part_pb.Clear();
8025
0
        if (!part_pb.ParseFromString(val)) {
8026
0
            return 0;
8027
0
        }
8028
        // Partitions with PREPARED state MUST have no data
8029
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
8030
0
        int ret = 0;
8031
0
        for (int64_t index_id : part_pb.index_id()) {
8032
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
8033
0
                                            partition_id, is_empty_tablet) != 0) {
8034
0
                ret = 0;
8035
0
            }
8036
0
        }
8037
0
        metrics_context.total_need_recycle_num++;
8038
0
        return ret;
8039
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_
8040
8041
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
8042
0
    metrics_context.report(true);
8043
0
    segment_metrics_context_.report(true);
8044
0
    tablet_metrics_context_.report(true);
8045
0
    return ret;
8046
0
}
8047
8048
// Scan and statistics rowsets that need to be recycled
8049
0
int InstanceRecycler::scan_and_statistics_rowsets() {
8050
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
8051
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
8052
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
8053
0
    std::string recyc_rs_key0;
8054
0
    std::string recyc_rs_key1;
8055
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
8056
0
                recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
8057
0
       int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8058
8059
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
8060
0
        RecycleRowsetPB rowset;
8061
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8062
0
            return 0;
8063
0
        }
8064
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
8065
0
        int64_t current_time = ::time(nullptr);
8066
0
        if (current_time <
8067
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
8068
0
            return 0;
8069
0
        }
8070
8071
0
        if (!rowset.has_type()) {
8072
0
            if (!rowset.has_resource_id()) [[unlikely]] {
8073
0
                return 0;
8074
0
            }
8075
0
            if (rowset.resource_id().empty()) [[unlikely]] {
8076
0
                return 0;
8077
0
            }
8078
0
            metrics_context.total_need_recycle_num++;
8079
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8080
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
8081
0
            segment_metrics_context_.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8082
0
            return 0;
8083
0
        }
8084
8085
0
        if (config::enable_mark_delete_rowset_before_recycle &&
8086
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
8087
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
8088
0
            return 0;
8089
0
        }
8090
8091
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
8092
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
8093
0
                return 0;
8094
0
            }
8095
0
        }
8096
0
        metrics_context.total_need_recycle_num++;
8097
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
8098
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
8099
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8100
0
        return 0;
8101
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_
8102
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8103
0
    metrics_context.report(true);
8104
0
    segment_metrics_context_.report(true);
8105
0
    return ret;
8106
0
}
8107
8108
// Scan and statistics tmp_rowsets that need to be recycled
8109
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8110
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8111
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8112
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8113
0
    std::string tmp_rs_key0;
8114
0
    std::string tmp_rs_key1;
8115
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8116
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8117
8118
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8119
8120
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8121
0
        doris::RowsetMetaCloudPB rowset;
8122
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8123
0
            return 0;
8124
0
        }
8125
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8126
0
        int64_t current_time = ::time(nullptr);
8127
0
        if (current_time < expiration) {
8128
0
            return 0;
8129
0
        }
8130
8131
0
        DCHECK_GT(rowset.txn_id(), 0)
8132
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8133
8134
0
        if(!rowset.has_is_recycled() || !rowset.is_recycled()) {
8135
0
            return 0;
8136
0
        }
8137
8138
0
        if (!rowset.has_resource_id()) {
8139
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8140
0
                return 0;
8141
0
            }
8142
0
            return 0;
8143
0
        }
8144
8145
0
        metrics_context.total_need_recycle_num++;
8146
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8147
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8148
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8149
0
        return 0;
8150
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_
8151
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8152
0
    metrics_context.report(true);
8153
0
    segment_metrics_context_.report(true);
8154
0
    return ret;
8155
0
}
8156
8157
// Scan and statistics abort_timeout_txn that need to be recycled
8158
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8159
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8160
8161
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8162
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8163
0
    std::string begin_txn_running_key;
8164
0
    std::string end_txn_running_key;
8165
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8166
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8167
8168
0
    int64_t current_time =
8169
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8170
8171
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8172
0
                                               std::string_view k, std::string_view v) -> int {
8173
0
        std::unique_ptr<Transaction> txn;
8174
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8175
0
        if (err != TxnErrorCode::TXN_OK) {
8176
0
            return 0;
8177
0
        }
8178
0
        std::string_view k1 = k;
8179
0
        k1.remove_prefix(1);
8180
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8181
0
        if (decode_key(&k1, &out) != 0) {
8182
0
            return 0;
8183
0
        }
8184
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8185
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8186
        // Update txn_info
8187
0
        std::string txn_inf_key, txn_inf_val;
8188
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8189
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8190
0
        if (err != TxnErrorCode::TXN_OK) {
8191
0
            return 0;
8192
0
        }
8193
0
        TxnInfoPB txn_info;
8194
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8195
0
            return 0;
8196
0
        }
8197
8198
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8199
0
            TxnRunningPB txn_running_pb;
8200
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8201
0
                return 0;
8202
0
            }
8203
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8204
0
                return 0;
8205
0
            }
8206
0
            metrics_context.total_need_recycle_num++;
8207
0
        }
8208
0
        return 0;
8209
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_
8210
8211
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key, std::move(handle_abort_timeout_txn_kv));
8212
0
    metrics_context.report(true);
8213
0
    return ret;
8214
0
}
8215
8216
// Scan and statistics expired_txn_label that need to be recycled
8217
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8218
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8219
8220
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8221
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8222
0
    std::string begin_recycle_txn_key;
8223
0
    std::string end_recycle_txn_key;
8224
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8225
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8226
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8227
0
    int64_t current_time_ms =
8228
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8229
8230
    // for calculate the total num or bytes of recyled objects
8231
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8232
0
        RecycleTxnPB recycle_txn_pb;
8233
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8234
0
            return 0;
8235
0
        }
8236
0
        if ((config::force_immediate_recycle) ||
8237
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8238
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8239
0
             current_time_ms)) {
8240
0
            metrics_context.total_need_recycle_num++;
8241
0
        }
8242
0
        return 0;
8243
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_
8244
8245
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key, std::move(handle_expired_txn_label_kv));
8246
0
    metrics_context.report(true);
8247
0
    return ret;
8248
0
}
8249
8250
// Scan and statistics copy_jobs that need to be recycled
8251
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8252
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8253
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8254
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8255
0
    std::string key0;
8256
0
    std::string key1;
8257
0
    copy_job_key(key_info0, &key0);
8258
0
    copy_job_key(key_info1, &key1);
8259
8260
    // for calculate the total num or bytes of recyled objects
8261
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8262
0
        CopyJobPB copy_job;
8263
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8264
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8265
0
            return 0;
8266
0
        }
8267
8268
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8269
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8270
0
                int64_t current_time =
8271
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8272
0
                if (copy_job.finish_time_ms() > 0) {
8273
0
                    if (!config::force_immediate_recycle &&
8274
0
                        current_time < copy_job.finish_time_ms() +
8275
0
                                               config::copy_job_max_retention_second * 1000) {
8276
0
                        return 0;
8277
0
                    }
8278
0
                } else {
8279
0
                    if (!config::force_immediate_recycle &&
8280
0
                        current_time < copy_job.start_time_ms() +
8281
0
                                               config::copy_job_max_retention_second * 1000) {
8282
0
                        return 0;
8283
0
                    }
8284
0
                }
8285
0
            }
8286
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8287
0
            int64_t current_time =
8288
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8289
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8290
0
                return 0;
8291
0
            }
8292
0
        }
8293
0
        metrics_context.total_need_recycle_num++;
8294
0
        return 0;
8295
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_
8296
8297
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8298
0
    metrics_context.report(true);
8299
0
    return ret;
8300
0
}
8301
8302
// Scan and statistics stage that need to be recycled
8303
0
int InstanceRecycler::scan_and_statistics_stage() {
8304
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8305
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8306
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8307
0
    std::string key0 = recycle_stage_key(key_info0);
8308
0
    std::string key1 = recycle_stage_key(key_info1);
8309
8310
    // for calculate the total num or bytes of recyled objects
8311
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8312
0
                                                        std::string_view v) -> int {
8313
0
        RecycleStagePB recycle_stage;
8314
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8315
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8316
0
            return 0;
8317
0
        }
8318
8319
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8320
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8321
0
            LOG(WARNING) << "invalid idx: " << idx;
8322
0
            return 0;
8323
0
        }
8324
8325
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8326
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8327
0
                [&] {
8328
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8329
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8330
0
                    if (!s3_conf) {
8331
0
                        return 0;
8332
0
                    }
8333
8334
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8335
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8336
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8337
0
                    if (ret != 0) {
8338
0
                        return 0;
8339
0
                    }
8340
8341
0
                    accessor = std::move(s3_accessor);
8342
0
                    return 0;
8343
0
                }(),
8344
0
                "recycle_stage:get_accessor", &accessor);
8345
8346
0
        if (ret != 0) {
8347
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8348
0
            return 0;
8349
0
        }
8350
8351
0
        metrics_context.total_need_recycle_num++;
8352
0
        return 0;
8353
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_
8354
8355
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8356
0
    metrics_context.report(true);
8357
0
    return ret;
8358
0
}
8359
8360
// Scan and statistics expired_stage_objects that need to be recycled
8361
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8362
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8363
8364
    // for calculate the total num or bytes of recyled objects
8365
0
    auto scan_and_statistics = [&metrics_context, this]() {
8366
0
        for (const auto& stage : instance_info_.stages()) {
8367
0
            if (stopped()) {
8368
0
                break;
8369
0
            }
8370
0
            if (stage.type() == StagePB::EXTERNAL) {
8371
0
                continue;
8372
0
            }
8373
0
            int idx = stoi(stage.obj_info().id());
8374
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8375
0
                continue;
8376
0
            }
8377
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8378
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8379
0
            if (!s3_conf) {
8380
0
                continue;
8381
0
            }
8382
0
            s3_conf->prefix = stage.obj_info().prefix();
8383
0
            std::shared_ptr<S3Accessor> accessor;
8384
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8385
0
            if (ret1 != 0) {
8386
0
                continue;
8387
0
            }
8388
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8389
0
                continue;
8390
0
            }
8391
0
            metrics_context.total_need_recycle_num++;
8392
0
        }
8393
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8394
8395
0
    scan_and_statistics();
8396
0
    metrics_context.report(true);
8397
0
    return 0;
8398
0
}
8399
8400
// Scan and statistics versions that need to be recycled
8401
0
int InstanceRecycler::scan_and_statistics_versions() {
8402
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8403
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8404
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8405
8406
0
    int64_t last_scanned_table_id = 0;
8407
0
    bool is_recycled = false; // Is last scanned kv recycled
8408
    // for calculate the total num or bytes of recyled objects
8409
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8410
0
                                       std::string_view k, std::string_view) {
8411
0
        auto k1 = k;
8412
0
        k1.remove_prefix(1);
8413
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8414
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8415
0
        decode_key(&k1, &out);
8416
0
        DCHECK_EQ(out.size(), 6) << k;
8417
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8418
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8419
0
            metrics_context.total_need_recycle_num +=
8420
0
                    is_recycled; // Version kv of this table has been recycled
8421
0
            return 0;
8422
0
        }
8423
0
        last_scanned_table_id = table_id;
8424
0
        is_recycled = false;
8425
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8426
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8427
0
        std::unique_ptr<Transaction> txn;
8428
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8429
0
        if (err != TxnErrorCode::TXN_OK) {
8430
0
            return 0;
8431
0
        }
8432
0
        std::unique_ptr<RangeGetIterator> iter;
8433
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8434
0
        if (err != TxnErrorCode::TXN_OK) {
8435
0
            return 0;
8436
0
        }
8437
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8438
0
            return 0;
8439
0
        }
8440
0
        metrics_context.total_need_recycle_num++;
8441
0
        is_recycled = true;
8442
0
        return 0;
8443
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_
8444
8445
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8446
0
    metrics_context.report(true);
8447
0
    return ret;
8448
0
}
8449
8450
// Scan and statistics restore jobs that need to be recycled
8451
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8452
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8453
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8454
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8455
0
    std::string restore_job_key0;
8456
0
    std::string restore_job_key1;
8457
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8458
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8459
8460
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8461
8462
    // for calculate the total num or bytes of recyled objects
8463
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8464
0
        RestoreJobCloudPB restore_job_pb;
8465
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8466
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8467
0
            return 0;
8468
0
        }
8469
0
        int64_t expiration =
8470
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8471
0
        int64_t current_time = ::time(nullptr);
8472
0
        if (current_time < expiration) { // not expired
8473
0
            return 0;
8474
0
        }
8475
0
        metrics_context.total_need_recycle_num++;
8476
0
        if(restore_job_pb.need_recycle_data()) {
8477
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8478
0
        }
8479
0
        return 0;
8480
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_
8481
8482
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8483
0
    metrics_context.report(true);
8484
0
    return ret;
8485
0
}
8486
8487
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8488
3
    if (!should_recycle_versioned_keys()) {
8489
0
        return;
8490
0
    }
8491
8492
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8493
8494
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8495
3
    if (recycle_checker.init() != 0) {
8496
0
        return;
8497
0
    }
8498
8499
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8500
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8501
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8502
8503
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8504
8
    for (; iter->valid(); iter->next()) {
8505
5
        OperationLogPB operation_log;
8506
5
        if (!iter->parse_value(&operation_log)) {
8507
0
            continue;
8508
0
        }
8509
8510
5
        std::string_view key = iter->key();
8511
5
        Versionstamp log_versionstamp;
8512
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8513
0
            continue;
8514
0
        }
8515
8516
5
        OperationLogReferenceInfo ref_info;
8517
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8518
5
                                         &ref_info)) {
8519
4
            metrics_context.total_need_recycle_num++;
8520
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8521
4
        }
8522
5
    }
8523
8524
3
    metrics_context.report(true);
8525
3
}
8526
8527
int InstanceRecycler::classify_rowset_task_by_ref_count(
8528
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8529
60
    constexpr int MAX_RETRY = 10;
8530
60
    const auto& rowset_meta = task.rowset_meta;
8531
60
    int64_t tablet_id = rowset_meta.tablet_id();
8532
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8533
60
    std::string_view reference_instance_id = instance_id_;
8534
60
    if (rowset_meta.has_reference_instance_id()) {
8535
5
        reference_instance_id = rowset_meta.reference_instance_id();
8536
5
    }
8537
8538
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8539
61
        std::unique_ptr<Transaction> txn;
8540
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8541
61
        if (err != TxnErrorCode::TXN_OK) {
8542
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8543
0
                    .tag("instance_id", instance_id_)
8544
0
                    .tag("tablet_id", tablet_id)
8545
0
                    .tag("rowset_id", rowset_id)
8546
0
                    .tag("err", err);
8547
0
            return -1;
8548
0
        }
8549
8550
61
        std::string rowset_ref_count_key =
8551
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8552
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8553
8554
61
        int64_t ref_count = 0;
8555
61
        {
8556
61
            std::string value;
8557
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8558
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8559
0
                ref_count = 1;
8560
61
            } else if (err != TxnErrorCode::TXN_OK) {
8561
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8562
0
                        .tag("instance_id", instance_id_)
8563
0
                        .tag("tablet_id", tablet_id)
8564
0
                        .tag("rowset_id", rowset_id)
8565
0
                        .tag("err", err);
8566
0
                return -1;
8567
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8568
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8569
0
                        .tag("instance_id", instance_id_)
8570
0
                        .tag("tablet_id", tablet_id)
8571
0
                        .tag("rowset_id", rowset_id)
8572
0
                        .tag("value", hex(value));
8573
0
                return -1;
8574
0
            }
8575
61
        }
8576
8577
61
        if (ref_count > 1) {
8578
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8579
12
            txn->atomic_add(rowset_ref_count_key, -1);
8580
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8581
12
                    .tag("instance_id", instance_id_)
8582
12
                    .tag("tablet_id", tablet_id)
8583
12
                    .tag("rowset_id", rowset_id)
8584
12
                    .tag("ref_count", ref_count - 1)
8585
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8586
8587
12
            if (!task.recycle_rowset_key.empty()) {
8588
0
                txn->remove(task.recycle_rowset_key);
8589
0
                LOG_INFO("remove recycle rowset key in classification phase")
8590
0
                        .tag("key", hex(task.recycle_rowset_key));
8591
0
            }
8592
12
            if (!task.non_versioned_rowset_key.empty()) {
8593
12
                txn->remove(task.non_versioned_rowset_key);
8594
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8595
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8596
12
            }
8597
8598
12
            err = txn->commit();
8599
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8600
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8601
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8602
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8603
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8604
1
                continue;
8605
11
            } else if (err != TxnErrorCode::TXN_OK) {
8606
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8607
0
                        .tag("instance_id", instance_id_)
8608
0
                        .tag("tablet_id", tablet_id)
8609
0
                        .tag("rowset_id", rowset_id)
8610
0
                        .tag("err", err);
8611
0
                return -1;
8612
0
            }
8613
11
            return 1; // handled, not added to batch delete
8614
49
        } else {
8615
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8616
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8617
49
            LOG_INFO("add rowset to batch delete plan")
8618
49
                    .tag("instance_id", instance_id_)
8619
49
                    .tag("tablet_id", tablet_id)
8620
49
                    .tag("rowset_id", rowset_id)
8621
49
                    .tag("resource_id", rowset_meta.resource_id())
8622
49
                    .tag("ref_count", ref_count);
8623
8624
49
            batch_delete_tasks.push_back(std::move(task));
8625
49
            return 0; // added to batch delete
8626
49
        }
8627
61
    }
8628
8629
0
    LOG_WARNING("failed to classify rowset task after retry")
8630
0
            .tag("instance_id", instance_id_)
8631
0
            .tag("tablet_id", tablet_id)
8632
0
            .tag("rowset_id", rowset_id)
8633
0
            .tag("retry", MAX_RETRY);
8634
0
    return -1;
8635
60
}
8636
8637
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8638
10
    int ret = 0;
8639
49
    for (const auto& task : tasks) {
8640
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8641
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8642
8643
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8644
        // so we don't need to call it again here.
8645
8646
        // Remove all metadata keys in one transaction
8647
49
        std::unique_ptr<Transaction> txn;
8648
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8649
49
        if (err != TxnErrorCode::TXN_OK) {
8650
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8651
0
                    .tag("instance_id", instance_id_)
8652
0
                    .tag("tablet_id", tablet_id)
8653
0
                    .tag("rowset_id", rowset_id)
8654
0
                    .tag("err", err);
8655
0
            ret = -1;
8656
0
            continue;
8657
0
        }
8658
8659
49
        std::string_view reference_instance_id = instance_id_;
8660
49
        if (task.rowset_meta.has_reference_instance_id()) {
8661
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8662
0
        }
8663
8664
49
        txn->remove(task.rowset_ref_count_key);
8665
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8666
49
                .tag("instance_id", instance_id_)
8667
49
                .tag("tablet_id", tablet_id)
8668
49
                .tag("rowset_id", rowset_id)
8669
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8670
8671
49
        std::string dbm_start_key =
8672
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8673
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8674
49
                {reference_instance_id, tablet_id, rowset_id,
8675
49
                 std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
8676
49
        txn->remove(dbm_start_key, dbm_end_key);
8677
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8678
49
                .tag("instance_id", instance_id_)
8679
49
                .tag("tablet_id", tablet_id)
8680
49
                .tag("rowset_id", rowset_id)
8681
49
                .tag("begin", hex(dbm_start_key))
8682
49
                .tag("end", hex(dbm_end_key));
8683
8684
49
        std::string versioned_dbm_start_key =
8685
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8686
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8687
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8688
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8689
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8690
49
                .tag("instance_id", instance_id_)
8691
49
                .tag("tablet_id", tablet_id)
8692
49
                .tag("rowset_id", rowset_id)
8693
49
                .tag("begin", hex(versioned_dbm_start_key))
8694
49
                .tag("end", hex(versioned_dbm_end_key));
8695
8696
        // Remove versioned meta rowset key
8697
49
        if (!task.versioned_rowset_key.empty()) {
8698
49
            versioned::document_remove<RowsetMetaCloudPB>(
8699
49
                txn.get(), task.versioned_rowset_key, task.versionstamp);
8700
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8701
49
                    .tag("instance_id", instance_id_)
8702
49
                    .tag("tablet_id", tablet_id)
8703
49
                    .tag("rowset_id", rowset_id)
8704
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8705
49
        }
8706
8707
49
        if (!task.non_versioned_rowset_key.empty()) {
8708
49
            txn->remove(task.non_versioned_rowset_key);
8709
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8710
49
                    .tag("instance_id", instance_id_)
8711
49
                    .tag("tablet_id", tablet_id)
8712
49
                    .tag("rowset_id", rowset_id)
8713
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8714
49
        }
8715
8716
        // Remove recycle_rowset_key last to ensure retry safety:
8717
        // if cleanup fails, this key remains and triggers next round retry.
8718
49
        if (!task.recycle_rowset_key.empty()) {
8719
0
            txn->remove(task.recycle_rowset_key);
8720
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8721
0
                    .tag("instance_id", instance_id_)
8722
0
                    .tag("tablet_id", tablet_id)
8723
0
                    .tag("rowset_id", rowset_id)
8724
0
                    .tag("key", hex(task.recycle_rowset_key));
8725
0
        }
8726
8727
49
        err = txn->commit();
8728
49
        if (err != TxnErrorCode::TXN_OK) {
8729
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8730
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8731
0
                    .tag("instance_id", instance_id_)
8732
0
                    .tag("tablet_id", tablet_id)
8733
0
                    .tag("rowset_id", rowset_id)
8734
0
                    .tag("err", err);
8735
0
            ret = -1;
8736
0
            continue;
8737
0
        }
8738
8739
49
        LOG_INFO("cleanup rowset metadata success")
8740
49
                .tag("instance_id", instance_id_)
8741
49
                .tag("tablet_id", tablet_id)
8742
49
                .tag("rowset_id", rowset_id);
8743
49
    }
8744
10
    return ret;
8745
10
}
8746
8747
} // namespace doris::cloud