Coverage Report

Created: 2026-09-11 16:25

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
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
869k
    const auto& locations = rowset.packed_slice_locations();
106
869k
    auto it = locations.find(path);
107
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
869k
           !it->second.packed_file_path().empty();
109
869k
}
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
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
869k
    const auto& locations = rowset.packed_slice_locations();
106
869k
    auto it = locations.find(path);
107
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
869k
           !it->second.packed_file_path().empty();
109
869k
}
110
111
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
112
                                      const std::string& path,
113
869k
                                      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
869k
}
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
869k
                                      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
869k
}
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
427
                   std::unique_ptr<RangeGetIterator>& it) {
150
427
    std::unique_ptr<Transaction> txn;
151
427
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
427
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
427
    switch (txn->get(begin, end, &it, true)) {
156
427
    case TxnErrorCode::TXN_OK:
157
427
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
427
    };
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
388
                   std::unique_ptr<RangeGetIterator>& it) {
150
388
    std::unique_ptr<Transaction> txn;
151
388
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
388
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
388
    switch (txn->get(begin, end, &it, true)) {
156
388
    case TxnErrorCode::TXN_OK:
157
388
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
388
    };
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
102k
                                       std::string_view end) {
208
102k
    std::unique_ptr<Transaction> txn;
209
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
102k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
102k
    txn->remove(begin, end);
214
102k
    switch (txn->commit()) {
215
102k
    case TxnErrorCode::TXN_OK:
216
102k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
102k
    }
222
102k
}
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
102k
                                       std::string_view end) {
208
102k
    std::unique_ptr<Transaction> txn;
209
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
102k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
102k
    txn->remove(begin, end);
214
102k
    switch (txn->commit()) {
215
102k
    case TxnErrorCode::TXN_OK:
216
102k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
102k
    }
222
102k
}
223
224
// Remove versioned delete bitmap keys grouped by rowset.
225
// Each inner vector represents all DBM shard keys for one rowset that MUST be deleted
226
// atomically in the same txn. Transaction splitting only occurs between rowsets, never
227
// within a rowset's shard keys.
228
//
229
// This ensures that a DBM blob with multiple shards is either fully deleted or not
230
// deleted at all, preventing partial deletion that would leave the blob unrecoverable.
231
//
232
// return 0 for success otherwise error
233
static int delete_versioned_delete_bitmap_by_rowset(
234
7
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
7
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
6
    size_t idx = 0;
239
13
    while (idx < rowset_dbm_key_groups.size()) {
240
7
        std::unique_ptr<Transaction> txn;
241
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
7
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
7
        bool has_keys = false;
247
1.57k
        while (idx < rowset_dbm_key_groups.size()) {
248
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
249
1.57k
            const auto keys_bytes =
250
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
1.61k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
recycler_test.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
Line
Count
Source
251
1.61k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
1.60k
            for (const auto& key : keys) {
258
1.60k
                txn->remove(key);
259
1.60k
            }
260
261
1.56k
            has_keys = true;
262
1.56k
            ++idx;
263
1.56k
        }
264
265
7
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
7
        err = txn->commit();
267
7
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
7
    }
272
6
    return 0;
273
6
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
recycler_test.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
Line
Count
Source
234
7
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
7
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
6
    size_t idx = 0;
239
13
    while (idx < rowset_dbm_key_groups.size()) {
240
7
        std::unique_ptr<Transaction> txn;
241
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
7
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
7
        bool has_keys = false;
247
1.57k
        while (idx < rowset_dbm_key_groups.size()) {
248
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
249
1.57k
            const auto keys_bytes =
250
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
1.57k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
1.60k
            for (const auto& key : keys) {
258
1.60k
                txn->remove(key);
259
1.60k
            }
260
261
1.56k
            has_keys = true;
262
1.56k
            ++idx;
263
1.56k
        }
264
265
7
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
7
        err = txn->commit();
267
7
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
7
    }
272
6
    return 0;
273
6
}
274
275
void scan_restore_job_rowset(
276
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
277
        std::string& msg,
278
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
279
280
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
281
                                      int64_t num_scanned, int64_t num_recycled,
282
62
                                      int64_t start_time) {
283
62
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
62
    return;
295
62
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
5
                                      int64_t start_time) {
283
5
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
5
    return;
295
5
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
57
                                      int64_t start_time) {
283
57
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
57
    return;
295
57
}
296
297
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
298
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
299
300
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
301
6
                                                               "s3_producer_pool");
302
6
    s3_producer_pool->start();
303
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
304
6
                                                                  "recycle_tablet_pool");
305
6
    recycle_tablet_pool->start();
306
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
307
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
308
6
    group_recycle_function_pool->start();
309
6
    _thread_pool_group =
310
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
311
6
                                    std::move(group_recycle_function_pool));
312
313
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
314
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
315
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
316
6
}
317
318
6
Recycler::~Recycler() {
319
6
    if (!stopped()) {
320
0
        stop();
321
0
    }
322
6
}
323
324
5
void Recycler::instance_scanner_callback() {
325
    // sleep 60 seconds before scheduling for the launch procedure to complete:
326
    // some bad hdfs connection may cause some log to stdout stderr
327
    // which may pollute .out file and affect the script to check success
328
5
    std::this_thread::sleep_for(
329
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
330
876
    while (!stopped()) {
331
871
        if (config::enable_recycler) {
332
4
            std::vector<InstanceInfoPB> instances;
333
4
            get_all_instances(txn_kv_.get(), instances);
334
            // TODO(plat1ko): delete job recycle kv of non-existent instances
335
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
4
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
4
                return ss.str();
339
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
335
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
4
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
4
                return ss.str();
339
4
            }();
340
4
            if (!instances.empty()) {
341
                // enqueue instances
342
3
                std::lock_guard lock(mtx_);
343
30
                for (auto& instance : instances) {
344
30
                    if (filter_out_instance(instance.instance_id())) continue;
345
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
346
                    // skip instance already in pending queue
347
30
                    if (success) {
348
30
                        pending_instance_queue_.push_back(std::move(instance));
349
30
                    }
350
30
                }
351
3
                pending_instance_cond_.notify_all();
352
3
            }
353
867
        } else {
354
867
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
355
867
        }
356
871
        {
357
871
            std::unique_lock lock(mtx_);
358
871
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
359
1.74k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
359
1.74k
                               [&]() { return stopped(); });
360
871
        }
361
871
    }
362
5
}
363
364
9
void Recycler::recycle_callback() {
365
40
    while (!stopped()) {
366
39
        InstanceInfoPB instance;
367
39
        {
368
39
            std::unique_lock lock(mtx_);
369
39
            pending_instance_cond_.wait(
370
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
370
52
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
371
39
            if (stopped()) {
372
8
                return;
373
8
            }
374
31
            instance = std::move(pending_instance_queue_.front());
375
31
            pending_instance_queue_.pop_front();
376
31
            pending_instance_set_.erase(instance.instance_id());
377
31
        }
378
0
        auto& instance_id = instance.instance_id();
379
31
        {
380
31
            std::lock_guard lock(mtx_);
381
            // skip instance in recycling
382
31
            if (recycling_instance_map_.count(instance_id)) continue;
383
31
        }
384
31
        if (!config::enable_recycler) {
385
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
386
1
                         << " since enable_recycler is false";
387
1
            continue;
388
1
        }
389
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
390
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
391
392
30
        if (int r = instance_recycler->init(); r != 0) {
393
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
394
0
                         << " ret=" << r;
395
0
            continue;
396
0
        }
397
30
        std::string recycle_job_key;
398
30
        job_recycle_key({instance_id}, &recycle_job_key);
399
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
400
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
401
30
        if (ret != 0) { // Prepare failed
402
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
403
20
                         << " ret=" << ret;
404
20
            continue;
405
20
        } else {
406
10
            std::lock_guard lock(mtx_);
407
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
408
10
        }
409
10
        if (stopped()) return;
410
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
411
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
412
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
413
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
414
10
        ret = instance_recycler->do_recycle();
415
        // If instance recycler has been aborted, don't finish this job
416
417
10
        if (!instance_recycler->stopped()) {
418
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
419
10
                                        ret == 0, ctime_ms);
420
10
        }
421
10
        if (instance_recycler->stopped() || ret != 0) {
422
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
423
0
        }
424
10
        {
425
10
            std::lock_guard lock(mtx_);
426
10
            recycling_instance_map_.erase(instance_id);
427
10
        }
428
429
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
430
10
        auto elpased_ms = now - ctime_ms;
431
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
432
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
433
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
434
10
                                             now + config::recycle_interval_seconds * 1000);
435
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
436
10
        LOG(INFO) << "recycle instance done, "
437
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
438
10
                  << " now: " << now;
439
440
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
441
442
10
        LOG_WARNING("finish recycle instance")
443
10
                .tag("instance_id", instance_id)
444
10
                .tag("cost_ms", elpased_ms);
445
10
    }
446
9
}
447
448
4
void Recycler::lease_recycle_jobs() {
449
54
    while (!stopped()) {
450
50
        std::vector<std::string> instances;
451
50
        instances.reserve(recycling_instance_map_.size());
452
50
        {
453
50
            std::lock_guard lock(mtx_);
454
50
            for (auto& [id, _] : recycling_instance_map_) {
455
30
                instances.push_back(id);
456
30
            }
457
50
        }
458
50
        for (auto& i : instances) {
459
30
            std::string recycle_job_key;
460
30
            job_recycle_key({i}, &recycle_job_key);
461
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
462
30
            if (ret == 1) {
463
0
                std::lock_guard lock(mtx_);
464
0
                if (auto it = recycling_instance_map_.find(i);
465
0
                    it != recycling_instance_map_.end()) {
466
0
                    it->second->stop();
467
0
                }
468
0
            }
469
30
        }
470
50
        {
471
50
            std::unique_lock lock(mtx_);
472
50
            notifier_.wait_for(lock,
473
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
474
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
474
100
                               [&]() { return stopped(); });
475
50
        }
476
50
    }
477
4
}
478
479
4
void Recycler::check_recycle_tasks() {
480
7
    while (!stopped()) {
481
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
482
3
        {
483
3
            std::lock_guard lock(mtx_);
484
3
            recycling_instance_map = recycling_instance_map_;
485
3
        }
486
3
        for (auto& entry : recycling_instance_map) {
487
0
            entry.second->check_recycle_tasks();
488
0
        }
489
490
3
        std::unique_lock lock(mtx_);
491
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
492
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
492
6
                           [&]() { return stopped(); });
493
3
    }
494
4
}
495
496
4
int Recycler::start(brpc::Server* server) {
497
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
498
4
    S3Environment::getInstance();
499
500
4
    if (config::enable_checker) {
501
0
        checker_ = std::make_unique<Checker>(txn_kv_);
502
0
        int ret = checker_->start();
503
0
        std::string msg;
504
0
        if (ret != 0) {
505
0
            msg = "failed to start checker";
506
0
            LOG(ERROR) << msg;
507
0
            std::cerr << msg << std::endl;
508
0
            return ret;
509
0
        }
510
0
        msg = "checker started";
511
0
        LOG(INFO) << msg;
512
0
        std::cout << msg << std::endl;
513
0
    }
514
515
4
    if (server) {
516
        // Add service
517
1
        auto recycler_service =
518
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
519
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
520
1
    }
521
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
523
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
524
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
524
8
        workers_.emplace_back([this] { recycle_callback(); });
525
8
    }
526
527
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
528
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
529
530
4
    if (config::enable_snapshot_data_migrator) {
531
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
532
0
        int ret = snapshot_data_migrator_->start();
533
0
        if (ret != 0) {
534
0
            LOG(ERROR) << "failed to start snapshot data migrator";
535
0
            return ret;
536
0
        }
537
0
        LOG(INFO) << "snapshot data migrator started";
538
0
    }
539
540
4
    if (config::enable_snapshot_chain_compactor) {
541
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
542
0
        int ret = snapshot_chain_compactor_->start();
543
0
        if (ret != 0) {
544
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
545
0
            return ret;
546
0
        }
547
0
        LOG(INFO) << "snapshot chain compactor started";
548
0
    }
549
550
4
    return 0;
551
4
}
552
553
4
void Recycler::stop() {
554
4
    stopped_ = true;
555
4
    notifier_.notify_all();
556
4
    pending_instance_cond_.notify_all();
557
4
    {
558
4
        std::lock_guard lock(mtx_);
559
4
        for (auto& [_, recycler] : recycling_instance_map_) {
560
0
            recycler->stop();
561
0
        }
562
4
    }
563
20
    for (auto& w : workers_) {
564
20
        if (w.joinable()) w.join();
565
20
    }
566
4
    if (checker_) {
567
0
        checker_->stop();
568
0
    }
569
4
    if (snapshot_data_migrator_) {
570
0
        snapshot_data_migrator_->stop();
571
0
    }
572
4
    if (snapshot_chain_compactor_) {
573
0
        snapshot_chain_compactor_->stop();
574
0
    }
575
4
}
576
577
class InstanceRecycler::InvertedIndexIdCache {
578
public:
579
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
580
190
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
581
582
    // Return 0 if success, 1 if schema kv not found, negative for error
583
    // For the same index_id, schema_version, res, since `get` is not completely atomic
584
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
585
    // resulting in repeated addition and inaccuracy.
586
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
587
    // repeated addition does not affect correctness.
588
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
589
28.4k
        {
590
28.4k
            std::lock_guard lock(mtx_);
591
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
592
4.70k
                return 0;
593
4.70k
            }
594
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
595
23.7k
                it != inverted_index_id_map_.end()) {
596
18.1k
                res = it->second;
597
18.1k
                return 0;
598
18.1k
            }
599
23.7k
        }
600
        // Get schema from kv
601
        // TODO(plat1ko): Single flight
602
5.54k
        std::unique_ptr<Transaction> txn;
603
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
604
5.54k
        if (err != TxnErrorCode::TXN_OK) {
605
0
            LOG(WARNING) << "failed to create txn, err=" << err;
606
0
            return -1;
607
0
        }
608
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
609
5.54k
        ValueBuf val_buf;
610
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
611
5.54k
        if (err != TxnErrorCode::TXN_OK) {
612
500
            LOG(WARNING) << "failed to get schema, err=" << err;
613
500
            return static_cast<int>(err);
614
500
        }
615
5.04k
        doris::TabletSchemaCloudPB schema;
616
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
617
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
618
0
            return -1;
619
0
        }
620
5.04k
        if (schema.index_size() > 0) {
621
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
622
4.01k
            if (schema.has_inverted_index_storage_format()) {
623
4.00k
                index_format = schema.inverted_index_storage_format();
624
4.00k
            }
625
4.01k
            res.first = index_format;
626
4.01k
            res.second.reserve(schema.index_size());
627
10.0k
            for (auto& i : schema.index()) {
628
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
629
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
630
10.0k
                }
631
10.0k
            }
632
4.01k
        }
633
5.04k
        insert(index_id, schema_version, res);
634
5.04k
        return 0;
635
5.04k
    }
636
637
    // Empty `ids` means this schema has no inverted index
638
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
639
5.04k
        if (index_info.second.empty()) {
640
1.03k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
641
1.03k
            std::lock_guard lock(mtx_);
642
1.03k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
643
4.01k
        } else {
644
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
645
4.01k
            std::lock_guard lock(mtx_);
646
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
647
4.01k
        }
648
5.04k
    }
649
650
private:
651
    std::string instance_id_;
652
    std::shared_ptr<TxnKv> txn_kv_;
653
654
    std::mutex mtx_;
655
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
656
    struct HashOfKey {
657
57.2k
        size_t operator()(const Key& key) const {
658
57.2k
            size_t seed = 0;
659
57.2k
            seed = std::hash<int64_t> {}(key.first);
660
57.2k
            seed = std::hash<int32_t> {}(key.second);
661
57.2k
            return seed;
662
57.2k
        }
663
    };
664
    // <index_id, schema_version> -> inverted_index_ids
665
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
666
    // Store <index_id, schema_version> of schema which doesn't have inverted index
667
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
668
};
669
670
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
671
                                   RecyclerThreadPoolGroup thread_pool_group,
672
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
673
190
        : txn_kv_(std::move(txn_kv)),
674
190
          instance_id_(instance.instance_id()),
675
190
          instance_info_(instance),
676
190
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
677
190
          _thread_pool_group(std::move(thread_pool_group)),
678
190
          txn_lazy_committer_(std::move(txn_lazy_committer)),
679
190
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
680
190
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
681
190
    delete_bitmap_lock_white_list_->init();
682
190
    resource_mgr_->init();
683
684
190
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
685
686
    // Since the recycler's resource manager could not be notified when instance info changes,
687
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
688
190
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
689
190
};
690
691
190
InstanceRecycler::~InstanceRecycler() = default;
692
693
158
int InstanceRecycler::init_obj_store_accessors() {
694
158
    for (const auto& obj_info : instance_info_.obj_info()) {
695
110
#ifdef UNIT_TEST
696
110
        auto accessor = std::make_shared<MockAccessor>();
697
#else
698
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
699
        if (!s3_conf) {
700
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
701
            return -1;
702
        }
703
704
        std::shared_ptr<S3Accessor> accessor;
705
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
706
        if (ret != 0) {
707
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
708
                         << " resource_id=" << obj_info.id();
709
            return ret;
710
        }
711
#endif
712
110
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
713
110
    }
714
715
158
    return 0;
716
158
}
717
718
158
int InstanceRecycler::init_storage_vault_accessors() {
719
158
    if (instance_info_.resource_ids().empty()) {
720
151
        return 0;
721
151
    }
722
723
7
    FullRangeGetOptions opts(txn_kv_);
724
7
    opts.prefetch = true;
725
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
726
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
727
728
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
729
18
        auto [k, v] = *kv;
730
18
        StorageVaultPB vault;
731
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
732
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
733
0
            return -1;
734
0
        }
735
18
        std::string recycler_storage_vault_white_list = accumulate(
736
18
                config::recycler_storage_vault_white_list.begin(),
737
18
                config::recycler_storage_vault_white_list.end(), std::string(),
738
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
738
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
739
18
        LOG_INFO("config::recycler_storage_vault_white_list")
740
18
                .tag("", recycler_storage_vault_white_list);
741
18
        if (!config::recycler_storage_vault_white_list.empty()) {
742
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
743
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
744
8
                it == config::recycler_storage_vault_white_list.end()) {
745
2
                LOG_WARNING(
746
2
                        "failed to init accessor for vault because this vault is not in "
747
2
                        "config::recycler_storage_vault_white_list. ")
748
2
                        .tag(" vault name:", vault.name())
749
2
                        .tag(" config::recycler_storage_vault_white_list:",
750
2
                             recycler_storage_vault_white_list);
751
2
                continue;
752
2
            }
753
8
        }
754
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
755
16
                                 &accessor_map_, &vault);
756
16
        if (vault.has_hdfs_info()) {
757
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
758
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
759
9
            int ret = accessor->init();
760
9
            if (ret != 0) {
761
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
762
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
763
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
764
4
                continue;
765
4
            }
766
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
767
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
768
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
769
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
770
#else
771
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
772
                       << "but HDFS storage vaults were detected";
773
#endif
774
7
        } else if (vault.has_obj_info()) {
775
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
776
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
777
7
            if (!s3_conf) {
778
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
779
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
780
1
                continue;
781
1
            }
782
783
6
            std::shared_ptr<S3Accessor> accessor;
784
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
785
6
            if (ret != 0) {
786
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
787
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
788
0
                             << " ret=" << ret
789
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
790
0
                continue;
791
0
            }
792
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
793
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
794
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
795
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
796
6
        }
797
16
    }
798
799
7
    if (!it->is_valid()) {
800
0
        LOG_WARNING("failed to get storage vault kv");
801
0
        return -1;
802
0
    }
803
804
7
    if (accessor_map_.empty()) {
805
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
806
1
        return -2;
807
1
    }
808
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
809
6
             instance_id_);
810
811
6
    return 0;
812
7
}
813
814
159
int InstanceRecycler::init() {
815
159
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
816
159
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
817
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
818
1
        return 0;
819
1
    }
820
821
158
    int ret = init_obj_store_accessors();
822
158
    if (ret != 0) {
823
0
        return ret;
824
0
    }
825
826
158
    return init_storage_vault_accessors();
827
158
}
828
829
template <typename... Func>
830
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
120
    return [funcs...]() {
832
120
        return [](std::initializer_list<int> ret_vals) {
833
120
            int i = 0;
834
140
            for (int ret : ret_vals) {
835
140
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
140
            }
839
120
            return i;
840
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
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
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
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
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
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
843
844
11
int InstanceRecycler::do_recycle() {
845
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
846
11
    tablet_metrics_context_.reset();
847
11
    segment_metrics_context_.reset();
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
852
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
853
1
        int res = recycle_cluster_snapshots();
854
1
        if (res != 0) {
855
0
            return -1;
856
0
        }
857
1
        return recycle_deleted_instance();
858
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
859
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
860
10
                                        fmt::format("instance id {}", instance_id_),
861
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
861
120
                                        [](int r) { return r != 0; });
862
10
        sync_executor
863
10
                .add(task_wrapper(
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
865
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
865
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
866
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
867
                                   // becase they may both recycle the same set of tablets
868
                        // recycle dropped table or idexes(mv, rollup)
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
870
                        // recycle dropped partitions
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
872
10
                .add(task_wrapper(
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
874
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
874
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
877
10
                .add(task_wrapper(
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
880
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
880
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
881
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
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
882
10
                .add(task_wrapper(
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
884
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
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
885
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
885
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
886
10
        bool finished = true;
887
10
        std::vector<int> rets = sync_executor.when_all(&finished);
888
120
        for (int ret : rets) {
889
120
            if (ret != 0) {
890
0
                return ret;
891
0
            }
892
120
        }
893
10
        return finished ? 0 : -1;
894
10
    } else {
895
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
896
0
                     << " instance_id=" << instance_id_;
897
0
        return -1;
898
0
    }
899
11
}
900
901
/**
902
* 1. delete all remote data
903
* 2. delete all kv
904
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
905
*/
906
13
int InstanceRecycler::recycle_deleted_instance() {
907
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
908
909
13
    int ret = 0;
910
13
    auto start_time = steady_clock::now();
911
13
    const auto recycle_state = instance_info_.recycle_state();
912
913
13
    if (config::retain_deleted_instance_tombstone &&
914
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
915
4
        return 0;
916
4
    }
917
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
934
935
9
    switch (recycle_state) {
936
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
937
6
        ret = recycle_deleted_instance_data();
938
6
        break;
939
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
940
3
        ret = recycle_deleted_instance_metadata();
941
3
        break;
942
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
943
0
        ret = remove_instance_key();
944
0
        break;
945
0
    default:
946
0
        LOG_WARNING("invalid instance recycle state")
947
0
                .tag("instance_id", instance_id_)
948
0
                .tag("recycle_state", instance_info_.recycle_state());
949
0
        ret = -1;
950
0
        break;
951
9
    }
952
953
9
    return ret;
954
9
}
955
956
6
int InstanceRecycler::recycle_deleted_instance_data() {
957
6
    int ret = 0;
958
959
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
971
972
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
973
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
974
0
        return -1;
975
0
    }
976
977
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
978
6
    if (recycle_versioned_rowsets() != 0) {
979
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
980
0
        return -1;
981
0
    }
982
983
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
984
6
    if (recycle_operation_logs() != 0) {
985
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
986
0
        return -1;
987
0
    }
988
989
    // Step 4: Check if there are still cluster snapshots
990
6
    bool has_snapshots = false;
991
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
992
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
993
0
        return -1;
994
6
    } else if (has_snapshots) {
995
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
996
1
        return 0;
997
1
    }
998
999
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
1000
5
                            instance_info().snapshot_switch_status() !=
1001
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1002
5
    if (snapshot_enabled) {
1003
1
        bool has_unrecycled_rowsets = false;
1004
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1005
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1006
0
            return -1;
1007
1
        } else if (has_unrecycled_rowsets) {
1008
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1009
0
                    .tag("instance_id", instance_id_);
1010
0
            return ret;
1011
0
        }
1012
4
    } else { // delete all remote data if snapshot is disabled
1013
4
        for (auto& [_, accessor] : accessor_map_) {
1014
4
            if (stopped()) {
1015
0
                return ret;
1016
0
            }
1017
1018
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1019
4
            int del_ret = accessor->delete_all();
1020
4
            if (del_ret == 0) {
1021
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1022
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1023
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1024
                // so the recycling has been successful.
1025
0
                ret = -1;
1026
0
            }
1027
4
        }
1028
1029
4
        if (ret != 0) {
1030
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1031
0
            return ret;
1032
0
        }
1033
4
    }
1034
1035
5
    if (update_instance_recycle_state(
1036
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1037
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1038
0
        return -1;
1039
0
    }
1040
1041
5
    return 0;
1042
5
}
1043
1044
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1045
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1046
7
    if (instance_info_.has_successor_instance_id() &&
1047
7
        !instance_info_.successor_instance_id().empty()) {
1048
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1049
4
        std::unique_ptr<Transaction> txn;
1050
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1051
4
        if (err != TxnErrorCode::TXN_OK) {
1052
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1053
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1054
0
                         << " err=" << err;
1055
0
            return -1;
1056
0
        }
1057
1058
4
        InstanceInfoPB successor_instance;
1059
4
        std::string value;
1060
4
        err = txn->get(key, &value);
1061
4
        if (err == TxnErrorCode::TXN_OK) {
1062
3
            InstanceInfoPB successor_instance;
1063
3
            if (!successor_instance.ParseFromString(value)) {
1064
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1065
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1066
0
                return -1;
1067
0
            }
1068
3
            if (!successor_instance.has_recycle_state() ||
1069
3
                successor_instance.recycle_state() !=
1070
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1071
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1072
2
                          << " instance_id=" << instance_id_
1073
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1074
2
                          << " successor_status=" << successor_instance.status()
1075
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1076
2
                return 0;
1077
2
            }
1078
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1079
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1080
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1081
0
                         << " err=" << err;
1082
0
            return -1;
1083
0
        }
1084
4
    }
1085
1086
    // delete all kv
1087
5
    std::unique_ptr<Transaction> txn;
1088
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1089
5
    if (err != TxnErrorCode::TXN_OK) {
1090
0
        LOG(WARNING) << "failed to create txn";
1091
0
        return -1;
1092
0
    }
1093
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1094
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1095
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1096
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1097
5
    txn->remove(start_txn_key, end_txn_key);
1098
5
    std::string start_version_key = version_key_prefix(instance_id_);
1099
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_version_key, end_version_key);
1101
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1102
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_meta_key, end_meta_key);
1104
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1105
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1106
5
    txn->remove(start_recycle_key, end_recycle_key);
1107
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1108
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1109
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1110
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1111
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1112
5
    txn->remove(start_copy_key, end_copy_key);
1113
    // should not remove job key range, because we need to reserve job recycle kv
1114
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1115
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1116
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1117
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1118
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1119
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1120
5
    std::string start_vault_key = storage_vault_key(key_info0);
1121
5
    std::string end_vault_key = storage_vault_key(key_info1);
1122
5
    txn->remove(start_vault_key, end_vault_key);
1123
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1124
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1125
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1126
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1127
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1129
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1130
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1132
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1133
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1135
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1136
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1138
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1139
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1140
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1141
1142
    // Updating the recycle state also commits this transaction, making the metadata deletions
1143
    // and state transition atomic.
1144
5
    if (update_instance_recycle_state(
1145
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1146
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1147
0
        return -1;
1148
0
    }
1149
1150
5
    return 0;
1151
5
}
1152
1153
0
int InstanceRecycler::remove_instance_key() {
1154
0
    std::unique_ptr<Transaction> txn;
1155
0
    std::string key = instance_key(instance_info_.instance_id());
1156
0
    std::string value;
1157
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1158
0
    if (err != TxnErrorCode::TXN_OK) {
1159
0
        LOG(WARNING) << "failed to create txn";
1160
0
        return -1;
1161
0
    }
1162
1163
0
    err = txn->get(key, &value);
1164
0
    if (err != TxnErrorCode::TXN_OK) {
1165
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1166
0
                     << ", err=" << err;
1167
0
        return -1;
1168
0
    }
1169
1170
0
    InstanceInfoPB instance;
1171
0
    if (!instance.ParseFromString(value)) {
1172
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1173
0
        return -1;
1174
0
    }
1175
1176
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1177
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1178
0
                     << instance_id_ << ", status=" << instance.status();
1179
0
        return -1;
1180
0
    }
1181
1182
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1183
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1184
0
                     << instance_id_
1185
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1186
0
                     << ", expected_state="
1187
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1188
0
        return -1;
1189
0
    }
1190
1191
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1192
0
    txn->remove(key);
1193
0
    err = txn->commit();
1194
0
    if (err != TxnErrorCode::TXN_OK) {
1195
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1196
0
                     << " err=" << err;
1197
0
        return -1;
1198
0
    }
1199
0
    return 0;
1200
0
}
1201
1202
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1203
7
                                                    InstanceRecycleState target_state) {
1204
7
    std::unique_ptr<Transaction> txn;
1205
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1206
7
    if (err != TxnErrorCode::TXN_OK) {
1207
0
        LOG(WARNING) << "failed to create txn";
1208
0
        return -1;
1209
0
    }
1210
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1211
7
}
1212
1213
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1214
                                                    InstanceRecycleState target_state,
1215
12
                                                    Transaction* txn) {
1216
12
    const bool valid_transition =
1217
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1218
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1219
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1220
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1221
1222
12
    if (!valid_transition) {
1223
1
        LOG_WARNING("invalid instance recycled state transition")
1224
1
                .tag("instance_id", instance_id_)
1225
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1226
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1227
1
        return -1;
1228
1
    }
1229
1230
11
    std::string key = instance_key({instance_id_});
1231
11
    std::string value;
1232
11
    TxnErrorCode err = txn->get(key, &value);
1233
11
    if (err != TxnErrorCode::TXN_OK) {
1234
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1235
0
                .tag("instance_id", instance_id_)
1236
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1237
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1238
0
                .tag("err", err);
1239
0
        return -1;
1240
0
    }
1241
1242
11
    InstanceInfoPB instance;
1243
11
    if (!instance.ParseFromString(value)) {
1244
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1245
0
                .tag("instance_id", instance_id_)
1246
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1247
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1248
0
        return -1;
1249
0
    }
1250
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1251
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1252
0
                .tag("instance_id", instance_id_)
1253
0
                .tag("status", instance.status())
1254
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1255
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1256
0
        return -1;
1257
0
    }
1258
11
    if (instance.recycle_state() != current_state) {
1259
1
        LOG_WARNING("instance recycled state changed before update")
1260
1
                .tag("instance_id", instance_id_)
1261
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1262
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1263
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1264
1
        return -1;
1265
1
    }
1266
1267
10
    instance.set_recycle_state(target_state);
1268
10
    instance.set_recycle_state_update_time_ms(
1269
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1270
10
    if (!instance.SerializeToString(&value)) {
1271
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1272
0
                .tag("instance_id", instance_id_)
1273
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1274
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1275
0
        return -1;
1276
0
    }
1277
1278
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1279
10
    txn->put(key, value);
1280
10
    err = txn->commit();
1281
10
    if (err != TxnErrorCode::TXN_OK) {
1282
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1283
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1284
0
        return -1;
1285
0
    }
1286
1287
10
    instance_info_.Swap(&instance);
1288
10
    LOG_INFO("updated instance recycled state")
1289
10
            .tag("instance_id", instance_id_)
1290
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1291
10
    return 0;
1292
10
}
1293
1294
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1295
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1296
9
    if (exists == nullptr) {
1297
0
        return -1;
1298
0
    }
1299
9
    *exists = false;
1300
1301
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1302
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1303
9
    std::string scan_begin = begin;
1304
1305
9
    while (true) {
1306
9
        std::unique_ptr<RangeGetIterator> it_range;
1307
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1308
9
        if (get_ret < 0) {
1309
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1310
0
                    .tag("instance_id", instance_id_)
1311
0
                    .tag("tablet_id", tablet_id)
1312
0
                    .tag("ret", get_ret);
1313
0
            return -1;
1314
0
        }
1315
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1316
6
            return 0;
1317
6
        }
1318
1319
3
        std::string last_key;
1320
3
        while (it_range->has_next()) {
1321
3
            auto [k, v] = it_range->next();
1322
3
            last_key.assign(k.data(), k.size());
1323
3
            doris::RowsetMetaCloudPB rowset_meta;
1324
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1325
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1326
0
                        .tag("instance_id", instance_id_)
1327
0
                        .tag("tablet_id", tablet_id)
1328
0
                        .tag("key", hex(k));
1329
0
                continue;
1330
0
            }
1331
3
            if (stats) {
1332
3
                ++stats->rowset_scan_count;
1333
3
            }
1334
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1335
3
                *exists = true;
1336
3
                return 0;
1337
3
            }
1338
3
        }
1339
1340
0
        if (!it_range->more()) {
1341
0
            return 0;
1342
0
        }
1343
1344
        // Continue scanning from the next key to keep each transaction short.
1345
0
        scan_begin = std::move(last_key);
1346
0
        scan_begin.push_back('\x00');
1347
0
    }
1348
9
}
1349
1350
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1351
                                                          const std::string& rowset_id,
1352
                                                          int64_t txn_id, bool* recycle_exists,
1353
11
                                                          bool* tmp_exists) {
1354
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1355
0
        return -1;
1356
0
    }
1357
11
    *recycle_exists = false;
1358
11
    *tmp_exists = false;
1359
1360
11
    if (txn_id <= 0) {
1361
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1362
0
                .tag("instance_id", instance_id_)
1363
0
                .tag("tablet_id", tablet_id)
1364
0
                .tag("rowset_id", rowset_id)
1365
0
                .tag("txn_id", txn_id);
1366
0
        return -1;
1367
0
    }
1368
1369
11
    std::unique_ptr<Transaction> txn;
1370
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
11
    if (err != TxnErrorCode::TXN_OK) {
1372
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1373
0
                .tag("instance_id", instance_id_)
1374
0
                .tag("tablet_id", tablet_id)
1375
0
                .tag("rowset_id", rowset_id)
1376
0
                .tag("txn_id", txn_id)
1377
0
                .tag("err", err);
1378
0
        return -1;
1379
0
    }
1380
1381
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1382
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1383
11
    if (ret == TxnErrorCode::TXN_OK) {
1384
1
        *recycle_exists = true;
1385
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1386
0
        LOG_WARNING("failed to check recycle rowset existence")
1387
0
                .tag("instance_id", instance_id_)
1388
0
                .tag("tablet_id", tablet_id)
1389
0
                .tag("rowset_id", rowset_id)
1390
0
                .tag("key", hex(recycle_key))
1391
0
                .tag("err", ret);
1392
0
        return -1;
1393
0
    }
1394
1395
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1396
11
    ret = key_exists(txn.get(), tmp_key, true);
1397
11
    if (ret == TxnErrorCode::TXN_OK) {
1398
1
        *tmp_exists = true;
1399
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1400
0
        LOG_WARNING("failed to check tmp rowset existence")
1401
0
                .tag("instance_id", instance_id_)
1402
0
                .tag("tablet_id", tablet_id)
1403
0
                .tag("txn_id", txn_id)
1404
0
                .tag("key", hex(tmp_key))
1405
0
                .tag("err", ret);
1406
0
        return -1;
1407
0
    }
1408
1409
11
    return 0;
1410
11
}
1411
1412
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1413
9
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1414
9
    if (!hint.empty()) {
1415
9
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1416
9
            return {hint, it->second};
1417
9
        }
1418
9
    }
1419
1420
0
    return {"", nullptr};
1421
9
}
1422
1423
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1424
                                               const std::string& packed_file_path,
1425
3
                                               PackedFileRecycleStats* stats) {
1426
3
    bool local_changed = false;
1427
3
    int64_t left_num = 0;
1428
3
    int64_t left_bytes = 0;
1429
3
    bool all_small_files_confirmed = true;
1430
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1431
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
14
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
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
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
14
    };
1448
1449
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1450
14
        auto* small_file = packed_info->mutable_slices(i);
1451
14
        if (small_file->deleted()) {
1452
3
            log_small_file_status(*small_file, small_file->corrected());
1453
3
            continue;
1454
3
        }
1455
1456
11
        if (small_file->corrected()) {
1457
0
            left_num++;
1458
0
            left_bytes += small_file->size();
1459
0
            log_small_file_status(*small_file, true);
1460
0
            continue;
1461
0
        }
1462
1463
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1464
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1465
0
                    .tag("instance_id", instance_id_)
1466
0
                    .tag("small_file_path", small_file->path())
1467
0
                    .tag("index", i);
1468
0
            return -1;
1469
0
        }
1470
1471
11
        int64_t tablet_id = small_file->tablet_id();
1472
11
        const std::string& rowset_id = small_file->rowset_id();
1473
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1474
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1475
0
                    .tag("instance_id", instance_id_)
1476
0
                    .tag("small_file_path", small_file->path())
1477
0
                    .tag("index", i)
1478
0
                    .tag("tablet_id", tablet_id)
1479
0
                    .tag("rowset_id", rowset_id)
1480
0
                    .tag("has_txn_id", small_file->has_txn_id())
1481
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1482
0
            return -1;
1483
0
        }
1484
11
        int64_t txn_id = small_file->txn_id();
1485
11
        bool recycle_exists = false;
1486
11
        bool tmp_exists = false;
1487
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1488
11
                                                &tmp_exists) != 0) {
1489
0
            return -1;
1490
0
        }
1491
1492
11
        bool small_file_confirmed = false;
1493
11
        if (tmp_exists) {
1494
1
            left_num++;
1495
1
            left_bytes += small_file->size();
1496
1
            small_file_confirmed = true;
1497
10
        } else if (recycle_exists) {
1498
1
            left_num++;
1499
1
            left_bytes += small_file->size();
1500
            // keep small_file_confirmed=false so the packed file remains uncorrected
1501
9
        } else {
1502
9
            bool rowset_exists = false;
1503
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1504
0
                return -1;
1505
0
            }
1506
1507
9
            if (!rowset_exists) {
1508
6
                if (!small_file->deleted()) {
1509
6
                    small_file->set_deleted(true);
1510
6
                    local_changed = true;
1511
6
                }
1512
6
                if (!small_file->corrected()) {
1513
6
                    small_file->set_corrected(true);
1514
6
                    local_changed = true;
1515
6
                }
1516
6
                small_file_confirmed = true;
1517
6
            } else {
1518
3
                left_num++;
1519
3
                left_bytes += small_file->size();
1520
3
                small_file_confirmed = true;
1521
3
            }
1522
9
        }
1523
1524
11
        if (!small_file_confirmed) {
1525
1
            all_small_files_confirmed = false;
1526
1
        }
1527
1528
11
        if (small_file->corrected() != small_file_confirmed) {
1529
4
            small_file->set_corrected(small_file_confirmed);
1530
4
            local_changed = true;
1531
4
        }
1532
1533
11
        log_small_file_status(*small_file, small_file_confirmed);
1534
11
    }
1535
1536
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1537
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1538
3
        local_changed = true;
1539
3
    }
1540
3
    if (packed_info->ref_cnt() != left_num) {
1541
3
        auto old_ref_cnt = packed_info->ref_cnt();
1542
3
        packed_info->set_ref_cnt(left_num);
1543
3
        LOG_INFO("corrected packed file ref count")
1544
3
                .tag("instance_id", instance_id_)
1545
3
                .tag("resource_id", packed_info->resource_id())
1546
3
                .tag("packed_file_path", packed_file_path)
1547
3
                .tag("old_ref_cnt", old_ref_cnt)
1548
3
                .tag("new_ref_cnt", left_num);
1549
3
        local_changed = true;
1550
3
    }
1551
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1552
2
        packed_info->set_corrected(all_small_files_confirmed);
1553
2
        local_changed = true;
1554
2
    }
1555
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1556
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1557
1
        local_changed = true;
1558
1
    }
1559
1560
3
    if (changed != nullptr) {
1561
3
        *changed = local_changed;
1562
3
    }
1563
3
    return 0;
1564
3
}
1565
1566
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1567
                                                 const std::string& packed_file_path,
1568
3
                                                 PackedFileRecycleStats* stats) {
1569
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1570
3
    bool correction_ok = false;
1571
3
    cloud::PackedFileInfoPB packed_info;
1572
1573
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1574
3
        if (stopped()) {
1575
0
            LOG_WARNING("recycler stopped before processing packed file")
1576
0
                    .tag("instance_id", instance_id_)
1577
0
                    .tag("packed_file_path", packed_file_path)
1578
0
                    .tag("attempt", attempt);
1579
0
            return -1;
1580
0
        }
1581
1582
3
        std::unique_ptr<Transaction> txn;
1583
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1584
3
        if (err != TxnErrorCode::TXN_OK) {
1585
0
            LOG_WARNING("failed to create txn when processing packed file")
1586
0
                    .tag("instance_id", instance_id_)
1587
0
                    .tag("packed_file_path", packed_file_path)
1588
0
                    .tag("attempt", attempt)
1589
0
                    .tag("err", err);
1590
0
            return -1;
1591
0
        }
1592
1593
3
        std::string packed_val;
1594
3
        err = txn->get(packed_key, &packed_val);
1595
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1596
0
            return 0;
1597
0
        }
1598
3
        if (err != TxnErrorCode::TXN_OK) {
1599
0
            LOG_WARNING("failed to get packed file kv")
1600
0
                    .tag("instance_id", instance_id_)
1601
0
                    .tag("packed_file_path", packed_file_path)
1602
0
                    .tag("attempt", attempt)
1603
0
                    .tag("err", err);
1604
0
            return -1;
1605
0
        }
1606
1607
3
        if (!packed_info.ParseFromString(packed_val)) {
1608
0
            LOG_WARNING("failed to parse packed file info")
1609
0
                    .tag("instance_id", instance_id_)
1610
0
                    .tag("packed_file_path", packed_file_path)
1611
0
                    .tag("attempt", attempt);
1612
0
            return -1;
1613
0
        }
1614
1615
3
        int64_t now_sec = ::time(nullptr);
1616
3
        bool corrected = packed_info.corrected();
1617
3
        bool due = config::force_immediate_recycle ||
1618
3
                   now_sec - packed_info.created_at_sec() >=
1619
3
                           config::packed_file_correction_delay_seconds;
1620
1621
3
        if (!corrected && due) {
1622
3
            bool changed = false;
1623
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1624
0
                LOG_WARNING("correct_packed_file_info failed")
1625
0
                        .tag("instance_id", instance_id_)
1626
0
                        .tag("packed_file_path", packed_file_path)
1627
0
                        .tag("attempt", attempt);
1628
0
                return -1;
1629
0
            }
1630
3
            if (changed) {
1631
3
                std::string updated;
1632
3
                if (!packed_info.SerializeToString(&updated)) {
1633
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1634
0
                            .tag("instance_id", instance_id_)
1635
0
                            .tag("packed_file_path", packed_file_path)
1636
0
                            .tag("attempt", attempt);
1637
0
                    return -1;
1638
0
                }
1639
3
                txn->put(packed_key, updated);
1640
3
                err = txn->commit();
1641
3
                if (err == TxnErrorCode::TXN_OK) {
1642
3
                    if (stats) {
1643
3
                        ++stats->num_corrected;
1644
3
                    }
1645
3
                } else {
1646
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1647
0
                        LOG_WARNING(
1648
0
                                "failed to commit correction for packed file due to conflict, "
1649
0
                                "retrying")
1650
0
                                .tag("instance_id", instance_id_)
1651
0
                                .tag("packed_file_path", packed_file_path)
1652
0
                                .tag("attempt", attempt);
1653
0
                        sleep_for_packed_file_retry();
1654
0
                        packed_info.Clear();
1655
0
                        continue;
1656
0
                    }
1657
0
                    LOG_WARNING("failed to commit correction for packed file")
1658
0
                            .tag("instance_id", instance_id_)
1659
0
                            .tag("packed_file_path", packed_file_path)
1660
0
                            .tag("attempt", attempt)
1661
0
                            .tag("err", err);
1662
0
                    return -1;
1663
0
                }
1664
3
            }
1665
3
        }
1666
1667
3
        correction_ok = true;
1668
3
        break;
1669
3
    }
1670
1671
3
    if (!correction_ok) {
1672
0
        return -1;
1673
0
    }
1674
1675
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1676
3
          packed_info.ref_cnt() == 0)) {
1677
2
        return 0;
1678
2
    }
1679
1680
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1681
0
        LOG_WARNING("packed file missing resource id when recycling")
1682
0
                .tag("instance_id", instance_id_)
1683
0
                .tag("packed_file_path", packed_file_path);
1684
0
        return -1;
1685
0
    }
1686
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1687
1
    if (!accessor) {
1688
0
        LOG_WARNING("no accessor available to delete packed file")
1689
0
                .tag("instance_id", instance_id_)
1690
0
                .tag("packed_file_path", packed_file_path)
1691
0
                .tag("resource_id", packed_info.resource_id());
1692
0
        return -1;
1693
0
    }
1694
1
    int del_ret = accessor->delete_file(packed_file_path);
1695
1
    if (del_ret != 0 && del_ret != 1) {
1696
0
        LOG_WARNING("failed to delete packed file")
1697
0
                .tag("instance_id", instance_id_)
1698
0
                .tag("packed_file_path", packed_file_path)
1699
0
                .tag("resource_id", resource_id)
1700
0
                .tag("ret", del_ret);
1701
0
        return -1;
1702
0
    }
1703
1
    if (del_ret == 1) {
1704
0
        LOG_INFO("packed file already removed")
1705
0
                .tag("instance_id", instance_id_)
1706
0
                .tag("packed_file_path", packed_file_path)
1707
0
                .tag("resource_id", resource_id);
1708
1
    } else {
1709
1
        LOG_INFO("deleted packed file")
1710
1
                .tag("instance_id", instance_id_)
1711
1
                .tag("packed_file_path", packed_file_path)
1712
1
                .tag("resource_id", resource_id);
1713
1
    }
1714
1715
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1716
1
        std::unique_ptr<Transaction> del_txn;
1717
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1718
1
        if (err != TxnErrorCode::TXN_OK) {
1719
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1720
0
                    .tag("instance_id", instance_id_)
1721
0
                    .tag("packed_file_path", packed_file_path)
1722
0
                    .tag("del_attempt", del_attempt)
1723
0
                    .tag("err", err);
1724
0
            return -1;
1725
0
        }
1726
1727
1
        std::string latest_val;
1728
1
        err = del_txn->get(packed_key, &latest_val);
1729
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1730
0
            return 0;
1731
0
        }
1732
1
        if (err != TxnErrorCode::TXN_OK) {
1733
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1734
0
                    .tag("instance_id", instance_id_)
1735
0
                    .tag("packed_file_path", packed_file_path)
1736
0
                    .tag("del_attempt", del_attempt)
1737
0
                    .tag("err", err);
1738
0
            return -1;
1739
0
        }
1740
1741
1
        cloud::PackedFileInfoPB latest_info;
1742
1
        if (!latest_info.ParseFromString(latest_val)) {
1743
0
            LOG_WARNING("failed to parse packed file info before removal")
1744
0
                    .tag("instance_id", instance_id_)
1745
0
                    .tag("packed_file_path", packed_file_path)
1746
0
                    .tag("del_attempt", del_attempt);
1747
0
            return -1;
1748
0
        }
1749
1750
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1751
1
              latest_info.ref_cnt() == 0)) {
1752
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1753
0
                    .tag("instance_id", instance_id_)
1754
0
                    .tag("packed_file_path", packed_file_path)
1755
0
                    .tag("del_attempt", del_attempt);
1756
0
            return 0;
1757
0
        }
1758
1759
1
        del_txn->remove(packed_key);
1760
1
        err = del_txn->commit();
1761
1
        if (err == TxnErrorCode::TXN_OK) {
1762
1
            if (stats) {
1763
1
                ++stats->num_deleted;
1764
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1765
1
                                        static_cast<int64_t>(latest_val.size());
1766
1
                if (del_ret == 0 || del_ret == 1) {
1767
1
                    ++stats->num_object_deleted;
1768
1
                    int64_t object_size = latest_info.total_slice_bytes();
1769
1
                    if (object_size <= 0) {
1770
0
                        object_size = packed_info.total_slice_bytes();
1771
0
                    }
1772
1
                    stats->bytes_object_deleted += object_size;
1773
1
                }
1774
1
            }
1775
1
            LOG_INFO("removed packed file metadata")
1776
1
                    .tag("instance_id", instance_id_)
1777
1
                    .tag("packed_file_path", packed_file_path);
1778
1
            return 0;
1779
1
        }
1780
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1781
0
            if (del_attempt >= max_retry_times) {
1782
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1783
0
                        .tag("instance_id", instance_id_)
1784
0
                        .tag("packed_file_path", packed_file_path)
1785
0
                        .tag("del_attempt", del_attempt);
1786
0
                return -1;
1787
0
            }
1788
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1789
0
                    .tag("instance_id", instance_id_)
1790
0
                    .tag("packed_file_path", packed_file_path)
1791
0
                    .tag("del_attempt", del_attempt);
1792
0
            sleep_for_packed_file_retry();
1793
0
            continue;
1794
0
        }
1795
0
        LOG_WARNING("failed to remove packed file kv")
1796
0
                .tag("instance_id", instance_id_)
1797
0
                .tag("packed_file_path", packed_file_path)
1798
0
                .tag("del_attempt", del_attempt)
1799
0
                .tag("err", err);
1800
0
        return -1;
1801
0
    }
1802
1803
0
    return -1;
1804
1
}
1805
1806
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1807
4
                                            PackedFileRecycleStats* stats, int* ret) {
1808
4
    if (stats) {
1809
4
        ++stats->num_scanned;
1810
4
    }
1811
4
    std::string packed_file_path;
1812
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1813
0
        LOG_WARNING("failed to decode packed file key")
1814
0
                .tag("instance_id", instance_id_)
1815
0
                .tag("key", hex(key));
1816
0
        if (stats) {
1817
0
            ++stats->num_failed;
1818
0
        }
1819
0
        if (ret) {
1820
0
            *ret = -1;
1821
0
        }
1822
0
        return 0;
1823
0
    }
1824
1825
4
    cloud::PackedFileInfoPB packed_info;
1826
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1827
0
        LOG_WARNING("failed to parse packed file info from scan")
1828
0
                .tag("instance_id", instance_id_)
1829
0
                .tag("packed_file_path", packed_file_path);
1830
0
        if (stats) {
1831
0
            ++stats->num_failed;
1832
0
        }
1833
0
        if (ret) {
1834
0
            *ret = -1;
1835
0
        }
1836
0
        return 0;
1837
0
    }
1838
1839
4
    const int64_t now_sec = ::time(nullptr);
1840
4
    const bool due =
1841
4
            config::force_immediate_recycle ||
1842
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1843
4
    const bool need_correction = !packed_info.corrected() && due;
1844
4
    const bool need_recycle =
1845
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1846
4
    if (!need_correction && !need_recycle) {
1847
1
        return 0;
1848
1
    }
1849
1850
3
    std::string packed_key(key);
1851
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1852
3
    if (process_ret != 0) {
1853
0
        if (stats) {
1854
0
            ++stats->num_failed;
1855
0
        }
1856
0
        if (ret) {
1857
0
            *ret = -1;
1858
0
        }
1859
0
    }
1860
3
    return 0;
1861
4
}
1862
1863
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1864
6.34k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1865
6.34k
    if (config::force_immediate_recycle) {
1866
295
        return 0L;
1867
295
    }
1868
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1869
6.05k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1870
6.05k
    int64_t retention_seconds = config::retention_seconds;
1871
6.05k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1872
4.75k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1873
4.75k
    }
1874
6.05k
    int64_t final_expiration = expiration + retention_seconds;
1875
6.05k
    if (*earlest_ts > final_expiration) {
1876
17
        *earlest_ts = final_expiration;
1877
17
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1878
17
    }
1879
6.05k
    return final_expiration;
1880
6.34k
}
1881
1882
int64_t calculate_partition_expired_time(
1883
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1884
13
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1885
13
    if (config::force_immediate_recycle) {
1886
7
        return 0L;
1887
7
    }
1888
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1889
6
                                                            : partition_meta_pb.creation_time();
1890
6
    int64_t retention_seconds = config::retention_seconds;
1891
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1892
6
        retention_seconds =
1893
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1894
6
    }
1895
6
    int64_t final_expiration = expiration + retention_seconds;
1896
6
    if (*earlest_ts > final_expiration) {
1897
2
        *earlest_ts = final_expiration;
1898
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1899
2
    }
1900
6
    return final_expiration;
1901
13
}
1902
1903
int64_t calculate_index_expired_time(const std::string& instance_id_,
1904
                                     const RecycleIndexPB& index_meta_pb,
1905
19
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1906
19
    if (config::force_immediate_recycle) {
1907
13
        return 0L;
1908
13
    }
1909
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1910
6
                                                        : index_meta_pb.creation_time();
1911
6
    int64_t retention_seconds = config::retention_seconds;
1912
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1913
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1914
6
    }
1915
6
    int64_t final_expiration = expiration + retention_seconds;
1916
6
    if (*earlest_ts > final_expiration) {
1917
2
        *earlest_ts = final_expiration;
1918
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1919
2
    }
1920
6
    return final_expiration;
1921
19
}
1922
1923
int64_t calculate_tmp_rowset_expired_time(
1924
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1925
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1926
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1927
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1928
    //  duration or timeout always < `retention_time` in practice.
1929
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1930
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1931
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1932
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1933
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1934
53.2k
    if (*earlest_ts > final_expiration) {
1935
20
        *earlest_ts = final_expiration;
1936
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1937
20
    }
1938
53.2k
    return final_expiration;
1939
53.2k
}
1940
1941
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1942
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1943
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1944
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1945
11
        *earlest_ts = final_expiration / 1000;
1946
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1947
11
    }
1948
50.0k
    return final_expiration;
1949
50.0k
}
1950
1951
int64_t calculate_restore_job_expired_time(
1952
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1953
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1954
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1955
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1956
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1957
        // final state, recycle immediately
1958
41
        return 0L;
1959
41
    }
1960
    // not final state, wait much longer than the FE's timeout(1 day)
1961
0
    int64_t last_modified_s =
1962
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1963
0
    int64_t expiration = restore_job.expired_at_s() > 0
1964
0
                                 ? last_modified_s + restore_job.expired_at_s()
1965
0
                                 : last_modified_s;
1966
0
    int64_t final_expiration = expiration + config::retention_seconds;
1967
0
    if (*earlest_ts > final_expiration) {
1968
0
        *earlest_ts = final_expiration;
1969
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1970
0
    }
1971
0
    return final_expiration;
1972
41
}
1973
1974
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1975
537
    AbortTxnRequest req;
1976
537
    TxnInfoPB txn_info;
1977
537
    MetaServiceCode code = MetaServiceCode::OK;
1978
537
    std::string msg;
1979
537
    std::stringstream ss;
1980
537
    std::unique_ptr<Transaction> txn;
1981
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1982
537
    if (err != TxnErrorCode::TXN_OK) {
1983
0
        LOG_WARNING("failed to create txn").tag("err", err);
1984
0
        return -1;
1985
0
    }
1986
1987
    // get txn index
1988
537
    TxnIndexPB txn_idx_pb;
1989
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1990
537
    std::string index_val;
1991
537
    err = txn->get(index_key, &index_val);
1992
537
    if (err != TxnErrorCode::TXN_OK) {
1993
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1994
            // maybe recycled
1995
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1996
2
                    .tag("key", hex(index_key))
1997
2
                    .tag("txn_id", txn_id);
1998
2
            return 0;
1999
2
        }
2000
0
        LOG_WARNING("failed to get txn index")
2001
0
                .tag("err", err)
2002
0
                .tag("key", hex(index_key))
2003
0
                .tag("txn_id", txn_id);
2004
0
        return -1;
2005
2
    }
2006
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
2007
1
        LOG_WARNING("failed to parse txn index")
2008
1
                .tag("err", err)
2009
1
                .tag("key", hex(index_key))
2010
1
                .tag("txn_id", txn_id);
2011
1
        return -1;
2012
1
    }
2013
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
2014
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
2015
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
2016
3
                .tag("key", hex(index_key))
2017
3
                .tag("txn_id", txn_id)
2018
3
                .tag("db_id",
2019
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
2020
3
        return -1;
2021
3
    }
2022
2023
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
2024
531
    const int64_t owner_txn_id =
2025
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
2026
531
    if (owner_txn_id <= 0) {
2027
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2028
1
                .tag("key", hex(index_key))
2029
1
                .tag("txn_id", txn_id)
2030
1
                .tag("owner_txn_id", owner_txn_id);
2031
1
        return -1;
2032
1
    }
2033
2034
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2035
530
    std::string info_val;
2036
530
    err = txn->get(info_key, &info_val);
2037
530
    if (err != TxnErrorCode::TXN_OK) {
2038
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2039
            // maybe recycled
2040
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2041
1
                        owner_txn_id, instance_id_)
2042
1
                    .tag("key", hex(info_key))
2043
1
                    .tag("txn_id", txn_id)
2044
1
                    .tag("owner_txn_id", owner_txn_id);
2045
1
            return 0;
2046
1
        }
2047
0
        LOG_WARNING("failed to get txn info")
2048
0
                .tag("err", err)
2049
0
                .tag("key", hex(info_key))
2050
0
                .tag("txn_id", txn_id)
2051
0
                .tag("owner_txn_id", owner_txn_id);
2052
0
        return -1;
2053
1
    }
2054
529
    if (!txn_info.ParseFromString(info_val)) {
2055
1
        LOG_WARNING("failed to parse txn info")
2056
1
                .tag("err", err)
2057
1
                .tag("key", hex(info_key))
2058
1
                .tag("txn_id", txn_id)
2059
1
                .tag("owner_txn_id", owner_txn_id);
2060
1
        return -1;
2061
1
    }
2062
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2063
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2064
1
                .tag("key", hex(info_key))
2065
1
                .tag("txn_id", txn_id)
2066
1
                .tag("owner_txn_id", owner_txn_id)
2067
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2068
1
        return -1;
2069
1
    }
2070
2071
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2072
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2073
514
                .tag("key", hex(info_key))
2074
514
                .tag("txn_id", txn_id)
2075
514
                .tag("owner_txn_id", owner_txn_id);
2076
514
        return 0;
2077
514
    }
2078
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2079
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2080
4
                    owner_txn_id, txn_info.status())
2081
4
                .tag("key", hex(info_key))
2082
4
                .tag("txn_id", txn_id)
2083
4
                .tag("owner_txn_id", owner_txn_id);
2084
4
        return -1;
2085
4
    }
2086
2087
9
    req.set_txn_id(owner_txn_id);
2088
9
    req.set_db_id(db_id);
2089
2090
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2091
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2092
9
                 << " txn_info=" << txn_info.ShortDebugString();
2093
2094
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2095
9
    if (code != MetaServiceCode::OK) {
2096
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2097
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2098
0
                     << " code=" << code << " msg=" << msg;
2099
0
        return -1;
2100
0
    }
2101
2102
9
    err = txn->commit();
2103
9
    if (err != TxnErrorCode::TXN_OK) {
2104
0
        code = cast_as<ErrCategory::COMMIT>(err);
2105
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2106
0
        msg = ss.str();
2107
0
        return -1;
2108
0
    }
2109
2110
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2111
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2112
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2113
9
                 << " msg=" << msg;
2114
2115
9
    return 0;
2116
9
}
2117
2118
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2119
11
                                                   const std::string& job_id) {
2120
11
    FinishTabletJobRequest req;
2121
11
    FinishTabletJobResponse res;
2122
11
    req.set_action(FinishTabletJobRequest::ABORT);
2123
11
    MetaServiceCode code = MetaServiceCode::OK;
2124
11
    std::string msg;
2125
11
    std::stringstream ss;
2126
2127
11
    TabletIndexPB tablet_idx;
2128
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2129
11
    if (ret == 1) {
2130
        // tablet maybe recycled, directly return 0
2131
1
        return 0;
2132
10
    } else if (ret != 0) {
2133
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2134
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2135
0
        return ret;
2136
0
    }
2137
2138
10
    std::unique_ptr<Transaction> txn;
2139
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2140
10
    if (err != TxnErrorCode::TXN_OK) {
2141
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2142
0
        return -1;
2143
0
    }
2144
2145
10
    std::string job_key =
2146
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2147
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2148
10
    std::string job_val;
2149
10
    err = txn->get(job_key, &job_val);
2150
10
    if (err != TxnErrorCode::TXN_OK) {
2151
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2152
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2153
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2154
            // A previous recycler round may have aborted the job. The caller must recheck the
2155
            // recycle key before deleting object data.
2156
1
            return 0;
2157
1
        }
2158
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2159
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2160
0
                     << " key=" << hex(job_key);
2161
0
        return -1;
2162
1
    }
2163
2164
9
    TabletJobInfoPB job_pb;
2165
9
    if (!job_pb.ParseFromString(job_val)) {
2166
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2167
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2168
0
        return -1;
2169
0
    }
2170
2171
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2172
9
    for (const auto& compaction : job_pb.compaction()) {
2173
9
        if (compaction.id() == job_id) {
2174
5
            matched_compaction = &compaction;
2175
5
            break;
2176
5
        }
2177
9
    }
2178
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2179
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2180
9
        job_pb.schema_change().id() == job_id) {
2181
3
        matched_schema_change = &job_pb.schema_change();
2182
3
    }
2183
2184
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2185
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2186
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2187
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2188
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2189
        // both the base and mirrored schema-change records.
2190
8
        if (matched_compaction != nullptr) {
2191
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2192
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2193
5
        } else {
2194
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2195
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2196
3
        }
2197
8
        req.set_action(FinishTabletJobRequest::ABORT);
2198
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2199
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2200
8
                           ss);
2201
8
        if (code != MetaServiceCode::OK) {
2202
            // These two codes mean that the job cannot be aborted anymore.
2203
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2204
            // There is no running job that still owns the PREPARE rowset, so the caller may
2205
            // recheck the recycle key.
2206
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2207
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2208
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2209
            // job again and continue recycling only when the target job id no longer exists.
2210
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2211
0
                std::unique_ptr<Transaction> check_txn;
2212
0
                err = txn_kv_->create_txn(&check_txn);
2213
0
                if (err != TxnErrorCode::TXN_OK) {
2214
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2215
0
                                 << instance_id_ << " err=" << err;
2216
0
                    return -1;
2217
0
                }
2218
2219
0
                const auto& idx = req.job().idx();
2220
0
                std::string current_job_key =
2221
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2222
0
                                        idx.partition_id(), idx.tablet_id()});
2223
0
                std::string current_job_val;
2224
0
                err = check_txn->get(current_job_key, &current_job_val);
2225
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
0
                    no_job_to_abort = true;
2227
0
                } else if (err != TxnErrorCode::TXN_OK) {
2228
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2229
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2230
0
                                 << " key=" << hex(current_job_key);
2231
0
                    return -1;
2232
0
                } else {
2233
0
                    TabletJobInfoPB current_job;
2234
0
                    if (!current_job.ParseFromString(current_job_val)) {
2235
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2236
0
                                     << " tablet_id=" << idx.tablet_id()
2237
0
                                     << " key=" << hex(current_job_key);
2238
0
                        return -1;
2239
0
                    }
2240
0
                    if (matched_compaction != nullptr) {
2241
0
                        no_job_to_abort = true;
2242
0
                        for (const auto& compaction : current_job.compaction()) {
2243
0
                            if (compaction.id() == job_id) {
2244
0
                                no_job_to_abort = false;
2245
0
                                break;
2246
0
                            }
2247
0
                        }
2248
0
                    } else {
2249
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2250
0
                                          current_job.schema_change().id() != job_id;
2251
0
                    }
2252
0
                }
2253
0
            }
2254
0
            if (no_job_to_abort) {
2255
0
                return 0;
2256
0
            }
2257
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2258
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2259
0
                         << " msg=" << msg;
2260
0
            return -1;
2261
0
        }
2262
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2263
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2264
8
                     << " code=" << code << " msg=" << msg;
2265
8
    } else {
2266
        // clang-format off
2267
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2268
1
                  << ", instance_id=" << instance_id_ 
2269
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2270
1
                  << ", job_id=" << job_id
2271
1
                  << ", rowset_id=" << rowset_id;
2272
        // clang-format on
2273
1
    }
2274
2275
9
    return 0;
2276
9
}
2277
2278
template <typename T>
2279
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
13
        return rowset_meta_pb.mutable_rowset_meta();
2282
13
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2279
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
13
        return rowset_meta_pb.mutable_rowset_meta();
2282
    } else {
2283
        return &rowset_meta_pb;
2284
    }
2285
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2279
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
        return rowset_meta_pb.mutable_rowset_meta();
2282
9
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
9
}
2286
2287
template <typename T>
2288
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
833
        return rowset_meta_pb.rowset_meta();
2291
833
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2288
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
833
        return rowset_meta_pb.rowset_meta();
2291
    } else {
2292
        return rowset_meta_pb;
2293
    }
2294
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2288
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
        return rowset_meta_pb.rowset_meta();
2291
799
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
799
}
2295
2296
template <typename T>
2297
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2298
1.07k
        const T& rowset_meta_pb) {
2299
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
545
    }
2304
2305
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
1.07k
    RelatedTxnOrJobAbortTask task;
2307
1.07k
    task.tablet_id = rs_meta.tablet_id();
2308
1.07k
    task.start_version = rs_meta.start_version();
2309
1.07k
    task.end_version = rs_meta.end_version();
2310
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2311
1.07k
    if (rs_meta.has_load_id()) {
2312
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
1.05k
        task.txn_id = rs_meta.txn_id();
2314
1.05k
        return task;
2315
1.05k
    }
2316
19
    if (rs_meta.has_job_id()) {
2317
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
14
        task.job_id = rs_meta.job_id();
2319
14
        return task;
2320
14
    }
2321
5
    return std::nullopt;
2322
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
545
        const T& rowset_meta_pb) {
2299
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
545
    }
2304
2305
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
545
    RelatedTxnOrJobAbortTask task;
2307
545
    task.tablet_id = rs_meta.tablet_id();
2308
545
    task.start_version = rs_meta.start_version();
2309
545
    task.end_version = rs_meta.end_version();
2310
545
    task.rowset_id = rs_meta.rowset_id_v2();
2311
545
    if (rs_meta.has_load_id()) {
2312
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
534
        task.txn_id = rs_meta.txn_id();
2314
534
        return task;
2315
534
    }
2316
11
    if (rs_meta.has_job_id()) {
2317
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
10
        task.job_id = rs_meta.job_id();
2319
10
        return task;
2320
10
    }
2321
1
    return std::nullopt;
2322
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
526
        const T& rowset_meta_pb) {
2299
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
            return std::nullopt;
2302
        }
2303
    }
2304
2305
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
526
    RelatedTxnOrJobAbortTask task;
2307
526
    task.tablet_id = rs_meta.tablet_id();
2308
526
    task.start_version = rs_meta.start_version();
2309
526
    task.end_version = rs_meta.end_version();
2310
526
    task.rowset_id = rs_meta.rowset_id_v2();
2311
526
    if (rs_meta.has_load_id()) {
2312
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
518
        task.txn_id = rs_meta.txn_id();
2314
518
        return task;
2315
518
    }
2316
8
    if (rs_meta.has_job_id()) {
2317
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
4
        task.job_id = rs_meta.job_id();
2319
4
        return task;
2320
4
    }
2321
4
    return std::nullopt;
2322
8
}
2323
2324
template <typename T>
2325
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2326
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
268
    }
2332
2333
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
523
    }
2341
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
268
    }
2332
2333
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
264
    }
2341
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
            return false;
2330
        }
2331
    }
2332
2333
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
259
    }
2341
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
261
}
2343
2344
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2345
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2346
71
}
2347
2348
template <typename T>
2349
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2350
18
                                   const std::vector<std::string>& keys) {
2351
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
18
        std::unique_ptr<Transaction> txn;
2355
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
18
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
18
        std::vector<std::optional<std::string>> values;
2361
18
        err = txn->batch_get(&values, batch_keys);
2362
18
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
18
        DCHECK_EQ(values.size(), batch_keys.size());
2368
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
22
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
22
            const auto& key = batch_keys[i];
2374
22
            auto val = values[i].value();
2375
22
            T rowset_meta_pb;
2376
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
13
            }
2389
22
            val.clear();
2390
22
            rowset_meta_pb.SerializeToString(&val);
2391
22
            txn->put(key, val);
2392
22
        }
2393
18
        err = txn->commit();
2394
18
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
18
    }
2399
2400
17
    return 0;
2401
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
11
                                   const std::vector<std::string>& keys) {
2351
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
11
        std::unique_ptr<Transaction> txn;
2355
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
11
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
11
        std::vector<std::optional<std::string>> values;
2361
11
        err = txn->batch_get(&values, batch_keys);
2362
11
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
11
        DCHECK_EQ(values.size(), batch_keys.size());
2368
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
13
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
13
            const auto& key = batch_keys[i];
2374
13
            auto val = values[i].value();
2375
13
            T rowset_meta_pb;
2376
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
13
            }
2389
13
            val.clear();
2390
13
            rowset_meta_pb.SerializeToString(&val);
2391
13
            txn->put(key, val);
2392
13
        }
2393
11
        err = txn->commit();
2394
11
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
11
    }
2399
2400
10
    return 0;
2401
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
7
                                   const std::vector<std::string>& keys) {
2351
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
7
        std::unique_ptr<Transaction> txn;
2355
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
7
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
7
        std::vector<std::optional<std::string>> values;
2361
7
        err = txn->batch_get(&values, batch_keys);
2362
7
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
7
        DCHECK_EQ(values.size(), batch_keys.size());
2368
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
9
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
9
            const auto& key = batch_keys[i];
2374
9
            auto val = values[i].value();
2375
9
            T rowset_meta_pb;
2376
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
            }
2389
9
            val.clear();
2390
9
            rowset_meta_pb.SerializeToString(&val);
2391
9
            txn->put(key, val);
2392
9
        }
2393
7
        err = txn->commit();
2394
7
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
0
            return -1;
2397
0
        }
2398
7
    }
2399
2400
7
    return 0;
2401
7
}
2402
2403
template <typename T>
2404
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2405
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
0
        }
2411
7
    });
2412
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
11
        }
2411
11
    });
2412
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
7
        }
2411
7
    });
2412
7
}
2413
2414
template <typename T>
2415
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2416
                                 const std::vector<std::string>& keys,
2417
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
22
        std::unique_ptr<Transaction> txn;
2422
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
22
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
22
        std::vector<std::optional<std::string>> values;
2428
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
22
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
22
        DCHECK_EQ(values.size(), batch_keys.size());
2435
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
533
            const std::string& key = batch_keys[idx];
2437
533
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
533
            T rowset_meta_pb;
2442
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
533
                abort_task.has_value()) {
2449
533
                abort_task->key = key;
2450
533
                abort_tasks->emplace_back(std::move(*abort_task));
2451
533
            }
2452
533
        }
2453
22
    }
2454
20
    return 0;
2455
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
16
        std::unique_ptr<Transaction> txn;
2422
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
16
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
16
        std::vector<std::optional<std::string>> values;
2428
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
16
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
16
        DCHECK_EQ(values.size(), batch_keys.size());
2435
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
272
            const std::string& key = batch_keys[idx];
2437
272
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
272
            T rowset_meta_pb;
2442
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
272
                abort_task.has_value()) {
2449
272
                abort_task->key = key;
2450
272
                abort_tasks->emplace_back(std::move(*abort_task));
2451
272
            }
2452
272
        }
2453
16
    }
2454
15
    return 0;
2455
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
6
        std::unique_ptr<Transaction> txn;
2422
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
6
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
6
        std::vector<std::optional<std::string>> values;
2428
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
6
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
6
        DCHECK_EQ(values.size(), batch_keys.size());
2435
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
261
            const std::string& key = batch_keys[idx];
2437
261
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
261
            T rowset_meta_pb;
2442
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
261
                abort_task.has_value()) {
2449
261
                abort_task->key = key;
2450
261
                abort_tasks->emplace_back(std::move(*abort_task));
2451
261
            }
2452
261
        }
2453
6
    }
2454
5
    return 0;
2455
5
}
2456
2457
template <typename T>
2458
int batch_recheck_rowsets_after_abort(
2459
        TxnKv* txn_kv, const std::string& instance_id,
2460
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2461
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
18
    int ret = 0;
2463
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
20
        std::vector<std::string> batch_keys;
2466
20
        batch_keys.reserve(limit - offset);
2467
550
        for (size_t idx = offset; idx < limit; ++idx) {
2468
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
530
        }
2470
2471
20
        std::unique_ptr<Transaction> txn;
2472
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
20
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
20
        std::vector<std::optional<std::string>> values;
2481
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
20
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
20
        DCHECK_EQ(values.size(), batch_keys.size());
2489
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
20
                                 &batch_size);
2492
2493
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
530
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
529
            T rowset_meta_pb;
2500
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
528
        }
2519
20
    }
2520
18
    return ret;
2521
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
13
    int ret = 0;
2463
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
14
        std::vector<std::string> batch_keys;
2466
14
        batch_keys.reserve(limit - offset);
2467
283
        for (size_t idx = offset; idx < limit; ++idx) {
2468
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
269
        }
2470
2471
14
        std::unique_ptr<Transaction> txn;
2472
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
14
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
14
        std::vector<std::optional<std::string>> values;
2481
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
14
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
14
        DCHECK_EQ(values.size(), batch_keys.size());
2489
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
14
                                 &batch_size);
2492
2493
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
269
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
268
            T rowset_meta_pb;
2500
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
267
        }
2519
14
    }
2520
13
    return ret;
2521
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
5
    int ret = 0;
2463
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
6
        std::vector<std::string> batch_keys;
2466
6
        batch_keys.reserve(limit - offset);
2467
267
        for (size_t idx = offset; idx < limit; ++idx) {
2468
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
261
        }
2470
2471
6
        std::unique_ptr<Transaction> txn;
2472
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
6
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
6
        std::vector<std::optional<std::string>> values;
2481
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
6
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
6
        DCHECK_EQ(values.size(), batch_keys.size());
2489
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
6
                                 &batch_size);
2492
2493
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
261
            if (!values[idx].has_value()) {
2496
0
                continue;
2497
0
            }
2498
2499
261
            T rowset_meta_pb;
2500
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
0
                             << instance_id << " key=" << hex(key);
2515
0
                continue;
2516
0
            }
2517
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
261
        }
2519
6
    }
2520
5
    return ret;
2521
5
}
2522
2523
template <typename T>
2524
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2525
        const std::vector<std::string>& keys,
2526
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
20
    int ret = 0;
2534
533
    for (const auto& abort_task : abort_tasks) {
2535
533
        int abort_ret = 0;
2536
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
526
        } else {
2539
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
7
                                                     abort_task.job_id);
2541
7
        }
2542
533
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
530
    }
2551
20
    return ret;
2552
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
15
    int ret = 0;
2534
272
    for (const auto& abort_task : abort_tasks) {
2535
272
        int abort_ret = 0;
2536
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
267
        } else {
2539
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
5
                                                     abort_task.job_id);
2541
5
        }
2542
272
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
269
    }
2551
15
    return ret;
2552
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
5
    int ret = 0;
2534
261
    for (const auto& abort_task : abort_tasks) {
2535
261
        int abort_ret = 0;
2536
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
259
        } else {
2539
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
2
                                                     abort_task.job_id);
2541
2
        }
2542
261
        if (abort_ret != 0) {
2543
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
0
            ret = abort_ret;
2547
0
            continue;
2548
0
        }
2549
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
261
    }
2551
5
    return ret;
2552
5
}
2553
2554
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2555
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2556
15
        std::atomic_long* num_recycled) {
2557
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2558
15
                                  num_recycled]() mutable {
2559
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
15
                                                                            keys_to_recheck);
2562
15
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
15
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
13
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
267
            const auto& current_meta = current_rowset.rowset_meta();
2580
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
267
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
266
                                                   current_meta.tablet_id(),
2587
266
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
266
            std::vector<std::string> keys {key};
2591
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
266
        }
2597
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
2
                                  num_recycled]() mutable {
2559
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
2
                                                                            keys_to_recheck);
2562
2
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2
        if (keys_to_recheck.empty()) {
2568
0
            return;
2569
0
        }
2570
2571
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
2
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
2
            const auto& current_meta = current_rowset.rowset_meta();
2580
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
2
                                   current_meta.rowset_id_v2()) != 0) {
2582
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
0
                continue;
2584
0
            }
2585
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
2
                                                   current_meta.tablet_id(),
2587
2
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
2
            std::vector<std::string> keys {key};
2591
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
2
        }
2597
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
13
                                  num_recycled]() mutable {
2559
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
13
                                                                            keys_to_recheck);
2562
13
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
13
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
11
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
265
            const auto& current_meta = current_rowset.rowset_meta();
2580
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
265
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
264
                                                   current_meta.tablet_id(),
2587
264
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
264
            std::vector<std::string> keys {key};
2591
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
264
        }
2597
11
    });
2598
15
    if (ret != 0) {
2599
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2600
0
    }
2601
15
}
2602
2603
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2604
                                                      std::vector<std::string> rowset_keys_to_abort,
2605
                                                      std::atomic_long* num_recycled,
2606
5
                                                      RecyclerMetricsContext* metrics_context) {
2607
5
    if (rowset_keys_to_abort.empty()) {
2608
0
        return;
2609
0
    }
2610
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2611
5
                        metrics_context]() mutable {
2612
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
5
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
5
        std::vector<std::string> keys_to_delete;
2623
5
        std::vector<std::string> ref_count_keys_to_delete;
2624
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
5
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
261
            keys_to_delete.push_back(key);
2633
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
261
        }
2637
2638
5
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
5
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
261
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
261
        }
2655
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
3
                        metrics_context]() mutable {
2612
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
3
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
3
        std::vector<std::string> keys_to_delete;
2623
3
        std::vector<std::string> ref_count_keys_to_delete;
2624
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
3
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
3
            keys_to_delete.push_back(key);
2633
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
3
        }
2637
2638
3
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
3
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
3
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
3
        }
2655
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
2
                        metrics_context]() mutable {
2612
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
2
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
2
        std::vector<std::string> keys_to_delete;
2623
2
        std::vector<std::string> ref_count_keys_to_delete;
2624
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
2
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
258
            keys_to_delete.push_back(key);
2633
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
258
        }
2637
2638
2
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
2
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
258
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
258
        }
2655
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
2
    });
2666
5
}
2667
2668
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2669
1
    const std::string task_name = "recycle_ref_rowsets";
2670
1
    *has_unrecycled_rowsets = false;
2671
2672
1
    std::string data_rowset_ref_count_key_start =
2673
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2674
1
    std::string data_rowset_ref_count_key_end =
2675
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2676
2677
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2678
2679
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2680
1
    register_recycle_task(task_name, start_time);
2681
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
2689
2690
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2691
1
    std::set<int64_t> tablets_with_refs;
2692
1
    int64_t num_scanned = 0;
2693
2694
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2695
0
        ++num_scanned;
2696
0
        int64_t tablet_id;
2697
0
        std::string rowset_id;
2698
0
        std::string_view key(k);
2699
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2700
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2701
0
            return 0; // Continue scanning
2702
0
        }
2703
2704
0
        tablets_with_refs.insert(tablet_id);
2705
0
        return 0;
2706
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2707
2708
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2709
1
                         std::move(scan_func)) != 0) {
2710
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2711
0
        return -1;
2712
0
    }
2713
2714
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2715
1
             tablets_with_refs.size(), num_scanned)
2716
1
            .tag("instance_id", instance_id_);
2717
2718
    // Phase 2: Recycle each tablet
2719
1
    int64_t num_recycled_tablets = 0;
2720
1
    for (int64_t tablet_id : tablets_with_refs) {
2721
0
        if (stopped()) {
2722
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2723
0
                    .tag("instance_id", instance_id_)
2724
0
                    .tag("tablets_processed", num_recycled_tablets)
2725
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2726
0
            break;
2727
0
        }
2728
2729
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2730
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2731
0
            LOG_WARNING("failed to recycle tablet")
2732
0
                    .tag("instance_id", instance_id_)
2733
0
                    .tag("tablet_id", tablet_id);
2734
0
            return -1;
2735
0
        }
2736
0
        ++num_recycled_tablets;
2737
0
    }
2738
2739
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2740
1
            .tag("instance_id", instance_id_)
2741
1
            .tag("total_tablets", tablets_with_refs.size());
2742
2743
    // Phase 3: Scan again to check if any ref count keys still exist
2744
1
    std::unique_ptr<Transaction> txn;
2745
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2746
1
    if (err != TxnErrorCode::TXN_OK) {
2747
0
        LOG_WARNING("failed to create txn for final check")
2748
0
                .tag("instance_id", instance_id_)
2749
0
                .tag("err", err);
2750
0
        return -1;
2751
0
    }
2752
2753
1
    std::unique_ptr<RangeGetIterator> iter;
2754
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2755
1
    if (err != TxnErrorCode::TXN_OK) {
2756
0
        LOG_WARNING("failed to create range iterator for final check")
2757
0
                .tag("instance_id", instance_id_)
2758
0
                .tag("err", err);
2759
0
        return -1;
2760
0
    }
2761
2762
1
    *has_unrecycled_rowsets = iter->has_next();
2763
1
    if (*has_unrecycled_rowsets) {
2764
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2765
0
                .tag("instance_id", instance_id_);
2766
0
    }
2767
2768
1
    return 0;
2769
1
}
2770
2771
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2772
16
                                                         RecyclerMetricsContext* metrics_context) {
2773
16
    std::string end = prefix;
2774
16
    end.push_back('\xff');
2775
16
    std::vector<std::string_view> keys;
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
4
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
4
        keys.push_back(key);
2778
4
        return 0;
2779
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
2780
16
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
16
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
16
        DORIS_CLOUD_DEFER {
2785
16
            keys.clear();
2786
16
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
16
        const size_t num_keys = keys.size();
2788
16
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
16
        metrics_context->total_recycled_num += num_keys;
2795
16
        metrics_context->report();
2796
16
        return 0;
2797
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
4
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
4
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
2787
4
        const size_t num_keys = keys.size();
2788
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
4
        metrics_context->total_recycled_num += num_keys;
2795
4
        metrics_context->report();
2796
4
        return 0;
2797
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
12
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
12
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
12
        const size_t num_keys = keys.size();
2788
12
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
12
        metrics_context->total_recycled_num += num_keys;
2795
12
        metrics_context->report();
2796
12
        return 0;
2797
12
    };
2798
16
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2799
16
}
2800
2801
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2802
                                              const RecycleIndexPB& recycle_index,
2803
8
                                              std::string_view recycle_key) {
2804
8
    std::unique_ptr<Transaction> txn;
2805
8
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2806
8
    if (err != TxnErrorCode::TXN_OK) {
2807
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2808
0
                .tag("instance_id", instance_id_)
2809
0
                .tag("stream_id", stream_id)
2810
0
                .tag("err", err);
2811
0
        return -1;
2812
0
    }
2813
2814
8
    std::string current_recycle_value;
2815
8
    err = txn->get(recycle_key, &current_recycle_value);
2816
8
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2817
0
        return 0;
2818
0
    }
2819
8
    if (err != TxnErrorCode::TXN_OK) {
2820
0
        LOG_WARNING("failed to read table stream recycle index")
2821
0
                .tag("instance_id", instance_id_)
2822
0
                .tag("stream_id", stream_id)
2823
0
                .tag("err", err);
2824
0
        return -1;
2825
0
    }
2826
8
    RecycleIndexPB current_recycle_index;
2827
8
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2828
8
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2829
8
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2830
8
        current_recycle_index.db_id() != recycle_index.db_id() ||
2831
8
        current_recycle_index.table_id() != recycle_index.table_id() ||
2832
8
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2833
0
        LOG_WARNING("table stream recycle index changed during recycling")
2834
0
                .tag("instance_id", instance_id_)
2835
0
                .tag("stream_id", stream_id);
2836
0
        return -1;
2837
0
    }
2838
2839
8
    txn->remove(recycle_key);
2840
8
    err = txn->commit();
2841
8
    if (err != TxnErrorCode::TXN_OK) {
2842
0
        LOG_WARNING("failed to commit final table stream cleanup")
2843
0
                .tag("instance_id", instance_id_)
2844
0
                .tag("stream_id", stream_id)
2845
0
                .tag("err", err);
2846
0
        return -1;
2847
0
    }
2848
8
    return 0;
2849
8
}
2850
2851
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2852
8
                                     std::string_view recycle_key) {
2853
8
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2854
0
        LOG_WARNING("table stream recycle index is missing binding")
2855
0
                .tag("instance_id", instance_id_)
2856
0
                .tag("stream_id", stream_id);
2857
0
        return -1;
2858
0
    }
2859
2860
8
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2861
8
    DORIS_CLOUD_DEFER {
2862
8
        metrics_context.finish_report();
2863
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
3
    DORIS_CLOUD_DEFER {
2862
3
        metrics_context.finish_report();
2863
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
5
    DORIS_CLOUD_DEFER {
2862
5
        metrics_context.finish_report();
2863
5
    };
2864
8
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2865
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2866
8
            recycle_index.stream_db_id(), stream_id);
2867
8
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2868
0
        return -1;
2869
0
    }
2870
8
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2871
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2872
8
            recycle_index.stream_db_id(), stream_id);
2873
8
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2874
8
        stopped()) {
2875
0
        return -1;
2876
0
    }
2877
8
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2878
8
}
2879
2880
int InstanceRecycler::recycle_partition_table_stream_offsets(
2881
        int64_t db_id, int64_t table_id, int64_t partition_id,
2882
12
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2883
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2884
12
    DORIS_CLOUD_DEFER {
2885
12
        metrics_context.finish_report();
2886
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
1
    DORIS_CLOUD_DEFER {
2885
1
        metrics_context.finish_report();
2886
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
11
    DORIS_CLOUD_DEFER {
2885
11
        metrics_context.finish_report();
2886
11
    };
2887
12
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2888
17
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2889
5
        const size_t end_index =
2890
5
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2891
5
        std::unique_ptr<Transaction> txn;
2892
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2893
5
        if (err != TxnErrorCode::TXN_OK) {
2894
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2895
0
                    .tag("instance_id", instance_id_)
2896
0
                    .tag("partition_id", partition_id)
2897
0
                    .tag("err", err);
2898
0
            return -1;
2899
0
        }
2900
12
        for (size_t i = begin_index; i < end_index; ++i) {
2901
7
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2902
7
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2903
7
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2904
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2905
0
                        .tag("instance_id", instance_id_)
2906
0
                        .tag("partition_id", partition_id)
2907
0
                        .tag("stream_id", stream.stream_id());
2908
0
                return -1;
2909
0
            }
2910
7
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2911
7
                                                 stream.base_table_id(), stream.stream_db_id(),
2912
7
                                                 stream.stream_id(), partition_id}));
2913
7
            versioned_remove_all(
2914
7
                    txn.get(), versioned::table_stream_offset_key(
2915
7
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2916
7
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2917
7
        }
2918
5
        err = txn->commit();
2919
5
        if (err != TxnErrorCode::TXN_OK) {
2920
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2921
0
                    .tag("instance_id", instance_id_)
2922
0
                    .tag("partition_id", partition_id)
2923
0
                    .tag("err", err);
2924
0
            return -1;
2925
0
        }
2926
5
        metrics_context.total_recycled_num += end_index - begin_index;
2927
5
        metrics_context.report();
2928
5
    }
2929
12
    return 0;
2930
12
}
2931
2932
25
int InstanceRecycler::recycle_indexes() {
2933
25
    const std::string task_name = "recycle_indexes";
2934
25
    int64_t num_scanned = 0;
2935
25
    int64_t num_expired = 0;
2936
25
    int64_t num_recycled = 0;
2937
25
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2938
2939
25
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2940
25
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2941
25
    std::string index_key0;
2942
25
    std::string index_key1;
2943
25
    recycle_index_key(index_key_info0, &index_key0);
2944
25
    recycle_index_key(index_key_info1, &index_key1);
2945
2946
25
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2947
2948
25
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2949
25
    register_recycle_task(task_name, start_time);
2950
2951
25
    DORIS_CLOUD_DEFER {
2952
25
        unregister_recycle_task(task_name);
2953
25
        int64_t cost =
2954
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
25
        metrics_context.finish_report();
2956
25
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
25
                .tag("instance_id", instance_id_)
2958
25
                .tag("num_scanned", num_scanned)
2959
25
                .tag("num_expired", num_expired)
2960
25
                .tag("num_recycled", num_recycled);
2961
25
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
4
    DORIS_CLOUD_DEFER {
2952
4
        unregister_recycle_task(task_name);
2953
4
        int64_t cost =
2954
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
4
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
4
                .tag("instance_id", instance_id_)
2958
4
                .tag("num_scanned", num_scanned)
2959
4
                .tag("num_expired", num_expired)
2960
4
                .tag("num_recycled", num_recycled);
2961
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
21
    DORIS_CLOUD_DEFER {
2952
21
        unregister_recycle_task(task_name);
2953
21
        int64_t cost =
2954
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
21
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
21
                .tag("instance_id", instance_id_)
2958
21
                .tag("num_scanned", num_scanned)
2959
21
                .tag("num_expired", num_expired)
2960
21
                .tag("num_recycled", num_recycled);
2961
21
    };
2962
2963
25
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2964
2965
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2966
25
    std::vector<std::string_view> index_keys;
2967
25
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
18
        ++num_scanned;
2969
18
        RecycleIndexPB index_pb;
2970
18
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
18
        int64_t current_time = ::time(nullptr);
2975
18
        if (current_time <
2976
18
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
18
        ++num_expired;
2980
        // decode index_id
2981
18
        auto k1 = k;
2982
18
        k1.remove_prefix(1);
2983
18
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
18
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
18
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
18
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
18
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
18
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
18
        std::unique_ptr<Transaction> txn;
2992
18
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
18
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
18
        std::string val;
2998
18
        err = txn->get(k, &val);
2999
18
        if (err ==
3000
18
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
18
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
18
        index_pb.Clear();
3009
18
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
18
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
16
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
16
            txn->put(k, index_pb.SerializeAsString());
3016
16
            err = txn->commit();
3017
16
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
16
        }
3022
18
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
8
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
8
            metrics_context.total_recycled_num = ++num_recycled;
3030
8
            metrics_context.report();
3031
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
8
            return 0;
3033
8
        }
3034
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
9
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
3
            std::unique_ptr<Transaction> txn;
3045
3
            err = txn_kv_->create_txn(&txn);
3046
3
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
3
            std::string index_inverted_key = versioned::index_inverted_key(
3053
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
3
            versioned_remove_all(txn.get(), meta_key);
3055
3
            txn->remove(index_key);
3056
3
            txn->remove(index_inverted_key);
3057
3
            err = txn->commit();
3058
3
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
3
        }
3063
3064
9
        metrics_context.total_recycled_num = ++num_recycled;
3065
9
        metrics_context.report();
3066
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
9
        index_keys.push_back(k);
3068
9
        return 0;
3069
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
5
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
5
        ++num_scanned;
2969
5
        RecycleIndexPB index_pb;
2970
5
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
5
        int64_t current_time = ::time(nullptr);
2975
5
        if (current_time <
2976
5
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
5
        ++num_expired;
2980
        // decode index_id
2981
5
        auto k1 = k;
2982
5
        k1.remove_prefix(1);
2983
5
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
5
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
5
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
5
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
5
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
5
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
5
        std::unique_ptr<Transaction> txn;
2992
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
5
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
5
        std::string val;
2998
5
        err = txn->get(k, &val);
2999
5
        if (err ==
3000
5
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
5
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
5
        index_pb.Clear();
3009
5
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
5
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
4
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
4
            txn->put(k, index_pb.SerializeAsString());
3016
4
            err = txn->commit();
3017
4
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
4
        }
3022
5
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
3
            metrics_context.total_recycled_num = ++num_recycled;
3030
3
            metrics_context.report();
3031
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
3
            return 0;
3033
3
        }
3034
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
1
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
1
            std::unique_ptr<Transaction> txn;
3045
1
            err = txn_kv_->create_txn(&txn);
3046
1
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
1
            std::string index_inverted_key = versioned::index_inverted_key(
3053
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
1
            versioned_remove_all(txn.get(), meta_key);
3055
1
            txn->remove(index_key);
3056
1
            txn->remove(index_inverted_key);
3057
1
            err = txn->commit();
3058
1
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
1
        }
3063
3064
1
        metrics_context.total_recycled_num = ++num_recycled;
3065
1
        metrics_context.report();
3066
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
1
        index_keys.push_back(k);
3068
1
        return 0;
3069
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
13
        ++num_scanned;
2969
13
        RecycleIndexPB index_pb;
2970
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
13
        int64_t current_time = ::time(nullptr);
2975
13
        if (current_time <
2976
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
13
        ++num_expired;
2980
        // decode index_id
2981
13
        auto k1 = k;
2982
13
        k1.remove_prefix(1);
2983
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
13
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
13
        std::unique_ptr<Transaction> txn;
2992
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
13
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
13
        std::string val;
2998
13
        err = txn->get(k, &val);
2999
13
        if (err ==
3000
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
13
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
13
        index_pb.Clear();
3009
13
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
12
            txn->put(k, index_pb.SerializeAsString());
3016
12
            err = txn->commit();
3017
12
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
12
        }
3022
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
5
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
5
            metrics_context.total_recycled_num = ++num_recycled;
3030
5
            metrics_context.report();
3031
5
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
5
            return 0;
3033
5
        }
3034
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
0
            LOG_WARNING("failed to recycle tablets under index")
3036
0
                    .tag("table_id", index_pb.table_id())
3037
0
                    .tag("instance_id", instance_id_)
3038
0
                    .tag("index_id", index_id);
3039
0
            return -1;
3040
0
        }
3041
3042
8
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
2
            std::unique_ptr<Transaction> txn;
3045
2
            err = txn_kv_->create_txn(&txn);
3046
2
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
2
            std::string index_inverted_key = versioned::index_inverted_key(
3053
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
2
            versioned_remove_all(txn.get(), meta_key);
3055
2
            txn->remove(index_key);
3056
2
            txn->remove(index_inverted_key);
3057
2
            err = txn->commit();
3058
2
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
2
        }
3063
3064
8
        metrics_context.total_recycled_num = ++num_recycled;
3065
8
        metrics_context.report();
3066
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
8
        index_keys.push_back(k);
3068
8
        return 0;
3069
8
    };
3070
3071
25
    auto loop_done = [&index_keys, this]() -> int {
3072
13
        if (index_keys.empty()) return 0;
3073
5
        DORIS_CLOUD_DEFER {
3074
5
            index_keys.clear();
3075
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
5
        return 0;
3081
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
4
    auto loop_done = [&index_keys, this]() -> int {
3072
4
        if (index_keys.empty()) return 0;
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
3076
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
1
        return 0;
3081
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
9
    auto loop_done = [&index_keys, this]() -> int {
3072
9
        if (index_keys.empty()) return 0;
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
4
        return 0;
3081
4
    };
3082
3083
25
    if (config::enable_recycler_stats_metrics) {
3084
0
        scan_and_statistics_indexes();
3085
0
    }
3086
    // recycle_func and loop_done for scan and recycle
3087
25
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3088
25
}
3089
3090
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3091
8.25k
                             int64_t tablet_id) {
3092
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3093
3094
8.25k
    std::unique_ptr<Transaction> txn;
3095
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3096
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3097
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3098
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3099
0
        return false;
3100
0
    }
3101
3102
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3103
8.25k
    std::string tablet_idx_val;
3104
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3105
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3106
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3107
0
                     << " tablet_id=" << tablet_id << " err=" << err
3108
0
                     << " key=" << hex(tablet_idx_key);
3109
0
        return false;
3110
0
    }
3111
3112
8.25k
    TabletIndexPB tablet_idx_pb;
3113
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3114
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3115
0
                     << " tablet_id=" << tablet_id;
3116
0
        return false;
3117
0
    }
3118
3119
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3120
        // In the previous version, the db_id was not set in the index_pb.
3121
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3122
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3123
0
                  << " instance_id=" << instance_id
3124
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3125
0
        return true;
3126
0
    }
3127
3128
8.25k
    std::string ver_val;
3129
8.25k
    std::string ver_key =
3130
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3131
8.25k
                                   tablet_idx_pb.partition_id()});
3132
8.25k
    err = txn->get(ver_key, &ver_val);
3133
3134
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3135
214
        LOG(INFO) << ""
3136
214
                     "partition version not found, instance_id="
3137
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3138
214
                  << " table_id=" << tablet_idx_pb.table_id()
3139
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3140
214
                  << " key=" << hex(ver_key);
3141
214
        return true;
3142
214
    }
3143
3144
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3145
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3146
0
                     << " db_id=" << tablet_idx_pb.db_id()
3147
0
                     << " table_id=" << tablet_idx_pb.table_id()
3148
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3149
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3150
0
        return false;
3151
0
    }
3152
3153
8.03k
    VersionPB version_pb;
3154
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3155
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3156
0
                     << " db_id=" << tablet_idx_pb.db_id()
3157
0
                     << " table_id=" << tablet_idx_pb.table_id()
3158
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3159
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3160
0
        return false;
3161
0
    }
3162
3163
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3164
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3165
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3166
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3167
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3168
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3169
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3170
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3171
4.00k
                     << " key=" << hex(ver_key);
3172
4.00k
        return false;
3173
4.00k
    }
3174
4.03k
    return true;
3175
8.03k
}
3176
3177
20
int InstanceRecycler::recycle_partitions() {
3178
20
    const std::string task_name = "recycle_partitions";
3179
20
    int64_t num_scanned = 0;
3180
20
    int64_t num_expired = 0;
3181
20
    int64_t num_recycled = 0;
3182
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3183
3184
20
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3185
20
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3186
20
    std::string part_key0;
3187
20
    std::string part_key1;
3188
20
    recycle_partition_key(part_key_info0, &part_key0);
3189
20
    recycle_partition_key(part_key_info1, &part_key1);
3190
3191
20
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3192
3193
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3194
20
    register_recycle_task(task_name, start_time);
3195
3196
20
    DORIS_CLOUD_DEFER {
3197
20
        unregister_recycle_task(task_name);
3198
20
        int64_t cost =
3199
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
20
        metrics_context.finish_report();
3201
20
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
20
                .tag("instance_id", instance_id_)
3203
20
                .tag("num_scanned", num_scanned)
3204
20
                .tag("num_expired", num_expired)
3205
20
                .tag("num_recycled", num_recycled);
3206
20
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
2
    DORIS_CLOUD_DEFER {
3197
2
        unregister_recycle_task(task_name);
3198
2
        int64_t cost =
3199
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
2
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
2
                .tag("instance_id", instance_id_)
3203
2
                .tag("num_scanned", num_scanned)
3204
2
                .tag("num_expired", num_expired)
3205
2
                .tag("num_recycled", num_recycled);
3206
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
18
    DORIS_CLOUD_DEFER {
3197
18
        unregister_recycle_task(task_name);
3198
18
        int64_t cost =
3199
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
18
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
18
                .tag("instance_id", instance_id_)
3203
18
                .tag("num_scanned", num_scanned)
3204
18
                .tag("num_expired", num_expired)
3205
18
                .tag("num_recycled", num_recycled);
3206
18
    };
3207
3208
20
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3209
3210
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3211
20
    std::vector<std::string_view> partition_keys;
3212
20
    std::vector<std::string> partition_version_keys;
3213
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
13
        ++num_scanned;
3215
13
        RecyclePartitionPB part_pb;
3216
13
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
13
        int64_t current_time = ::time(nullptr);
3221
13
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
13
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
13
        ++num_expired;
3226
        // decode partition_id
3227
13
        auto k1 = k;
3228
13
        k1.remove_prefix(1);
3229
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
13
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
13
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
13
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
13
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
13
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
13
        std::unique_ptr<Transaction> txn;
3238
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
13
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
13
        std::string val;
3244
13
        err = txn->get(k, &val);
3245
13
        if (err ==
3246
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
13
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
13
        part_pb.Clear();
3255
13
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
13
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
11
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
11
            txn->put(k, part_pb.SerializeAsString());
3263
11
            err = txn->commit();
3264
11
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
11
        }
3269
3270
13
        int ret = 0;
3271
37
        for (int64_t index_id : part_pb.index_id()) {
3272
37
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
37
        }
3281
13
        if (ret == 0 && part_pb.has_db_id() &&
3282
13
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
12
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
13
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
12
            std::unique_ptr<Transaction> txn;
3293
12
            err = txn_kv_->create_txn(&txn);
3294
12
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
12
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
12
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
12
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
12
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
12
            std::string partition_version_key =
3303
12
                    versioned::partition_version_key({instance_id_, partition_id});
3304
12
            versioned_remove_all(txn.get(), meta_key);
3305
12
            txn->remove(index_key);
3306
12
            txn->remove(inverted_index_key);
3307
12
            versioned_remove_all(txn.get(), partition_version_key);
3308
12
            err = txn->commit();
3309
12
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
12
        }
3314
3315
13
        if (ret == 0) {
3316
12
            ++num_recycled;
3317
12
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
12
            partition_keys.push_back(k);
3319
12
            if (part_pb.db_id() > 0) {
3320
12
                partition_version_keys.push_back(partition_version_key(
3321
12
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
12
            }
3323
12
            metrics_context.total_recycled_num = num_recycled;
3324
12
            metrics_context.report();
3325
12
        }
3326
13
        return ret;
3327
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
2
        ++num_scanned;
3215
2
        RecyclePartitionPB part_pb;
3216
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
2
        int64_t current_time = ::time(nullptr);
3221
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
2
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
2
        ++num_expired;
3226
        // decode partition_id
3227
2
        auto k1 = k;
3228
2
        k1.remove_prefix(1);
3229
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
2
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
2
        std::unique_ptr<Transaction> txn;
3238
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
2
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
2
        std::string val;
3244
2
        err = txn->get(k, &val);
3245
2
        if (err ==
3246
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
2
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
2
        part_pb.Clear();
3255
2
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
1
            txn->put(k, part_pb.SerializeAsString());
3263
1
            err = txn->commit();
3264
1
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
1
        }
3269
3270
2
        int ret = 0;
3271
2
        for (int64_t index_id : part_pb.index_id()) {
3272
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
2
        }
3281
2
        if (ret == 0 && part_pb.has_db_id() &&
3282
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
2
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
1
            std::unique_ptr<Transaction> txn;
3293
1
            err = txn_kv_->create_txn(&txn);
3294
1
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
1
            std::string partition_version_key =
3303
1
                    versioned::partition_version_key({instance_id_, partition_id});
3304
1
            versioned_remove_all(txn.get(), meta_key);
3305
1
            txn->remove(index_key);
3306
1
            txn->remove(inverted_index_key);
3307
1
            versioned_remove_all(txn.get(), partition_version_key);
3308
1
            err = txn->commit();
3309
1
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
1
        }
3314
3315
2
        if (ret == 0) {
3316
1
            ++num_recycled;
3317
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
1
            partition_keys.push_back(k);
3319
1
            if (part_pb.db_id() > 0) {
3320
1
                partition_version_keys.push_back(partition_version_key(
3321
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
1
            }
3323
1
            metrics_context.total_recycled_num = num_recycled;
3324
1
            metrics_context.report();
3325
1
        }
3326
2
        return ret;
3327
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
11
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
11
        ++num_scanned;
3215
11
        RecyclePartitionPB part_pb;
3216
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
11
        int64_t current_time = ::time(nullptr);
3221
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
11
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
11
        ++num_expired;
3226
        // decode partition_id
3227
11
        auto k1 = k;
3228
11
        k1.remove_prefix(1);
3229
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
11
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
11
        std::unique_ptr<Transaction> txn;
3238
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
11
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
11
        std::string val;
3244
11
        err = txn->get(k, &val);
3245
11
        if (err ==
3246
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
11
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
11
        part_pb.Clear();
3255
11
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
10
            txn->put(k, part_pb.SerializeAsString());
3263
10
            err = txn->commit();
3264
10
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
10
        }
3269
3270
11
        int ret = 0;
3271
35
        for (int64_t index_id : part_pb.index_id()) {
3272
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
0
                LOG_WARNING("failed to recycle tablets under partition")
3274
0
                        .tag("table_id", part_pb.table_id())
3275
0
                        .tag("instance_id", instance_id_)
3276
0
                        .tag("index_id", index_id)
3277
0
                        .tag("partition_id", partition_id);
3278
0
                ret = -1;
3279
0
            }
3280
35
        }
3281
11
        if (ret == 0 && part_pb.has_db_id() &&
3282
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
11
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
11
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
11
            std::unique_ptr<Transaction> txn;
3293
11
            err = txn_kv_->create_txn(&txn);
3294
11
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
11
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
11
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
11
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
11
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
11
            std::string partition_version_key =
3303
11
                    versioned::partition_version_key({instance_id_, partition_id});
3304
11
            versioned_remove_all(txn.get(), meta_key);
3305
11
            txn->remove(index_key);
3306
11
            txn->remove(inverted_index_key);
3307
11
            versioned_remove_all(txn.get(), partition_version_key);
3308
11
            err = txn->commit();
3309
11
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
11
        }
3314
3315
11
        if (ret == 0) {
3316
11
            ++num_recycled;
3317
11
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
11
            partition_keys.push_back(k);
3319
11
            if (part_pb.db_id() > 0) {
3320
11
                partition_version_keys.push_back(partition_version_key(
3321
11
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
11
            }
3323
11
            metrics_context.total_recycled_num = num_recycled;
3324
11
            metrics_context.report();
3325
11
        }
3326
11
        return ret;
3327
11
    };
3328
3329
20
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
9
        if (partition_keys.empty()) return 0;
3331
8
        DORIS_CLOUD_DEFER {
3332
8
            partition_keys.clear();
3333
8
            partition_version_keys.clear();
3334
8
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
8
        std::unique_ptr<Transaction> txn;
3336
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
8
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
12
        for (auto& k : partition_keys) {
3342
12
            txn->remove(k);
3343
12
        }
3344
12
        for (auto& k : partition_version_keys) {
3345
12
            txn->remove(k);
3346
12
        }
3347
8
        err = txn->commit();
3348
8
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
8
        return 0;
3354
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
2
        if (partition_keys.empty()) return 0;
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
3335
1
        std::unique_ptr<Transaction> txn;
3336
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
1
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
1
        for (auto& k : partition_keys) {
3342
1
            txn->remove(k);
3343
1
        }
3344
1
        for (auto& k : partition_version_keys) {
3345
1
            txn->remove(k);
3346
1
        }
3347
1
        err = txn->commit();
3348
1
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
1
        return 0;
3354
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
7
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
7
        if (partition_keys.empty()) return 0;
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
7
        std::unique_ptr<Transaction> txn;
3336
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
7
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
11
        for (auto& k : partition_keys) {
3342
11
            txn->remove(k);
3343
11
        }
3344
11
        for (auto& k : partition_version_keys) {
3345
11
            txn->remove(k);
3346
11
        }
3347
7
        err = txn->commit();
3348
7
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
7
        return 0;
3354
7
    };
3355
3356
20
    if (config::enable_recycler_stats_metrics) {
3357
0
        scan_and_statistics_partitions();
3358
0
    }
3359
    // recycle_func and loop_done for scan and recycle
3360
20
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3361
20
}
3362
3363
14
int InstanceRecycler::recycle_versions() {
3364
14
    if (should_recycle_versioned_keys()) {
3365
2
        return recycle_orphan_partitions();
3366
2
    }
3367
3368
12
    int64_t num_scanned = 0;
3369
12
    int64_t num_recycled = 0;
3370
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3371
3372
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3373
3374
12
    auto start_time = steady_clock::now();
3375
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
3384
3385
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3386
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3387
12
    int64_t last_scanned_table_id = 0;
3388
12
    bool is_recycled = false; // Is last scanned kv recycled
3389
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3390
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3390
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
3453
3454
12
    if (config::enable_recycler_stats_metrics) {
3455
0
        scan_and_statistics_versions();
3456
0
    }
3457
    // recycle_func and loop_done for scan and recycle
3458
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3459
14
}
3460
3461
3
int InstanceRecycler::recycle_orphan_partitions() {
3462
3
    int64_t num_scanned = 0;
3463
3
    int64_t num_recycled = 0;
3464
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3465
3466
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3467
3
            .tag("instance_id", instance_id_);
3468
3469
3
    auto start_time = steady_clock::now();
3470
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
3479
3480
3
    bool is_empty_table = false;        // whether the table has no indexes
3481
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3482
3
    int64_t current_table_id = 0;       // current scanning table id
3483
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3484
3
                         &current_table_id, &is_table_kvs_recycled,
3485
3
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
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
3485
2
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
1
    };
3563
3564
    // recycle_func and loop_done for scan and recycle
3565
3
    return scan_and_recycle(
3566
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3567
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3568
3
            std::move(recycle_func));
3569
3
}
3570
3571
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3572
                                      RecyclerMetricsContext& metrics_context,
3573
56
                                      int64_t partition_id) {
3574
56
    bool is_multi_version =
3575
56
            instance_info_.has_multi_version_status() &&
3576
56
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3577
56
    int64_t num_scanned = 0;
3578
56
    std::atomic_long num_recycled = 0;
3579
3580
56
    std::string tablet_key_begin, tablet_key_end;
3581
56
    std::string stats_key_begin, stats_key_end;
3582
56
    std::string job_key_begin, job_key_end;
3583
3584
56
    std::string tablet_belongs;
3585
56
    if (partition_id > 0) {
3586
        // recycle tablets in a partition belonging to the index
3587
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3588
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3589
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3590
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3591
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3592
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3593
37
        tablet_belongs = "partition";
3594
37
    } else {
3595
        // recycle tablets in the index
3596
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3597
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3598
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3599
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3600
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3601
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3602
19
        tablet_belongs = "index";
3603
19
    }
3604
3605
56
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3606
56
            .tag("table_id", table_id)
3607
56
            .tag("index_id", index_id)
3608
56
            .tag("partition_id", partition_id);
3609
3610
56
    auto start_time = steady_clock::now();
3611
3612
56
    DORIS_CLOUD_DEFER {
3613
56
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
56
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
56
                .tag("instance_id", instance_id_)
3616
56
                .tag("table_id", table_id)
3617
56
                .tag("index_id", index_id)
3618
56
                .tag("partition_id", partition_id)
3619
56
                .tag("num_scanned", num_scanned)
3620
56
                .tag("num_recycled", num_recycled);
3621
56
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3612
4
    DORIS_CLOUD_DEFER {
3613
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
4
                .tag("instance_id", instance_id_)
3616
4
                .tag("table_id", table_id)
3617
4
                .tag("index_id", index_id)
3618
4
                .tag("partition_id", partition_id)
3619
4
                .tag("num_scanned", num_scanned)
3620
4
                .tag("num_recycled", num_recycled);
3621
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3612
52
    DORIS_CLOUD_DEFER {
3613
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
52
                .tag("instance_id", instance_id_)
3616
52
                .tag("table_id", table_id)
3617
52
                .tag("index_id", index_id)
3618
52
                .tag("partition_id", partition_id)
3619
52
                .tag("num_scanned", num_scanned)
3620
52
                .tag("num_recycled", num_recycled);
3621
52
    };
3622
3623
    // The tablet key and id which have been recycled.
3624
56
    struct TabletInfo {
3625
56
        std::string_view tablet_meta_key;
3626
56
        int64_t tablet_id;
3627
56
    };
3628
56
    SyncExecutor<TabletInfo> sync_executor(
3629
56
            _thread_pool_group.recycle_tablet_pool,
3630
56
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3631
56
                        index_id, partition_id),
3632
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3632
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3632
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3633
3634
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3635
56
    std::vector<std::string> init_rs_keys;
3636
56
    bool has_failure = false;
3637
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
8.25k
        ++num_scanned;
3639
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
4.00k
            has_failure = true;
3651
4.00k
            return -1;
3652
4.00k
        }
3653
3654
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
4.25k
        sync_executor.add(
3656
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
2
                        LOG_WARNING("failed to recycle tablet")
3659
2
                                .tag("instance_id", instance_id_)
3660
2
                                .tag("tablet_id", tid);
3661
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
2
                    }
3663
4.25k
                    ++num_recycled;
3664
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3656
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
0
                        LOG_WARNING("failed to recycle tablet")
3659
0
                                .tag("instance_id", instance_id_)
3660
0
                                .tag("tablet_id", tid);
3661
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
0
                    }
3663
4.00k
                    ++num_recycled;
3664
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3656
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
2
                        LOG_WARNING("failed to recycle tablet")
3659
2
                                .tag("instance_id", instance_id_)
3660
2
                                .tag("tablet_id", tid);
3661
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
2
                    }
3663
248
                    ++num_recycled;
3664
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
250
                });
3667
4.25k
        return 0;
3668
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3637
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
8.00k
        ++num_scanned;
3639
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
4.00k
            has_failure = true;
3651
4.00k
            return -1;
3652
4.00k
        }
3653
3654
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
4.00k
        sync_executor.add(
3656
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
4.00k
                        LOG_WARNING("failed to recycle tablet")
3659
4.00k
                                .tag("instance_id", instance_id_)
3660
4.00k
                                .tag("tablet_id", tid);
3661
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
4.00k
                    }
3663
4.00k
                    ++num_recycled;
3664
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.00k
                });
3667
4.00k
        return 0;
3668
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3637
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
251
        ++num_scanned;
3639
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
1
            has_failure = true;
3651
1
            return -1;
3652
1
        }
3653
3654
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
250
        sync_executor.add(
3656
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
250
                        LOG_WARNING("failed to recycle tablet")
3659
250
                                .tag("instance_id", instance_id_)
3660
250
                                .tag("tablet_id", tid);
3661
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
250
                    }
3663
250
                    ++num_recycled;
3664
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
250
                });
3667
250
        return 0;
3668
250
    };
3669
3670
56
    auto loop_done = [&, this]() -> int {
3671
52
        int ret = 0;
3672
52
        bool finished = true;
3673
52
        bool has_empty_key = false;
3674
52
        DORIS_CLOUD_DEFER {
3675
52
            init_rs_keys.clear();
3676
52
            has_failure = false;
3677
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3674
4
        DORIS_CLOUD_DEFER {
3675
4
            init_rs_keys.clear();
3676
4
            has_failure = false;
3677
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3674
48
        DORIS_CLOUD_DEFER {
3675
48
            init_rs_keys.clear();
3676
48
            has_failure = false;
3677
48
        };
3678
52
        auto tablets_info = sync_executor.when_all(&finished);
3679
52
        if (!finished) {
3680
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
1
            return -1;
3682
1
        }
3683
3684
51
        size_t size_before_erase = tablets_info.size();
3685
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
3685
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
3685
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
51
        if (tablets_info.empty()) {
3687
2
            return size_before_erase == 0 ? 0 : -1;
3688
49
        } else if (size_before_erase != tablets_info.size()) {
3689
1
            has_empty_key = true;
3690
1
        }
3691
3692
49
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3694
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3694
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
958
        });
3697
49
        std::unique_ptr<Transaction> txn;
3698
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
49
        std::string tablet_key_end;
3703
49
        if (!tablets_info.empty()) {
3704
49
            if (!has_empty_key && !has_failure) {
3705
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
47
            } else {
3708
8
                for (auto& tablet_info : tablets_info) {
3709
8
                    txn->remove(tablet_info.tablet_meta_key);
3710
8
                }
3711
2
            }
3712
49
        }
3713
49
        if (is_multi_version) {
3714
6
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
6
                LOG_INFO("remove versioned tablet compact stats key")
3718
6
                        .tag("compact_stats_key", hex(k));
3719
6
                versioned_remove_all(txn.get(), k);
3720
6
            }
3721
6
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
6
                versioned_remove_all(txn.get(), k);
3726
6
            }
3727
6
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
6
                versioned_remove_all(txn.get(), k);
3732
6
            }
3733
5
        }
3734
4.25k
        for (auto& tablet_info : tablets_info) {
3735
4.25k
            std::string k;
3736
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
4.25k
            txn->remove(k);
3738
4.25k
        }
3739
4.25k
        for (auto& tablet_info : tablets_info) {
3740
4.25k
            std::string k;
3741
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
4.25k
            txn->remove(k);
3743
4.25k
        }
3744
49
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
49
        return ret;
3753
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3670
4
    auto loop_done = [&, this]() -> int {
3671
4
        int ret = 0;
3672
4
        bool finished = true;
3673
4
        bool has_empty_key = false;
3674
4
        DORIS_CLOUD_DEFER {
3675
4
            init_rs_keys.clear();
3676
4
            has_failure = false;
3677
4
        };
3678
4
        auto tablets_info = sync_executor.when_all(&finished);
3679
4
        if (!finished) {
3680
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
0
            return -1;
3682
0
        }
3683
3684
4
        size_t size_before_erase = tablets_info.size();
3685
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
4
        if (tablets_info.empty()) {
3687
2
            return size_before_erase == 0 ? 0 : -1;
3688
2
        } else if (size_before_erase != tablets_info.size()) {
3689
0
            has_empty_key = true;
3690
0
        }
3691
3692
2
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
2
        });
3697
2
        std::unique_ptr<Transaction> txn;
3698
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
2
        std::string tablet_key_end;
3703
2
        if (!tablets_info.empty()) {
3704
2
            if (!has_empty_key && !has_failure) {
3705
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
2
            } else {
3708
0
                for (auto& tablet_info : tablets_info) {
3709
0
                    txn->remove(tablet_info.tablet_meta_key);
3710
0
                }
3711
0
            }
3712
2
        }
3713
2
        if (is_multi_version) {
3714
0
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
0
                LOG_INFO("remove versioned tablet compact stats key")
3718
0
                        .tag("compact_stats_key", hex(k));
3719
0
                versioned_remove_all(txn.get(), k);
3720
0
            }
3721
0
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
0
                versioned_remove_all(txn.get(), k);
3726
0
            }
3727
0
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
0
                versioned_remove_all(txn.get(), k);
3732
0
            }
3733
0
        }
3734
4.00k
        for (auto& tablet_info : tablets_info) {
3735
4.00k
            std::string k;
3736
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
4.00k
            txn->remove(k);
3738
4.00k
        }
3739
4.00k
        for (auto& tablet_info : tablets_info) {
3740
4.00k
            std::string k;
3741
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
4.00k
            txn->remove(k);
3743
4.00k
        }
3744
2
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
2
        return ret;
3753
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3670
48
    auto loop_done = [&, this]() -> int {
3671
48
        int ret = 0;
3672
48
        bool finished = true;
3673
48
        bool has_empty_key = false;
3674
48
        DORIS_CLOUD_DEFER {
3675
48
            init_rs_keys.clear();
3676
48
            has_failure = false;
3677
48
        };
3678
48
        auto tablets_info = sync_executor.when_all(&finished);
3679
48
        if (!finished) {
3680
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
1
            return -1;
3682
1
        }
3683
3684
47
        size_t size_before_erase = tablets_info.size();
3685
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
47
        if (tablets_info.empty()) {
3687
0
            return size_before_erase == 0 ? 0 : -1;
3688
47
        } else if (size_before_erase != tablets_info.size()) {
3689
1
            has_empty_key = true;
3690
1
        }
3691
3692
47
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
47
        });
3697
47
        std::unique_ptr<Transaction> txn;
3698
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
47
        std::string tablet_key_end;
3703
47
        if (!tablets_info.empty()) {
3704
47
            if (!has_empty_key && !has_failure) {
3705
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
45
            } else {
3708
8
                for (auto& tablet_info : tablets_info) {
3709
8
                    txn->remove(tablet_info.tablet_meta_key);
3710
8
                }
3711
2
            }
3712
47
        }
3713
47
        if (is_multi_version) {
3714
6
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
6
                LOG_INFO("remove versioned tablet compact stats key")
3718
6
                        .tag("compact_stats_key", hex(k));
3719
6
                versioned_remove_all(txn.get(), k);
3720
6
            }
3721
6
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
6
                versioned_remove_all(txn.get(), k);
3726
6
            }
3727
6
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
6
                versioned_remove_all(txn.get(), k);
3732
6
            }
3733
5
        }
3734
248
        for (auto& tablet_info : tablets_info) {
3735
248
            std::string k;
3736
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
248
            txn->remove(k);
3738
248
        }
3739
248
        for (auto& tablet_info : tablets_info) {
3740
248
            std::string k;
3741
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
248
            txn->remove(k);
3743
248
        }
3744
47
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
47
        return ret;
3753
47
    };
3754
3755
56
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3756
56
                               std::move(loop_done));
3757
56
    if (ret != 0) {
3758
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3759
5
        return ret;
3760
5
    }
3761
3762
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3763
51
    std::unique_ptr<Transaction> txn;
3764
51
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3765
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3766
0
        return -1;
3767
0
    }
3768
51
    txn->remove(stats_key_begin, stats_key_end);
3769
51
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3770
51
                 << " end=" << hex(stats_key_end);
3771
51
    txn->remove(job_key_begin, job_key_end);
3772
51
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3773
51
    std::string schema_key_begin, schema_key_end;
3774
51
    std::string schema_dict_key;
3775
51
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3776
51
    if (partition_id <= 0) {
3777
        // Delete schema kv of this index
3778
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3779
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3780
15
        txn->remove(schema_key_begin, schema_key_end);
3781
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3782
15
                     << " end=" << hex(schema_key_end);
3783
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3784
15
        txn->remove(schema_dict_key);
3785
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3786
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3787
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3788
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3789
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3790
15
                     << " end=" << hex(versioned_schema_key_end);
3791
15
    }
3792
3793
51
    TxnErrorCode err = txn->commit();
3794
51
    if (err != TxnErrorCode::TXN_OK) {
3795
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3796
0
                     << " err=" << err;
3797
0
        return -1;
3798
0
    }
3799
3800
51
    return ret;
3801
51
}
3802
3803
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3804
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3805
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3806
5.61k
    if (num_segments <= 0) return 0;
3807
3808
5.61k
    std::vector<std::string> file_paths;
3809
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3810
0
        return -1;
3811
0
    }
3812
3813
    // Process inverted indexes
3814
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3815
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3816
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3817
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3818
5.61k
    bool delete_rowset_data_by_prefix = false;
3819
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3820
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3821
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3822
0
        delete_rowset_data_by_prefix = true;
3823
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3824
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3825
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3826
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3827
10.0k
            }
3828
10.0k
        }
3829
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3830
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3831
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3832
2.00k
        }
3833
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3834
        // schema version and index id are not found, delete rowset data by prefix directly.
3835
0
        delete_rowset_data_by_prefix = true;
3836
809
    } else {
3837
        // otherwise, try to get schema kv
3838
809
        InvertedIndexInfo index_info;
3839
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3840
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3841
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3842
809
                                 &inverted_index_get_ret);
3843
809
        if (inverted_index_get_ret == 0) {
3844
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3845
809
                index_format = index_info.first;
3846
809
            }
3847
809
            index_ids = index_info.second;
3848
809
        } else if (inverted_index_get_ret == 1) {
3849
            // 1. Schema kv not found means tablet has been recycled
3850
            // Maybe some tablet recycle failed by some bugs
3851
            // We need to delete again to double check
3852
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3853
            // because we are uncertain about the inverted index information.
3854
            // If there are inverted indexes, some data might not be deleted,
3855
            // but this is acceptable as we have made our best effort to delete the data.
3856
0
            LOG_INFO(
3857
0
                    "delete rowset data schema kv not found, need to delete again to double "
3858
0
                    "check")
3859
0
                    .tag("instance_id", instance_id_)
3860
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3861
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3862
            // Currently index_ids is guaranteed to be empty,
3863
            // but we clear it again here as a safeguard against future code changes
3864
            // that might cause index_ids to no longer be empty
3865
0
            index_format = InvertedIndexStorageFormatPB::V2;
3866
0
            index_ids.clear();
3867
0
        } else {
3868
            // failed to get schema kv, delete rowset data by prefix directly.
3869
0
            delete_rowset_data_by_prefix = true;
3870
0
        }
3871
809
    }
3872
3873
5.61k
    if (delete_rowset_data_by_prefix) {
3874
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3875
0
                                  rs_meta_pb.rowset_id_v2());
3876
0
    }
3877
3878
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3879
5.61k
    if (it == accessor_map_.end()) {
3880
1.59k
        LOG_WARNING("instance has no such resource id")
3881
1.59k
                .tag("instance_id", instance_id_)
3882
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3883
1.59k
        return -1;
3884
1.59k
    }
3885
4.01k
    auto& accessor = it->second;
3886
3887
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3888
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3889
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3890
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3891
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3892
20.0k
                                         &file_paths);
3893
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3894
40.0k
            for (const auto& index_id : index_ids) {
3895
40.0k
                add_file_to_delete_if_not_packed(
3896
40.0k
                        rs_meta_pb,
3897
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3898
40.0k
                                               index_id.second),
3899
40.0k
                        &file_paths);
3900
40.0k
            }
3901
20.0k
        } else if (!index_ids.empty()) {
3902
2
            add_file_to_delete_if_not_packed(
3903
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3904
2
                    &file_paths);
3905
2
        }
3906
20.0k
    }
3907
3908
    // Process delete bitmap - check where it's stored.
3909
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3910
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3911
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3912
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3913
0
                .tag("instance_id", instance_id_)
3914
0
                .tag("tablet_id", tablet_id)
3915
0
                .tag("rowset_id", rowset_id);
3916
0
        return -1;
3917
0
    }
3918
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3919
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3920
2.00k
    }
3921
    // TODO(AlexYue): seems could do do batch
3922
4.01k
    return accessor->delete_files(file_paths);
3923
4.01k
}
3924
3925
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3926
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3927
62.6k
            .tag("instance_id", instance_id_)
3928
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3929
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3930
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3931
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3932
62.6k
    if (index_map.empty()) {
3933
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3934
62.6k
                .tag("instance_id", instance_id_)
3935
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3936
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3937
62.6k
        return 0;
3938
62.6k
    }
3939
3940
20
    struct PackedSmallFileInfo {
3941
20
        std::string small_file_path;
3942
20
    };
3943
20
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3944
20
    packed_file_updates.reserve(index_map.size());
3945
27
    for (const auto& [small_path, index_pb] : index_map) {
3946
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3947
0
            continue;
3948
0
        }
3949
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3950
27
                PackedSmallFileInfo {small_path});
3951
27
    }
3952
20
    if (packed_file_updates.empty()) {
3953
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3954
0
                .tag("instance_id", instance_id_)
3955
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3956
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3957
0
                .tag("index_map_size", index_map.size());
3958
0
        return 0;
3959
0
    }
3960
3961
20
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3962
20
    int ret = 0;
3963
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3964
24
        if (small_files.empty()) {
3965
0
            continue;
3966
0
        }
3967
3968
24
        bool success = false;
3969
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3970
24
            std::unique_ptr<Transaction> txn;
3971
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3972
24
            if (err != TxnErrorCode::TXN_OK) {
3973
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3974
0
                        .tag("instance_id", instance_id_)
3975
0
                        .tag("packed_file_path", packed_file_path)
3976
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3977
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3978
0
                        .tag("err", err);
3979
0
                ret = -1;
3980
0
                break;
3981
0
            }
3982
3983
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3984
24
            std::string packed_val;
3985
24
            err = txn->get(packed_key, &packed_val);
3986
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3987
0
                LOG_WARNING("packed file info not found when recycling rowset")
3988
0
                        .tag("instance_id", instance_id_)
3989
0
                        .tag("packed_file_path", packed_file_path)
3990
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3991
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3992
0
                        .tag("key", hex(packed_key))
3993
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3994
                // Skip this packed file entry and continue with others
3995
0
                success = true;
3996
0
                break;
3997
0
            }
3998
24
            if (err != TxnErrorCode::TXN_OK) {
3999
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
4000
0
                        .tag("instance_id", instance_id_)
4001
0
                        .tag("packed_file_path", packed_file_path)
4002
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4003
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4004
0
                        .tag("err", err);
4005
0
                ret = -1;
4006
0
                break;
4007
0
            }
4008
4009
24
            cloud::PackedFileInfoPB packed_info;
4010
24
            if (!packed_info.ParseFromString(packed_val)) {
4011
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
4012
0
                        .tag("instance_id", instance_id_)
4013
0
                        .tag("packed_file_path", packed_file_path)
4014
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4015
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4016
0
                ret = -1;
4017
0
                break;
4018
0
            }
4019
4020
24
            LOG_INFO("packed file update check")
4021
24
                    .tag("instance_id", instance_id_)
4022
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4023
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4024
24
                    .tag("merged_file_path", packed_file_path)
4025
24
                    .tag("requested_small_files", small_files.size())
4026
24
                    .tag("merge_entries", packed_info.slices_size());
4027
4028
24
            auto* small_file_entries = packed_info.mutable_slices();
4029
24
            int64_t changed_files = 0;
4030
24
            int64_t missing_entries = 0;
4031
24
            int64_t already_deleted = 0;
4032
27
            for (const auto& small_file_info : small_files) {
4033
27
                bool found = false;
4034
87
                for (auto& small_file_entry : *small_file_entries) {
4035
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
4036
27
                        if (!small_file_entry.deleted()) {
4037
27
                            small_file_entry.set_deleted(true);
4038
27
                            if (!small_file_entry.corrected()) {
4039
27
                                small_file_entry.set_corrected(true);
4040
27
                            }
4041
27
                            ++changed_files;
4042
27
                        } else {
4043
0
                            ++already_deleted;
4044
0
                        }
4045
27
                        found = true;
4046
27
                        break;
4047
27
                    }
4048
87
                }
4049
27
                if (!found) {
4050
0
                    ++missing_entries;
4051
0
                    LOG_WARNING("packed file info missing small file entry")
4052
0
                            .tag("instance_id", instance_id_)
4053
0
                            .tag("packed_file_path", packed_file_path)
4054
0
                            .tag("small_file_path", small_file_info.small_file_path)
4055
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4056
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4057
0
                }
4058
27
            }
4059
4060
24
            if (changed_files == 0) {
4061
0
                LOG_INFO("skip merge file update: no merge entries changed")
4062
0
                        .tag("instance_id", instance_id_)
4063
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4064
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4065
0
                        .tag("merged_file_path", packed_file_path)
4066
0
                        .tag("missing_entries", missing_entries)
4067
0
                        .tag("already_deleted", already_deleted)
4068
0
                        .tag("requested_small_files", small_files.size())
4069
0
                        .tag("merge_entries", packed_info.slices_size());
4070
0
                success = true;
4071
0
                break;
4072
0
            }
4073
4074
            // Calculate remaining files
4075
24
            int64_t left_file_count = 0;
4076
24
            int64_t left_file_bytes = 0;
4077
141
            for (const auto& small_file_entry : packed_info.slices()) {
4078
141
                if (!small_file_entry.deleted()) {
4079
57
                    ++left_file_count;
4080
57
                    left_file_bytes += small_file_entry.size();
4081
57
                }
4082
141
            }
4083
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4084
24
            packed_info.set_ref_cnt(left_file_count);
4085
24
            LOG_INFO("updated packed file reference info")
4086
24
                    .tag("instance_id", instance_id_)
4087
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4088
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4089
24
                    .tag("packed_file_path", packed_file_path)
4090
24
                    .tag("ref_cnt", left_file_count)
4091
24
                    .tag("left_file_bytes", left_file_bytes);
4092
4093
24
            if (left_file_count == 0) {
4094
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4095
7
            }
4096
4097
24
            std::string updated_val;
4098
24
            if (!packed_info.SerializeToString(&updated_val)) {
4099
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4100
0
                        .tag("instance_id", instance_id_)
4101
0
                        .tag("packed_file_path", packed_file_path)
4102
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4103
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4104
0
                ret = -1;
4105
0
                break;
4106
0
            }
4107
4108
24
            txn->put(packed_key, updated_val);
4109
24
            err = txn->commit();
4110
24
            if (err == TxnErrorCode::TXN_OK) {
4111
24
                success = true;
4112
24
                if (left_file_count == 0) {
4113
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4114
7
                            .tag("instance_id", instance_id_)
4115
7
                            .tag("packed_file_path", packed_file_path);
4116
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4117
0
                        ret = -1;
4118
0
                    }
4119
7
                }
4120
24
                break;
4121
24
            }
4122
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4123
0
                if (attempt >= max_retry_times) {
4124
0
                    LOG_WARNING("packed file info update conflict after max retry")
4125
0
                            .tag("instance_id", instance_id_)
4126
0
                            .tag("packed_file_path", packed_file_path)
4127
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4128
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4129
0
                            .tag("changed_files", changed_files)
4130
0
                            .tag("attempt", attempt);
4131
0
                    ret = -1;
4132
0
                    break;
4133
0
                }
4134
0
                LOG_WARNING("packed file info update conflict, retrying")
4135
0
                        .tag("instance_id", instance_id_)
4136
0
                        .tag("packed_file_path", packed_file_path)
4137
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4138
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4139
0
                        .tag("changed_files", changed_files)
4140
0
                        .tag("attempt", attempt);
4141
0
                sleep_for_packed_file_retry();
4142
0
                continue;
4143
0
            }
4144
4145
0
            LOG_WARNING("failed to commit packed file info update")
4146
0
                    .tag("instance_id", instance_id_)
4147
0
                    .tag("packed_file_path", packed_file_path)
4148
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4149
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4150
0
                    .tag("err", err)
4151
0
                    .tag("changed_files", changed_files);
4152
0
            ret = -1;
4153
0
            break;
4154
0
        }
4155
4156
24
        if (!success) {
4157
0
            ret = -1;
4158
0
        }
4159
24
    }
4160
4161
20
    return ret;
4162
20
}
4163
4164
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4165
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
4166
61.0k
        std::vector<std::string>* keys) {
4167
61.0k
    if (out_storage_type) {
4168
58.5k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4169
58.5k
    }
4170
4171
    // Get delete bitmap storage info from FDB
4172
61.0k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4173
61.0k
    std::unique_ptr<Transaction> txn;
4174
61.0k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4175
61.0k
    if (err != TxnErrorCode::TXN_OK) {
4176
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4177
0
                .tag("instance_id", instance_id_)
4178
0
                .tag("tablet_id", tablet_id)
4179
0
                .tag("rowset_id", rowset_id)
4180
0
                .tag("err", err);
4181
0
        return -1;
4182
0
    }
4183
4184
61.0k
    ValueBuf dbm_val;
4185
61.0k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4186
61.0k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4187
        // No delete bitmap for this rowset, nothing to do
4188
6.23k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4189
6.23k
                .tag("instance_id", instance_id_)
4190
6.23k
                .tag("tablet_id", tablet_id)
4191
6.23k
                .tag("rowset_id", rowset_id);
4192
6.23k
        return 0;
4193
6.23k
    }
4194
54.8k
    if (err != TxnErrorCode::TXN_OK) {
4195
0
        LOG_WARNING("failed to get delete bitmap storage")
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
54.8k
    if (keys) {
4204
1.55k
        for (auto& key : dbm_val.keys()) {
4205
1.55k
            keys->push_back(std::move(key));
4206
1.55k
        }
4207
1.55k
    }
4208
4209
54.8k
    DeleteBitmapStoragePB storage;
4210
54.8k
    if (!dbm_val.to_pb(&storage)) {
4211
0
        LOG_WARNING("failed to parse delete bitmap storage")
4212
0
                .tag("instance_id", instance_id_)
4213
0
                .tag("tablet_id", tablet_id)
4214
0
                .tag("rowset_id", rowset_id);
4215
0
        return -1;
4216
0
    }
4217
4218
54.8k
    if (storage.store_in_fdb()) {
4219
1
        if (out_storage_type) {
4220
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4221
1
        }
4222
1
        return 0;
4223
1
    }
4224
4225
    // Check if delete bitmap is stored in standalone file.
4226
54.8k
    if (!storage.has_packed_slice_location() ||
4227
54.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4228
54.8k
        if (out_storage_type) {
4229
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4230
53.5k
        }
4231
54.8k
        return 0;
4232
54.8k
    }
4233
4234
18.4E
    if (out_storage_type) {
4235
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4236
0
    }
4237
4238
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4239
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4240
4241
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4242
18.4E
            .tag("instance_id", instance_id_)
4243
18.4E
            .tag("tablet_id", tablet_id)
4244
18.4E
            .tag("rowset_id", rowset_id)
4245
18.4E
            .tag("packed_file_path", packed_file_path);
4246
4247
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4248
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4249
1
        std::unique_ptr<Transaction> update_txn;
4250
1
        err = txn_kv_->create_txn(&update_txn);
4251
1
        if (err != TxnErrorCode::TXN_OK) {
4252
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4253
0
                    .tag("instance_id", instance_id_)
4254
0
                    .tag("tablet_id", tablet_id)
4255
0
                    .tag("rowset_id", rowset_id)
4256
0
                    .tag("err", err);
4257
0
            return -1;
4258
0
        }
4259
4260
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4261
1
        std::string packed_val;
4262
1
        err = update_txn->get(packed_key, &packed_val);
4263
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4264
0
            LOG_WARNING("packed file info not found for delete bitmap")
4265
0
                    .tag("instance_id", instance_id_)
4266
0
                    .tag("tablet_id", tablet_id)
4267
0
                    .tag("rowset_id", rowset_id)
4268
0
                    .tag("packed_file_path", packed_file_path);
4269
0
            return 0;
4270
0
        }
4271
1
        if (err != TxnErrorCode::TXN_OK) {
4272
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4273
0
                    .tag("instance_id", instance_id_)
4274
0
                    .tag("tablet_id", tablet_id)
4275
0
                    .tag("rowset_id", rowset_id)
4276
0
                    .tag("packed_file_path", packed_file_path)
4277
0
                    .tag("err", err);
4278
0
            return -1;
4279
0
        }
4280
4281
1
        cloud::PackedFileInfoPB packed_info;
4282
1
        if (!packed_info.ParseFromString(packed_val)) {
4283
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4284
0
                    .tag("instance_id", instance_id_)
4285
0
                    .tag("tablet_id", tablet_id)
4286
0
                    .tag("rowset_id", rowset_id)
4287
0
                    .tag("packed_file_path", packed_file_path);
4288
0
            return -1;
4289
0
        }
4290
4291
        // Find and mark the small file entry as deleted
4292
        // Use tablet_id and rowset_id to match entry instead of path,
4293
        // because path format may vary with path_version (with or without shard prefix)
4294
1
        auto* entries = packed_info.mutable_slices();
4295
1
        bool found = false;
4296
1
        bool already_deleted = false;
4297
1
        for (auto& entry : *entries) {
4298
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4299
1
                if (!entry.deleted()) {
4300
1
                    entry.set_deleted(true);
4301
1
                    if (!entry.corrected()) {
4302
1
                        entry.set_corrected(true);
4303
1
                    }
4304
1
                } else {
4305
0
                    already_deleted = true;
4306
0
                }
4307
1
                found = true;
4308
1
                break;
4309
1
            }
4310
1
        }
4311
4312
1
        if (!found) {
4313
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4314
0
                    .tag("instance_id", instance_id_)
4315
0
                    .tag("tablet_id", tablet_id)
4316
0
                    .tag("rowset_id", rowset_id)
4317
0
                    .tag("packed_file_path", packed_file_path);
4318
0
            return 0;
4319
0
        }
4320
4321
1
        if (already_deleted) {
4322
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4323
0
                    .tag("instance_id", instance_id_)
4324
0
                    .tag("tablet_id", tablet_id)
4325
0
                    .tag("rowset_id", rowset_id)
4326
0
                    .tag("packed_file_path", packed_file_path);
4327
0
            return 0;
4328
0
        }
4329
4330
        // Calculate remaining files
4331
1
        int64_t left_file_count = 0;
4332
1
        int64_t left_file_bytes = 0;
4333
1
        for (const auto& entry : packed_info.slices()) {
4334
1
            if (!entry.deleted()) {
4335
0
                ++left_file_count;
4336
0
                left_file_bytes += entry.size();
4337
0
            }
4338
1
        }
4339
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4340
1
        packed_info.set_ref_cnt(left_file_count);
4341
4342
1
        if (left_file_count == 0) {
4343
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4344
1
        }
4345
4346
1
        std::string updated_val;
4347
1
        if (!packed_info.SerializeToString(&updated_val)) {
4348
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4349
0
                    .tag("instance_id", instance_id_)
4350
0
                    .tag("tablet_id", tablet_id)
4351
0
                    .tag("rowset_id", rowset_id)
4352
0
                    .tag("packed_file_path", packed_file_path);
4353
0
            return -1;
4354
0
        }
4355
4356
1
        update_txn->put(packed_key, updated_val);
4357
1
        err = update_txn->commit();
4358
1
        if (err == TxnErrorCode::TXN_OK) {
4359
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4360
1
                    .tag("instance_id", instance_id_)
4361
1
                    .tag("tablet_id", tablet_id)
4362
1
                    .tag("rowset_id", rowset_id)
4363
1
                    .tag("packed_file_path", packed_file_path)
4364
1
                    .tag("left_file_count", left_file_count);
4365
1
            if (left_file_count == 0) {
4366
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4367
0
                    return -1;
4368
0
                }
4369
1
            }
4370
1
            return 0;
4371
1
        }
4372
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4373
0
            if (attempt >= max_retry_times) {
4374
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4375
0
                        .tag("instance_id", instance_id_)
4376
0
                        .tag("tablet_id", tablet_id)
4377
0
                        .tag("rowset_id", rowset_id)
4378
0
                        .tag("packed_file_path", packed_file_path)
4379
0
                        .tag("attempt", attempt);
4380
0
                return -1;
4381
0
            }
4382
0
            sleep_for_packed_file_retry();
4383
0
            continue;
4384
0
        }
4385
4386
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4387
0
                .tag("instance_id", instance_id_)
4388
0
                .tag("tablet_id", tablet_id)
4389
0
                .tag("rowset_id", rowset_id)
4390
0
                .tag("packed_file_path", packed_file_path)
4391
0
                .tag("err", err);
4392
0
        return -1;
4393
0
    }
4394
4395
18.4E
    return -1;
4396
18.4E
}
4397
4398
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4399
                                                const std::string& packed_key,
4400
8
                                                const cloud::PackedFileInfoPB& packed_info) {
4401
8
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4402
0
        LOG_WARNING("packed file missing resource id when recycling")
4403
0
                .tag("instance_id", instance_id_)
4404
0
                .tag("packed_file_path", packed_file_path);
4405
0
        return -1;
4406
0
    }
4407
4408
8
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4409
8
    if (!accessor) {
4410
0
        LOG_WARNING("no accessor available to delete packed file")
4411
0
                .tag("instance_id", instance_id_)
4412
0
                .tag("packed_file_path", packed_file_path)
4413
0
                .tag("resource_id", packed_info.resource_id());
4414
0
        return -1;
4415
0
    }
4416
4417
8
    int del_ret = accessor->delete_file(packed_file_path);
4418
8
    if (del_ret != 0 && del_ret != 1) {
4419
0
        LOG_WARNING("failed to delete packed file")
4420
0
                .tag("instance_id", instance_id_)
4421
0
                .tag("packed_file_path", packed_file_path)
4422
0
                .tag("resource_id", resource_id)
4423
0
                .tag("ret", del_ret);
4424
0
        return -1;
4425
0
    }
4426
8
    if (del_ret == 1) {
4427
0
        LOG_INFO("packed file already removed")
4428
0
                .tag("instance_id", instance_id_)
4429
0
                .tag("packed_file_path", packed_file_path)
4430
0
                .tag("resource_id", resource_id);
4431
8
    } else {
4432
8
        LOG_INFO("deleted packed file")
4433
8
                .tag("instance_id", instance_id_)
4434
8
                .tag("packed_file_path", packed_file_path)
4435
8
                .tag("resource_id", resource_id);
4436
8
    }
4437
4438
8
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4439
8
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4440
8
        std::unique_ptr<Transaction> del_txn;
4441
8
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4442
8
        if (err != TxnErrorCode::TXN_OK) {
4443
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4444
0
                    .tag("instance_id", instance_id_)
4445
0
                    .tag("packed_file_path", packed_file_path)
4446
0
                    .tag("attempt", attempt)
4447
0
                    .tag("err", err);
4448
0
            return -1;
4449
0
        }
4450
4451
8
        std::string latest_val;
4452
8
        err = del_txn->get(packed_key, &latest_val);
4453
8
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4454
0
            return 0;
4455
0
        }
4456
8
        if (err != TxnErrorCode::TXN_OK) {
4457
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4458
0
                    .tag("instance_id", instance_id_)
4459
0
                    .tag("packed_file_path", packed_file_path)
4460
0
                    .tag("attempt", attempt)
4461
0
                    .tag("err", err);
4462
0
            return -1;
4463
0
        }
4464
4465
8
        cloud::PackedFileInfoPB latest_info;
4466
8
        if (!latest_info.ParseFromString(latest_val)) {
4467
0
            LOG_WARNING("failed to parse packed file info before removal")
4468
0
                    .tag("instance_id", instance_id_)
4469
0
                    .tag("packed_file_path", packed_file_path)
4470
0
                    .tag("attempt", attempt);
4471
0
            return -1;
4472
0
        }
4473
4474
8
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4475
8
              latest_info.ref_cnt() == 0)) {
4476
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4477
0
                    .tag("instance_id", instance_id_)
4478
0
                    .tag("packed_file_path", packed_file_path)
4479
0
                    .tag("attempt", attempt);
4480
0
            return 0;
4481
0
        }
4482
4483
8
        del_txn->remove(packed_key);
4484
8
        err = del_txn->commit();
4485
8
        if (err == TxnErrorCode::TXN_OK) {
4486
8
            LOG_INFO("removed packed file metadata")
4487
8
                    .tag("instance_id", instance_id_)
4488
8
                    .tag("packed_file_path", packed_file_path);
4489
8
            return 0;
4490
8
        }
4491
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4492
0
            if (attempt >= max_retry_times) {
4493
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4494
0
                        .tag("instance_id", instance_id_)
4495
0
                        .tag("packed_file_path", packed_file_path)
4496
0
                        .tag("attempt", attempt);
4497
0
                return -1;
4498
0
            }
4499
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4500
0
                    .tag("instance_id", instance_id_)
4501
0
                    .tag("packed_file_path", packed_file_path)
4502
0
                    .tag("attempt", attempt);
4503
0
            sleep_for_packed_file_retry();
4504
0
            continue;
4505
0
        }
4506
0
        LOG_WARNING("failed to remove packed file kv")
4507
0
                .tag("instance_id", instance_id_)
4508
0
                .tag("packed_file_path", packed_file_path)
4509
0
                .tag("attempt", attempt)
4510
0
                .tag("err", err);
4511
0
        return -1;
4512
0
    }
4513
0
    return -1;
4514
8
}
4515
4516
int InstanceRecycler::delete_rowset_data(
4517
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4518
        RecyclerMetricsContext& metrics_context,
4519
66
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4520
66
    int ret = 0;
4521
    // resource_id -> file_paths
4522
66
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4523
    // (resource_id, tablet_id, rowset_id)
4524
66
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4525
66
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4526
4527
56.4k
    for (const auto& [_, rs] : rowsets) {
4528
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4529
        // due to aborted schema change.
4530
56.4k
        if (is_formal_rowset) {
4531
3.19k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4532
                // Tablet has been recycled and this rowset has no packed slices, so file data
4533
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4534
                // slice info must still run to decrement packed file ref counts.
4535
0
                continue;
4536
0
            }
4537
3.19k
        }
4538
4539
56.4k
        int64_t num_segments = rs.num_segments();
4540
        // Check num_segments before accessor lookup, because empty rowsets
4541
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4542
        // set. Skipping them early avoids a spurious "no such resource id" error
4543
        // that marks the entire batch as failed and prevents txn_remove from
4544
        // cleaning up recycle KV keys.
4545
56.4k
        if (num_segments <= 0) {
4546
0
            metrics_context.total_recycled_num++;
4547
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4548
0
            continue;
4549
0
        }
4550
4551
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4552
        // possible if the accessor is not initilized correctly
4553
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4554
2.00k
            LOG_WARNING("instance has no such resource id")
4555
2.00k
                    .tag("instance_id", instance_id_)
4556
2.00k
                    .tag("resource_id", rs.resource_id());
4557
2.00k
            ret = -1;
4558
2.00k
            continue;
4559
2.00k
        }
4560
4561
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4562
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4563
54.4k
        int64_t tablet_id = rs.tablet_id();
4564
54.4k
        LOG_INFO("recycle rowset merge index size")
4565
54.4k
                .tag("instance_id", instance_id_)
4566
54.4k
                .tag("tablet_id", tablet_id)
4567
54.4k
                .tag("rowset_id", rowset_id)
4568
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4569
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4570
0
            ret = -1;
4571
0
            continue;
4572
0
        }
4573
4574
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4575
54.4k
        std::vector<std::string> rowset_dbm_keys;
4576
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4577
54.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4578
54.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4579
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4580
0
                    .tag("instance_id", instance_id_)
4581
0
                    .tag("tablet_id", tablet_id)
4582
0
                    .tag("rowset_id", rowset_id);
4583
0
            ret = -1;
4584
0
            continue;
4585
0
        }
4586
54.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4587
1.55k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4588
1.55k
        }
4589
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4590
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4591
51.5k
        }
4592
4593
        // Process inverted indexes
4594
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4595
        // default format as v1.
4596
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4597
54.4k
                                                            ? rs.inverted_index_storage_format()
4598
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4599
54.4k
        int inverted_index_get_ret = 0;
4600
54.4k
        if (rs.has_tablet_schema()) {
4601
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4602
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4603
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4604
53.5k
                }
4605
53.5k
            }
4606
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4607
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4608
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4609
26.5k
            }
4610
27.6k
        } else {
4611
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4612
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4613
0
                                "instance_id="
4614
0
                             << instance_id_ << " tablet_id=" << tablet_id
4615
0
                             << " rowset_id=" << rowset_id;
4616
0
                ret = -1;
4617
0
                continue;
4618
0
            }
4619
27.6k
            InvertedIndexInfo index_info;
4620
27.6k
            inverted_index_get_ret =
4621
27.6k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4622
27.6k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4623
27.6k
                                     &inverted_index_get_ret);
4624
27.6k
            if (inverted_index_get_ret == 0) {
4625
27.1k
                if (!rs.has_inverted_index_storage_format()) {
4626
27.1k
                    index_format = index_info.first;
4627
27.1k
                }
4628
27.1k
                index_ids = index_info.second;
4629
27.1k
            } else if (inverted_index_get_ret == 1) {
4630
                // 1. Schema kv not found means tablet has been recycled
4631
                // Maybe some tablet recycle failed by some bugs
4632
                // We need to delete again to double check
4633
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4634
                // because we are uncertain about the inverted index information.
4635
                // If there are inverted indexes, some data might not be deleted,
4636
                // but this is acceptable as we have made our best effort to delete the data.
4637
503
                LOG_INFO(
4638
503
                        "delete rowset data schema kv not found, need to delete again to "
4639
503
                        "double "
4640
503
                        "check")
4641
503
                        .tag("instance_id", instance_id_)
4642
503
                        .tag("tablet_id", tablet_id)
4643
503
                        .tag("rowset", rs.ShortDebugString());
4644
                // Currently index_ids is guaranteed to be empty,
4645
                // but we clear it again here as a safeguard against future code changes
4646
                // that might cause index_ids to no longer be empty
4647
503
                index_format = InvertedIndexStorageFormatPB::V2;
4648
503
                index_ids.clear();
4649
18.4E
            } else {
4650
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4651
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4652
18.4E
                ret = -1;
4653
18.4E
                continue;
4654
18.4E
            }
4655
27.6k
        }
4656
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4657
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4658
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4659
10
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4660
10
            continue;
4661
10
        }
4662
325k
        for (int64_t i = 0; i < num_segments; ++i) {
4663
270k
            auto segment_id = rowset_segment_id(rs, i);
4664
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4665
270k
                                             &file_paths);
4666
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4667
537k
                for (const auto& index_id : index_ids) {
4668
537k
                    add_file_to_delete_if_not_packed(
4669
537k
                            rs,
4670
537k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4671
537k
                                                   index_id.second),
4672
537k
                            &file_paths);
4673
537k
                }
4674
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4675
                // try to recycle inverted index v2 when get_ret == 1
4676
                // we treat schema not found as if it has a v2 format inverted index
4677
                // to reduce chance of data leakage
4678
2.50k
                if (inverted_index_get_ret == 1) {
4679
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4680
2.50k
                            .tag("instance_id", instance_id_)
4681
2.50k
                            .tag("inverted index v2 path",
4682
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4683
2.50k
                }
4684
2.50k
                add_file_to_delete_if_not_packed(
4685
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4686
2.50k
            }
4687
270k
        }
4688
54.4k
    }
4689
4690
66
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4691
66
                                                 "delete_rowset_data",
4692
66
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_0clERKi
Line
Count
Source
4692
6
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_0clERKi
Line
Count
Source
4692
57
                                                 [](const int& ret) { return ret != 0; });
4693
66
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4694
53
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
53
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
53
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
53
                                     &accessor_map_);
4700
53
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
53
            auto& accessor = accessor_map_[*rid];
4707
53
            int ret = accessor->delete_files(*paths);
4708
53
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
53
                std::set<std::string> deleted_rowset_id;
4713
4714
53
                std::for_each(paths->begin(), paths->end(),
4715
53
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
862k
                               this](const std::string& path) {
4717
862k
                                  std::vector<std::string> str;
4718
862k
                                  butil::SplitString(path, '/', &str);
4719
862k
                                  std::string rowset_id;
4720
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
858k
                                      rowset_id = str.back().substr(0, pos);
4722
858k
                                  } else {
4723
3.93k
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
3.93k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
3.93k
                                      return;
4728
3.93k
                                  }
4729
858k
                                  auto rs_meta = rowsets.find(rowset_id);
4730
858k
                                  if (rs_meta != rowsets.end() &&
4731
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4733
54.4k
                                      metrics_context.total_recycled_data_size +=
4734
54.4k
                                              rs_meta->second.total_disk_size();
4735
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4736
54.4k
                                              rs_meta->second.num_segments();
4737
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4738
54.4k
                                              rs_meta->second.total_disk_size();
4739
54.4k
                                      metrics_context.total_recycled_num++;
4740
54.4k
                                  }
4741
858k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4716
7
                               this](const std::string& path) {
4717
7
                                  std::vector<std::string> str;
4718
7
                                  butil::SplitString(path, '/', &str);
4719
7
                                  std::string rowset_id;
4720
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
7
                                      rowset_id = str.back().substr(0, pos);
4722
7
                                  } else {
4723
0
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
0
                                      return;
4728
0
                                  }
4729
7
                                  auto rs_meta = rowsets.find(rowset_id);
4730
7
                                  if (rs_meta != rowsets.end() &&
4731
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
7
                                      deleted_rowset_id.emplace(rowset_id);
4733
7
                                      metrics_context.total_recycled_data_size +=
4734
7
                                              rs_meta->second.total_disk_size();
4735
7
                                      segment_metrics_context_.total_recycled_num +=
4736
7
                                              rs_meta->second.num_segments();
4737
7
                                      segment_metrics_context_.total_recycled_data_size +=
4738
7
                                              rs_meta->second.total_disk_size();
4739
7
                                      metrics_context.total_recycled_num++;
4740
7
                                  }
4741
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4716
862k
                               this](const std::string& path) {
4717
862k
                                  std::vector<std::string> str;
4718
862k
                                  butil::SplitString(path, '/', &str);
4719
862k
                                  std::string rowset_id;
4720
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
858k
                                      rowset_id = str.back().substr(0, pos);
4722
858k
                                  } else {
4723
3.93k
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
3.93k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
3.93k
                                      return;
4728
3.93k
                                  }
4729
858k
                                  auto rs_meta = rowsets.find(rowset_id);
4730
858k
                                  if (rs_meta != rowsets.end() &&
4731
858k
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4733
54.4k
                                      metrics_context.total_recycled_data_size +=
4734
54.4k
                                              rs_meta->second.total_disk_size();
4735
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4736
54.4k
                                              rs_meta->second.num_segments();
4737
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4738
54.4k
                                              rs_meta->second.total_disk_size();
4739
54.4k
                                      metrics_context.total_recycled_num++;
4740
54.4k
                                  }
4741
858k
                              });
4742
53
            }
4743
53
            return ret;
4744
53
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4694
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
6
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
6
                                     &accessor_map_);
4700
6
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
6
            auto& accessor = accessor_map_[*rid];
4707
6
            int ret = accessor->delete_files(*paths);
4708
6
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
6
                std::set<std::string> deleted_rowset_id;
4713
4714
6
                std::for_each(paths->begin(), paths->end(),
4715
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
6
                               this](const std::string& path) {
4717
6
                                  std::vector<std::string> str;
4718
6
                                  butil::SplitString(path, '/', &str);
4719
6
                                  std::string rowset_id;
4720
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
6
                                      rowset_id = str.back().substr(0, pos);
4722
6
                                  } else {
4723
6
                                      if (path.find("packed_file/") != std::string::npos) {
4724
6
                                          return; // packed files do not have rowset_id encoded
4725
6
                                      }
4726
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
6
                                      return;
4728
6
                                  }
4729
6
                                  auto rs_meta = rowsets.find(rowset_id);
4730
6
                                  if (rs_meta != rowsets.end() &&
4731
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
6
                                      deleted_rowset_id.emplace(rowset_id);
4733
6
                                      metrics_context.total_recycled_data_size +=
4734
6
                                              rs_meta->second.total_disk_size();
4735
6
                                      segment_metrics_context_.total_recycled_num +=
4736
6
                                              rs_meta->second.num_segments();
4737
6
                                      segment_metrics_context_.total_recycled_data_size +=
4738
6
                                              rs_meta->second.total_disk_size();
4739
6
                                      metrics_context.total_recycled_num++;
4740
6
                                  }
4741
6
                              });
4742
6
            }
4743
6
            return ret;
4744
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4694
47
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
47
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
47
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
47
                                     &accessor_map_);
4700
47
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
47
            auto& accessor = accessor_map_[*rid];
4707
47
            int ret = accessor->delete_files(*paths);
4708
47
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
47
                std::set<std::string> deleted_rowset_id;
4713
4714
47
                std::for_each(paths->begin(), paths->end(),
4715
47
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
47
                               this](const std::string& path) {
4717
47
                                  std::vector<std::string> str;
4718
47
                                  butil::SplitString(path, '/', &str);
4719
47
                                  std::string rowset_id;
4720
47
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
47
                                      rowset_id = str.back().substr(0, pos);
4722
47
                                  } else {
4723
47
                                      if (path.find("packed_file/") != std::string::npos) {
4724
47
                                          return; // packed files do not have rowset_id encoded
4725
47
                                      }
4726
47
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
47
                                      return;
4728
47
                                  }
4729
47
                                  auto rs_meta = rowsets.find(rowset_id);
4730
47
                                  if (rs_meta != rowsets.end() &&
4731
47
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
47
                                      deleted_rowset_id.emplace(rowset_id);
4733
47
                                      metrics_context.total_recycled_data_size +=
4734
47
                                              rs_meta->second.total_disk_size();
4735
47
                                      segment_metrics_context_.total_recycled_num +=
4736
47
                                              rs_meta->second.num_segments();
4737
47
                                      segment_metrics_context_.total_recycled_data_size +=
4738
47
                                              rs_meta->second.total_disk_size();
4739
47
                                      metrics_context.total_recycled_num++;
4740
47
                                  }
4741
47
                              });
4742
47
            }
4743
47
            return ret;
4744
47
        });
4745
53
    }
4746
66
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4747
10
        LOG_INFO(
4748
10
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4749
10
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4750
10
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4751
10
        concurrent_delete_executor.add([&]() -> int {
4752
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4753
10
            if (!ret) {
4754
10
                auto rs = rowsets.at(rowset_id);
4755
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4756
10
                metrics_context.total_recycled_num++;
4757
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4758
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4759
10
            }
4760
10
            return ret;
4761
10
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_2clEv
Line
Count
Source
4751
10
        concurrent_delete_executor.add([&]() -> int {
4752
10
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4753
10
            if (!ret) {
4754
10
                auto rs = rowsets.at(rowset_id);
4755
10
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4756
10
                metrics_context.total_recycled_num++;
4757
10
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4758
10
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4759
10
            }
4760
10
            return ret;
4761
10
        });
4762
10
    }
4763
4764
66
    bool finished = true;
4765
66
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4766
66
    for (int r : rets) {
4767
63
        if (r != 0) {
4768
0
            ret = -1;
4769
0
            break;
4770
0
        }
4771
63
    }
4772
66
    ret = finished ? ret : -1;
4773
66
    return ret;
4774
66
}
4775
4776
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4777
3.58k
                                         const std::string& rowset_id) {
4778
3.58k
    auto it = accessor_map_.find(resource_id);
4779
3.58k
    if (it == accessor_map_.end()) {
4780
400
        LOG_WARNING("instance has no such resource id")
4781
400
                .tag("instance_id", instance_id_)
4782
400
                .tag("resource_id", resource_id)
4783
400
                .tag("tablet_id", tablet_id)
4784
400
                .tag("rowset_id", rowset_id);
4785
400
        return -1;
4786
400
    }
4787
3.18k
    auto& accessor = it->second;
4788
3.18k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4789
3.58k
}
4790
4791
55.6k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4792
55.6k
    std::lock_guard lock(recycled_tablets_mtx_);
4793
55.6k
    return recycled_tablets_.contains(tablet_id);
4794
55.6k
}
4795
4796
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4797
52.4k
                                                                int64_t tablet_id) {
4798
52.4k
    bool is_mow = true;
4799
52.4k
    if (partition_id != -1) {
4800
52.2k
        std::lock_guard lock(partition_mow_cache_mutex);
4801
52.2k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4802
            // cache hit
4803
1
            is_mow = it->second;
4804
1
            return is_mow ? 1 : 0;
4805
1
        }
4806
52.2k
    }
4807
4808
52.4k
    TabletIndexPB tablet_index;
4809
52.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4810
52.4k
    if (ret == 1) {
4811
        // maybe recycled
4812
52.4k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4813
52.4k
    }
4814
26
    if (ret != 0) {
4815
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4816
0
                     << ", tablet_id=" << tablet_id;
4817
0
        return ret;
4818
0
    }
4819
4820
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4821
    // obtaining its partition ID from the tablet index.
4822
26
    if (partition_id == -1) {
4823
0
        partition_id = tablet_index.partition_id();
4824
0
        std::lock_guard lock(partition_mow_cache_mutex);
4825
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4826
0
            is_mow = it->second;
4827
0
            return is_mow ? 1 : 0;
4828
0
        }
4829
0
    }
4830
4831
26
    std::string tablet_meta_key =
4832
26
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4833
26
                             partition_id, tablet_id});
4834
26
    std::string tablet_meta_value;
4835
26
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4836
26
    if (ret == 1) {
4837
        // maybe recycled
4838
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4839
10
    }
4840
16
    if (ret != 0) {
4841
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4842
0
                     << ", tablet_id=" << tablet_id;
4843
0
        return ret;
4844
0
    }
4845
4846
16
    TabletMetaCloudPB tablet_meta;
4847
16
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4848
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4849
0
                     << ", tablet_id=" << tablet_id;
4850
0
        return -1;
4851
0
    }
4852
    // The row-binlog companion of a MoW data tablet stores versioned delete bitmaps copied from
4853
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4854
    // false value as the MoW state of the whole partition.
4855
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isRowBinlogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4856
16
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_ROW_BINLOG) {
4857
1
        return 1;
4858
1
    }
4859
15
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4860
15
    std::lock_guard lock(partition_mow_cache_mutex);
4861
15
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4862
15
    return it->second ? 1 : 0;
4863
16
}
4864
4865
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4866
52.4k
                                                         const std::string& rowset_id) {
4867
52.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4868
52.4k
    if (ret <= 0) {
4869
1.00k
        return ret;
4870
1.00k
    }
4871
4872
51.4k
    std::string dbm_start_key =
4873
51.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4874
51.4k
    std::string dbm_end_key = dbm_start_key;
4875
51.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4876
51.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4877
51.4k
    if (ret != 0) {
4878
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4879
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4880
0
                     << " rowset_id=" << rowset_id;
4881
0
    }
4882
51.4k
    return ret;
4883
52.4k
}
4884
4885
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4886
51.2k
    std::string delete_bitmap_start =
4887
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4888
51.2k
    std::string delete_bitmap_end =
4889
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4890
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4891
51.2k
    if (ret != 0) {
4892
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4893
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4894
0
    }
4895
51.2k
    return ret;
4896
51.2k
}
4897
4898
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4899
4
    if (key.empty()) {
4900
0
        return false;
4901
0
    }
4902
4
    std::string_view key_view = key;
4903
4
    key_view.remove_prefix(1); // remove keyspace prefix
4904
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4905
4
    if (decode_key(&key_view, &decoded) != 0) {
4906
0
        return false;
4907
0
    }
4908
4
    if (decoded.size() < 4) {
4909
0
        return false;
4910
0
    }
4911
4
    try {
4912
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4913
4
    } catch (const std::bad_variant_access&) {
4914
0
        return false;
4915
0
    }
4916
4
    return true;
4917
4
}
4918
4919
14
int InstanceRecycler::recycle_packed_files() {
4920
14
    const std::string task_name = "recycle_packed_files";
4921
14
    auto start_tp = steady_clock::now();
4922
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4923
14
    int ret = 0;
4924
14
    PackedFileRecycleStats stats;
4925
4926
14
    register_recycle_task(task_name, start_time);
4927
14
    DORIS_CLOUD_DEFER {
4928
14
        unregister_recycle_task(task_name);
4929
14
        int64_t cost =
4930
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4931
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4932
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4933
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4934
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4935
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4936
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4937
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4938
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4939
14
                                                             stats.bytes_object_deleted);
4940
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4941
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4942
14
                .tag("instance_id", instance_id_)
4943
14
                .tag("num_scanned", stats.num_scanned)
4944
14
                .tag("num_corrected", stats.num_corrected)
4945
14
                .tag("num_deleted", stats.num_deleted)
4946
14
                .tag("num_failed", stats.num_failed)
4947
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4948
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4949
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4950
14
                .tag("bytes_deleted", stats.bytes_deleted)
4951
14
                .tag("ret", ret);
4952
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4927
14
    DORIS_CLOUD_DEFER {
4928
14
        unregister_recycle_task(task_name);
4929
14
        int64_t cost =
4930
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4931
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4932
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4933
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4934
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4935
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4936
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4937
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4938
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4939
14
                                                             stats.bytes_object_deleted);
4940
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4941
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4942
14
                .tag("instance_id", instance_id_)
4943
14
                .tag("num_scanned", stats.num_scanned)
4944
14
                .tag("num_corrected", stats.num_corrected)
4945
14
                .tag("num_deleted", stats.num_deleted)
4946
14
                .tag("num_failed", stats.num_failed)
4947
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4948
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4949
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4950
14
                .tag("bytes_deleted", stats.bytes_deleted)
4951
14
                .tag("ret", ret);
4952
14
    };
4953
4954
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4955
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4956
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4957
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
4954
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4955
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4956
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4957
4
    };
4958
4959
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4960
4961
14
    std::string begin = packed_file_key({instance_id_, ""});
4962
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4963
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4964
0
        ret = -1;
4965
0
    }
4966
4967
14
    return ret;
4968
14
}
4969
4970
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4971
                                                  RecyclerMetricsContext& metrics_context,
4972
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4973
0
    std::string tablet_key_begin, tablet_key_end;
4974
4975
0
    if (partition_id > 0) {
4976
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4977
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4978
0
    } else {
4979
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4980
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4981
0
    }
4982
    // for calculate the total num or bytes of recyled objects
4983
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4984
0
                                                          std::string_view v) -> int {
4985
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4986
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4987
0
            return 0;
4988
0
        }
4989
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4990
4991
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4992
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4993
0
            return 0;
4994
0
        }
4995
4996
0
        if (!is_empty_tablet) {
4997
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4998
0
                return 0;
4999
0
            }
5000
0
            tablet_metrics_context_.total_need_recycle_num++;
5001
0
        }
5002
0
        return 0;
5003
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_
5004
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
5005
0
    metrics_context.report(true);
5006
0
    tablet_metrics_context_.report(true);
5007
0
    segment_metrics_context_.report(true);
5008
0
    return ret;
5009
0
}
5010
5011
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
5012
0
                                                 RecyclerMetricsContext& metrics_context) {
5013
0
    int ret = 0;
5014
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
5015
0
    std::unique_ptr<Transaction> txn;
5016
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5017
0
        LOG_WARNING("failed to recycle tablet ")
5018
0
                .tag("tablet id", tablet_id)
5019
0
                .tag("instance_id", instance_id_)
5020
0
                .tag("reason", "failed to create txn");
5021
0
        ret = -1;
5022
0
    }
5023
0
    GetRowsetResponse resp;
5024
0
    std::string msg;
5025
0
    MetaServiceCode code = MetaServiceCode::OK;
5026
    // get rowsets in tablet
5027
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5028
0
                        tablet_id, code, msg, &resp);
5029
0
    if (code != MetaServiceCode::OK) {
5030
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5031
0
                .tag("tablet id", tablet_id)
5032
0
                .tag("msg", msg)
5033
0
                .tag("code", code)
5034
0
                .tag("instance id", instance_id_);
5035
0
        ret = -1;
5036
0
    }
5037
0
    for (const auto& rs_meta : resp.rowset_meta()) {
5038
        /*
5039
        * For compatibility, we skip the loop for [0-1] here.
5040
        * The purpose of this loop is to delete object files,
5041
        * and since [0-1] only has meta and doesn't have object files,
5042
        * skipping it doesn't affect system correctness.
5043
        *
5044
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
5045
        * would return error -1 directly, causing the recycle operation to fail.
5046
        *
5047
        * [0-1] doesn't have resource id is a bug.
5048
        * In the future, we will fix this problem, after that,
5049
        * we can remove this if statement.
5050
        *
5051
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
5052
        */
5053
5054
0
        if (rs_meta.end_version() == 1) {
5055
            // Assert that [0-1] has no resource_id to make sure
5056
            // this if statement will not be forgetted to remove
5057
            // when the resource id bug is fixed
5058
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5059
0
            continue;
5060
0
        }
5061
0
        if (!rs_meta.has_resource_id()) {
5062
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5063
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5064
0
                    .tag("instance_id", instance_id_)
5065
0
                    .tag("tablet_id", tablet_id);
5066
0
            continue;
5067
0
        }
5068
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5069
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5070
        // possible if the accessor is not initilized correctly
5071
0
        if (it == accessor_map_.end()) [[unlikely]] {
5072
0
            LOG_WARNING(
5073
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5074
0
                    "recycle process")
5075
0
                    .tag("tablet id", tablet_id)
5076
0
                    .tag("instance_id", instance_id_)
5077
0
                    .tag("resource_id", rs_meta.resource_id())
5078
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5079
0
            continue;
5080
0
        }
5081
5082
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
5083
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5084
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5085
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
5086
0
    }
5087
0
    return ret;
5088
0
}
5089
5090
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5091
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5092
4.26k
            .tag("instance_id", instance_id_)
5093
4.26k
            .tag("tablet_id", tablet_id);
5094
5095
4.26k
    if (should_recycle_versioned_keys()) {
5096
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5097
14
        if (ret != 0) {
5098
0
            return ret;
5099
0
        }
5100
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5101
        // during the recycle_versioned_tablet process.
5102
        //
5103
        // .. And remove restore job rowsets of this tablet too
5104
14
    }
5105
5106
4.26k
    int ret = 0;
5107
4.26k
    auto start_time = steady_clock::now();
5108
5109
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5110
5111
    // collect resource ids
5112
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5113
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5114
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5115
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5116
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5117
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5118
5119
260
    std::set<std::string> resource_ids;
5120
260
    int64_t recycle_rowsets_number = 0;
5121
260
    int64_t recycle_segments_number = 0;
5122
260
    int64_t recycle_rowsets_data_size = 0;
5123
260
    int64_t recycle_rowsets_index_size = 0;
5124
260
    int64_t recycle_restore_job_rowsets_number = 0;
5125
260
    int64_t recycle_restore_job_segments_number = 0;
5126
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
5127
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
5128
260
    int64_t max_rowset_version = 0;
5129
260
    int64_t min_rowset_creation_time = INT64_MAX;
5130
260
    int64_t max_rowset_creation_time = 0;
5131
260
    int64_t min_rowset_expiration_time = INT64_MAX;
5132
260
    int64_t max_rowset_expiration_time = 0;
5133
5134
260
    DORIS_CLOUD_DEFER {
5135
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5136
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5137
260
                .tag("instance_id", instance_id_)
5138
260
                .tag("tablet_id", tablet_id)
5139
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5140
260
                .tag("recycle segments number", recycle_segments_number)
5141
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5142
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5143
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5144
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5145
260
                .tag("all restore job rowsets recycle data size",
5146
260
                     recycle_restore_job_rowsets_data_size)
5147
260
                .tag("all restore job rowsets recycle index size",
5148
260
                     recycle_restore_job_rowsets_index_size)
5149
260
                .tag("max rowset version", max_rowset_version)
5150
260
                .tag("min rowset creation time", min_rowset_creation_time)
5151
260
                .tag("max rowset creation time", max_rowset_creation_time)
5152
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5153
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5154
260
                .tag("task type", metrics_context.operation_type)
5155
260
                .tag("ret", ret);
5156
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5134
260
    DORIS_CLOUD_DEFER {
5135
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5136
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5137
260
                .tag("instance_id", instance_id_)
5138
260
                .tag("tablet_id", tablet_id)
5139
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5140
260
                .tag("recycle segments number", recycle_segments_number)
5141
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5142
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5143
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5144
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5145
260
                .tag("all restore job rowsets recycle data size",
5146
260
                     recycle_restore_job_rowsets_data_size)
5147
260
                .tag("all restore job rowsets recycle index size",
5148
260
                     recycle_restore_job_rowsets_index_size)
5149
260
                .tag("max rowset version", max_rowset_version)
5150
260
                .tag("min rowset creation time", min_rowset_creation_time)
5151
260
                .tag("max rowset creation time", max_rowset_creation_time)
5152
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5153
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5154
260
                .tag("task type", metrics_context.operation_type)
5155
260
                .tag("ret", ret);
5156
260
    };
5157
5158
260
    std::unique_ptr<Transaction> txn;
5159
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5160
0
        LOG_WARNING("failed to recycle tablet ")
5161
0
                .tag("tablet id", tablet_id)
5162
0
                .tag("instance_id", instance_id_)
5163
0
                .tag("reason", "failed to create txn");
5164
0
        ret = -1;
5165
0
    }
5166
260
    GetRowsetResponse resp;
5167
260
    std::string msg;
5168
260
    MetaServiceCode code = MetaServiceCode::OK;
5169
    // get rowsets in tablet
5170
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5171
260
                        tablet_id, code, msg, &resp);
5172
260
    if (code != MetaServiceCode::OK) {
5173
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5174
0
                .tag("tablet id", tablet_id)
5175
0
                .tag("msg", msg)
5176
0
                .tag("code", code)
5177
0
                .tag("instance id", instance_id_);
5178
0
        ret = -1;
5179
0
    }
5180
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5181
5182
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5183
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5184
3
            if (rs_meta.num_segments() <= 0) {
5185
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5186
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5187
2
                        .tag("instance_id", instance_id_)
5188
2
                        .tag("tablet_id", tablet_id);
5189
2
                recycle_rowsets_number += 1;
5190
2
                continue;
5191
2
            }
5192
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5193
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5194
1
                    .tag("instance_id", instance_id_)
5195
1
                    .tag("tablet_id", tablet_id);
5196
1
            return -1;
5197
3
        }
5198
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5199
0
                << "rs_meta" << rs_meta.ShortDebugString();
5200
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5201
        // possible if the accessor is not initilized correctly
5202
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5203
1
            LOG_WARNING(
5204
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5205
1
                    "recycle process")
5206
1
                    .tag("tablet id", tablet_id)
5207
1
                    .tag("instance_id", instance_id_)
5208
1
                    .tag("resource_id", rs_meta.resource_id())
5209
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5210
1
            return -1;
5211
1
        }
5212
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5213
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5214
0
                    .tag("instance_id", instance_id_)
5215
0
                    .tag("tablet_id", tablet_id)
5216
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5217
0
            return -1;
5218
0
        }
5219
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5220
2.54k
                                                           nullptr) != 0) {
5221
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5222
0
                    .tag("instance_id", instance_id_)
5223
0
                    .tag("tablet_id", tablet_id)
5224
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5225
0
            return -1;
5226
0
        }
5227
2.54k
        recycle_rowsets_number += 1;
5228
2.54k
        recycle_segments_number += rs_meta.num_segments();
5229
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5230
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5231
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5232
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5233
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5234
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5235
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5236
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5237
2.54k
    }
5238
5239
    // get restore job rowset in tablet
5240
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5241
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5242
258
    if (code != MetaServiceCode::OK) {
5243
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5244
0
                .tag("tablet id", tablet_id)
5245
0
                .tag("msg", msg)
5246
0
                .tag("code", code)
5247
0
                .tag("instance id", instance_id_);
5248
0
        return -1;
5249
0
    }
5250
5251
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5252
0
        if (!rs_meta.has_resource_id()) {
5253
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5254
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5255
0
                    .tag("instance_id", instance_id_)
5256
0
                    .tag("tablet_id", tablet_id);
5257
0
            return -1;
5258
0
        }
5259
5260
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5261
        // possible if the accessor is not initilized correctly
5262
0
        if (it == accessor_map_.end()) [[unlikely]] {
5263
0
            LOG_WARNING(
5264
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5265
0
                    "recycle process")
5266
0
                    .tag("tablet id", tablet_id)
5267
0
                    .tag("instance_id", instance_id_)
5268
0
                    .tag("resource_id", rs_meta.resource_id())
5269
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5270
0
            return -1;
5271
0
        }
5272
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5273
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5274
0
                    .tag("instance_id", instance_id_)
5275
0
                    .tag("tablet_id", tablet_id)
5276
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5277
0
            return -1;
5278
0
        }
5279
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5280
0
                                                           nullptr) != 0) {
5281
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5282
0
                    .tag("instance_id", instance_id_)
5283
0
                    .tag("tablet_id", tablet_id)
5284
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5285
0
            return -1;
5286
0
        }
5287
0
        recycle_restore_job_rowsets_number += 1;
5288
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5289
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5290
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5291
0
        resource_ids.emplace(rs_meta.resource_id());
5292
0
    }
5293
5294
258
    LOG_INFO("recycle tablet start to delete object")
5295
258
            .tag("instance id", instance_id_)
5296
258
            .tag("tablet id", tablet_id)
5297
258
            .tag("recycle tablet resource ids are",
5298
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5299
258
                                 [](std::string rs_id, const auto& it) {
5300
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5301
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
5299
217
                                 [](std::string rs_id, const auto& it) {
5300
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5301
217
                                 }));
5302
5303
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5304
258
            _thread_pool_group.s3_producer_pool,
5305
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5306
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
5306
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5307
5308
    // delete all rowset data in this tablet
5309
    // ATTN: there may be data leak if not all accessor initilized successfully
5310
    //       partial data deleted if the tablet is stored cross-storage vault
5311
    //       vault id is not attached to TabletMeta...
5312
258
    for (const auto& resource_id : resource_ids) {
5313
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5314
217
        concurrent_delete_executor.add(
5315
217
                [&, rs_id = resource_id,
5316
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5317
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5318
217
                    if (res != 0) {
5319
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5320
3
                                     << " path=" << accessor_ptr->uri()
5321
3
                                     << " task type=" << metrics_context.operation_type;
5322
3
                        return std::make_pair(-1, rs_id);
5323
3
                    }
5324
214
                    return std::make_pair(0, rs_id);
5325
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5316
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5317
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5318
217
                    if (res != 0) {
5319
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5320
3
                                     << " path=" << accessor_ptr->uri()
5321
3
                                     << " task type=" << metrics_context.operation_type;
5322
3
                        return std::make_pair(-1, rs_id);
5323
3
                    }
5324
214
                    return std::make_pair(0, rs_id);
5325
217
                });
5326
217
    }
5327
5328
258
    bool finished = true;
5329
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5330
258
    for (auto& r : rets) {
5331
217
        if (r.first != 0) {
5332
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5333
3
            ret = -1;
5334
3
        }
5335
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5336
217
    }
5337
258
    ret = finished ? ret : -1;
5338
5339
258
    if (ret != 0) { // failed recycle tablet data
5340
3
        LOG_WARNING("ret!=0")
5341
3
                .tag("finished", finished)
5342
3
                .tag("ret", ret)
5343
3
                .tag("instance_id", instance_id_)
5344
3
                .tag("tablet_id", tablet_id);
5345
3
        return ret;
5346
3
    }
5347
5348
255
    tablet_metrics_context_.total_recycled_data_size +=
5349
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5350
255
    tablet_metrics_context_.total_recycled_num += 1;
5351
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5352
255
    segment_metrics_context_.total_recycled_data_size +=
5353
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5354
255
    metrics_context.total_recycled_data_size +=
5355
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5356
255
    tablet_metrics_context_.report();
5357
255
    segment_metrics_context_.report();
5358
255
    metrics_context.report();
5359
5360
255
    txn.reset();
5361
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5362
0
        LOG_WARNING("failed to recycle tablet ")
5363
0
                .tag("tablet id", tablet_id)
5364
0
                .tag("instance_id", instance_id_)
5365
0
                .tag("reason", "failed to create txn");
5366
0
        ret = -1;
5367
0
    }
5368
    // delete all rowset kv in this tablet
5369
255
    txn->remove(rs_key0, rs_key1);
5370
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5371
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5372
5373
    // remove delete bitmap for MoW table
5374
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5375
255
    txn->remove(pending_key);
5376
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5377
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5378
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5379
5380
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5381
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5382
255
    txn->remove(dbm_start_key, dbm_end_key);
5383
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5384
255
              << " end=" << hex(dbm_end_key);
5385
5386
255
    TxnErrorCode err = txn->commit();
5387
255
    if (err != TxnErrorCode::TXN_OK) {
5388
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5389
0
        ret = -1;
5390
0
    }
5391
5392
255
    if (ret == 0) {
5393
        // All object files under tablet have been deleted
5394
255
        std::lock_guard lock(recycled_tablets_mtx_);
5395
255
        recycled_tablets_.insert(tablet_id);
5396
255
    }
5397
5398
255
    return ret;
5399
258
}
5400
5401
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5402
14
                                               RecyclerMetricsContext& metrics_context) {
5403
14
    int ret = 0;
5404
14
    auto start_time = steady_clock::now();
5405
5406
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5407
5408
    // collect resource ids
5409
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5410
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5411
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5412
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5413
5414
11
    int64_t recycle_rowsets_number = 0;
5415
11
    int64_t recycle_segments_number = 0;
5416
11
    int64_t recycle_rowsets_data_size = 0;
5417
11
    int64_t recycle_rowsets_index_size = 0;
5418
11
    int64_t max_rowset_version = 0;
5419
11
    int64_t min_rowset_creation_time = INT64_MAX;
5420
11
    int64_t max_rowset_creation_time = 0;
5421
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5422
11
    int64_t max_rowset_expiration_time = 0;
5423
5424
11
    DORIS_CLOUD_DEFER {
5425
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5426
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5427
11
                .tag("instance_id", instance_id_)
5428
11
                .tag("tablet_id", tablet_id)
5429
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5430
11
                .tag("recycle segments number", recycle_segments_number)
5431
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5432
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5433
11
                .tag("max rowset version", max_rowset_version)
5434
11
                .tag("min rowset creation time", min_rowset_creation_time)
5435
11
                .tag("max rowset creation time", max_rowset_creation_time)
5436
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5437
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5438
11
                .tag("ret", ret);
5439
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5424
11
    DORIS_CLOUD_DEFER {
5425
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5426
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5427
11
                .tag("instance_id", instance_id_)
5428
11
                .tag("tablet_id", tablet_id)
5429
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5430
11
                .tag("recycle segments number", recycle_segments_number)
5431
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5432
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5433
11
                .tag("max rowset version", max_rowset_version)
5434
11
                .tag("min rowset creation time", min_rowset_creation_time)
5435
11
                .tag("max rowset creation time", max_rowset_creation_time)
5436
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5437
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5438
11
                .tag("ret", ret);
5439
11
    };
5440
5441
11
    std::unique_ptr<Transaction> txn;
5442
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5443
0
        LOG_WARNING("failed to recycle tablet ")
5444
0
                .tag("tablet id", tablet_id)
5445
0
                .tag("instance_id", instance_id_)
5446
0
                .tag("reason", "failed to create txn");
5447
0
        ret = -1;
5448
0
    }
5449
5450
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5451
    // by the related operation logs.
5452
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5453
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5454
11
    MetaReader meta_reader(instance_id_);
5455
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5456
11
    if (err == TxnErrorCode::TXN_OK) {
5457
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5458
11
    }
5459
11
    if (err != TxnErrorCode::TXN_OK) {
5460
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5461
0
                .tag("tablet id", tablet_id)
5462
0
                .tag("err", err)
5463
0
                .tag("instance id", instance_id_);
5464
0
        ret = -1;
5465
0
    }
5466
5467
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5468
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5469
11
            .tag("instance_id", instance_id_)
5470
11
            .tag("tablet_id", tablet_id);
5471
5472
11
    SyncExecutor<int> concurrent_delete_executor(
5473
11
            _thread_pool_group.s3_producer_pool,
5474
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5475
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
5476
5477
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5478
60
        recycle_rowsets_number += 1;
5479
60
        recycle_segments_number += rs_meta.num_segments();
5480
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5481
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5482
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5483
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5484
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5485
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5486
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5487
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5477
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5478
60
        recycle_rowsets_number += 1;
5479
60
        recycle_segments_number += rs_meta.num_segments();
5480
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5481
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5482
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5483
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5484
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5485
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5486
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5487
60
    };
5488
5489
11
    std::vector<RowsetDeleteTask> all_tasks;
5490
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5491
60
        update_rowset_stats(rs_meta);
5492
        // Version 0-1 rowset has no resource_id and no actual data files,
5493
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5494
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5495
60
        RowsetDeleteTask task;
5496
60
        task.rowset_meta = rs_meta;
5497
60
        task.versioned_rowset_key =
5498
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5499
60
        task.non_versioned_rowset_key =
5500
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5501
60
        task.versionstamp = versionstamp;
5502
60
        all_tasks.push_back(std::move(task));
5503
60
    }
5504
5505
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5506
0
        update_rowset_stats(rs_meta);
5507
        // Version 0-1 rowset has no resource_id and no actual data files,
5508
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5509
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5510
0
        RowsetDeleteTask task;
5511
0
        task.rowset_meta = rs_meta;
5512
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5513
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5514
0
        task.non_versioned_rowset_key =
5515
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5516
0
        task.versionstamp = versionstamp;
5517
0
        all_tasks.push_back(std::move(task));
5518
0
    }
5519
5520
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5521
0
        RecycleRowsetPB recycle_rowset;
5522
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5523
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5524
0
            return -1;
5525
0
        }
5526
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5527
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5528
                // in old version, keep this key-value pair and it needs to be checked manually
5529
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5530
0
                return -1;
5531
0
            }
5532
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5533
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5534
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5535
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5536
0
                return -1;
5537
0
            }
5538
            // decode rowset_id
5539
0
            auto k1 = k;
5540
0
            k1.remove_prefix(1);
5541
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5542
0
            decode_key(&k1, &out);
5543
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5544
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5545
0
            LOG_INFO("delete old-version rowset data")
5546
0
                    .tag("instance_id", instance_id_)
5547
0
                    .tag("tablet_id", tablet_id)
5548
0
                    .tag("rowset_id", rowset_id);
5549
5550
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5551
            // so we must use prefix deletion directly instead of batch delete.
5552
0
            concurrent_delete_executor.add(
5553
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5554
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5555
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5556
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
5557
0
        } else {
5558
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5559
            // Version 0-1 rowset has no resource_id and no actual data files,
5560
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5561
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5562
0
            RowsetDeleteTask task;
5563
0
            task.rowset_meta = rowset_meta;
5564
0
            task.recycle_rowset_key = k;
5565
0
            all_tasks.push_back(std::move(task));
5566
0
        }
5567
0
        return 0;
5568
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_
5569
5570
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5571
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5572
0
                .tag("tablet id", tablet_id)
5573
0
                .tag("instance_id", instance_id_)
5574
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5575
0
        ret = -1;
5576
0
    }
5577
5578
    // Phase 1: Classify tasks by ref_count
5579
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5580
60
    for (auto& task : all_tasks) {
5581
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5582
60
        if (classify_ret < 0) {
5583
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5584
0
                    .tag("instance_id", instance_id_)
5585
0
                    .tag("tablet_id", tablet_id)
5586
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5587
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5588
0
                return recycle_rowset_meta_and_data(t);
5589
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5590
0
        }
5591
60
    }
5592
5593
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5594
5595
11
    LOG_INFO("batch delete plan created")
5596
11
            .tag("instance_id", instance_id_)
5597
11
            .tag("tablet_id", tablet_id)
5598
11
            .tag("plan_count", batch_delete_tasks.size());
5599
5600
    // Phase 2: Execute batch delete using existing delete_rowset_data
5601
11
    if (!batch_delete_tasks.empty()) {
5602
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5603
49
        for (const auto& task : batch_delete_tasks) {
5604
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5605
49
            if (task.rowset_meta.resource_id().empty()) {
5606
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5607
10
                        .tag("instance_id", instance_id_)
5608
10
                        .tag("tablet_id", tablet_id)
5609
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5610
10
                continue;
5611
10
            }
5612
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5613
39
        }
5614
5615
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5616
10
        bool delete_success = true;
5617
10
        if (!rowsets_to_delete.empty()) {
5618
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5619
9
                                                         "batch_delete_versioned_tablet");
5620
9
            int delete_ret = delete_rowset_data(
5621
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5622
9
            if (delete_ret != 0) {
5623
0
                LOG_WARNING("batch delete execution failed")
5624
0
                        .tag("instance_id", instance_id_)
5625
0
                        .tag("tablet_id", tablet_id);
5626
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5627
0
                ret = -1;
5628
0
                delete_success = false;
5629
0
            }
5630
9
        }
5631
5632
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5633
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5634
10
        if (delete_success) {
5635
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5636
10
            if (cleanup_ret != 0) {
5637
0
                LOG_WARNING("batch delete cleanup failed")
5638
0
                        .tag("instance_id", instance_id_)
5639
0
                        .tag("tablet_id", tablet_id);
5640
0
                ret = -1;
5641
0
            }
5642
10
        }
5643
10
    }
5644
5645
    // Always wait for fallback tasks to complete before returning
5646
11
    bool finished = true;
5647
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5648
11
    for (int r : rets) {
5649
0
        if (r != 0) {
5650
0
            ret = -1;
5651
0
        }
5652
0
    }
5653
5654
11
    ret = finished ? ret : -1;
5655
5656
11
    if (ret != 0) { // failed recycle tablet data
5657
0
        LOG_WARNING("recycle versioned tablet failed")
5658
0
                .tag("finished", finished)
5659
0
                .tag("ret", ret)
5660
0
                .tag("instance_id", instance_id_)
5661
0
                .tag("tablet_id", tablet_id);
5662
0
        return ret;
5663
0
    }
5664
5665
11
    tablet_metrics_context_.total_recycled_data_size +=
5666
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5667
11
    tablet_metrics_context_.total_recycled_num += 1;
5668
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5669
11
    segment_metrics_context_.total_recycled_data_size +=
5670
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5671
11
    metrics_context.total_recycled_data_size +=
5672
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5673
11
    tablet_metrics_context_.report();
5674
11
    segment_metrics_context_.report();
5675
11
    metrics_context.report();
5676
5677
11
    txn.reset();
5678
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5679
0
        LOG_WARNING("failed to recycle tablet ")
5680
0
                .tag("tablet id", tablet_id)
5681
0
                .tag("instance_id", instance_id_)
5682
0
                .tag("reason", "failed to create txn");
5683
0
        ret = -1;
5684
0
    }
5685
    // delete all rowset kv in this tablet
5686
11
    txn->remove(rs_key0, rs_key1);
5687
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5688
5689
    // remove delete bitmap for MoW table
5690
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5691
11
    txn->remove(pending_key);
5692
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5693
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5694
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5695
5696
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5697
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5698
11
    txn->remove(dbm_start_key, dbm_end_key);
5699
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5700
11
              << " end=" << hex(dbm_end_key);
5701
5702
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5703
11
    std::string tablet_index_val;
5704
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5705
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5706
0
        LOG_WARNING("failed to get tablet index kv")
5707
0
                .tag("instance_id", instance_id_)
5708
0
                .tag("tablet_id", tablet_id)
5709
0
                .tag("err", err);
5710
0
        ret = -1;
5711
11
    } else if (err == TxnErrorCode::TXN_OK) {
5712
        // If the tablet index kv exists, we need to delete it
5713
10
        TabletIndexPB tablet_index_pb;
5714
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5715
0
            LOG_WARNING("failed to parse tablet index pb")
5716
0
                    .tag("instance_id", instance_id_)
5717
0
                    .tag("tablet_id", tablet_id);
5718
0
            ret = -1;
5719
10
        } else {
5720
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5721
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5722
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5723
10
            txn->remove(versioned_inverted_idx_key);
5724
10
            txn->remove(versioned_idx_key);
5725
10
        }
5726
10
    }
5727
5728
11
    err = txn->commit();
5729
11
    if (err != TxnErrorCode::TXN_OK) {
5730
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5731
0
        ret = -1;
5732
0
    }
5733
5734
11
    if (ret == 0) {
5735
        // All object files under tablet have been deleted
5736
11
        std::lock_guard lock(recycled_tablets_mtx_);
5737
11
        recycled_tablets_.insert(tablet_id);
5738
11
    }
5739
5740
11
    return ret;
5741
11
}
5742
5743
87
int InstanceRecycler::recycle_rowsets() {
5744
87
    if (should_recycle_versioned_keys()) {
5745
5
        return recycle_versioned_rowsets();
5746
5
    }
5747
5748
82
    const std::string task_name = "recycle_rowsets";
5749
82
    int64_t num_scanned = 0;
5750
82
    int64_t num_expired = 0;
5751
82
    int64_t num_prepare = 0;
5752
82
    int64_t num_compacted = 0;
5753
82
    int64_t num_empty_rowset = 0;
5754
82
    size_t total_rowset_key_size = 0;
5755
82
    size_t total_rowset_value_size = 0;
5756
82
    size_t expired_rowset_size = 0;
5757
82
    std::atomic_long num_recycled = 0;
5758
82
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5759
5760
82
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5761
82
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5762
82
    std::string recyc_rs_key0;
5763
82
    std::string recyc_rs_key1;
5764
82
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5765
82
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5766
5767
82
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5768
5769
82
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5770
82
    register_recycle_task(task_name, start_time);
5771
5772
82
    DORIS_CLOUD_DEFER {
5773
82
        unregister_recycle_task(task_name);
5774
82
        int64_t cost =
5775
82
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
82
        metrics_context.finish_report();
5777
82
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
82
                .tag("instance_id", instance_id_)
5779
82
                .tag("num_scanned", num_scanned)
5780
82
                .tag("num_expired", num_expired)
5781
82
                .tag("num_recycled", num_recycled)
5782
82
                .tag("num_recycled.prepare", num_prepare)
5783
82
                .tag("num_recycled.compacted", num_compacted)
5784
82
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
82
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
82
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
82
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
82
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5772
7
    DORIS_CLOUD_DEFER {
5773
7
        unregister_recycle_task(task_name);
5774
7
        int64_t cost =
5775
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
7
        metrics_context.finish_report();
5777
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
7
                .tag("instance_id", instance_id_)
5779
7
                .tag("num_scanned", num_scanned)
5780
7
                .tag("num_expired", num_expired)
5781
7
                .tag("num_recycled", num_recycled)
5782
7
                .tag("num_recycled.prepare", num_prepare)
5783
7
                .tag("num_recycled.compacted", num_compacted)
5784
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5772
75
    DORIS_CLOUD_DEFER {
5773
75
        unregister_recycle_task(task_name);
5774
75
        int64_t cost =
5775
75
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
75
        metrics_context.finish_report();
5777
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
75
                .tag("instance_id", instance_id_)
5779
75
                .tag("num_scanned", num_scanned)
5780
75
                .tag("num_expired", num_expired)
5781
75
                .tag("num_recycled", num_recycled)
5782
75
                .tag("num_recycled.prepare", num_prepare)
5783
75
                .tag("num_recycled.compacted", num_compacted)
5784
75
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
75
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
75
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
75
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
75
    };
5789
5790
82
    struct RecycleRowsetEntry {
5791
82
        std::string key;
5792
82
        doris::RowsetMetaCloudPB meta;
5793
82
    };
5794
82
    struct RecycleRowsetDeleteJob {
5795
82
        std::vector<std::string> keys;
5796
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5797
82
    };
5798
    // Store the scanned recycle key with rowset meta. The scanned key is the actual KV key to delete.
5799
82
    std::vector<RecycleRowsetEntry> rowsets;
5800
82
    int64_t current_tablet_id = -1;
5801
82
    int64_t recycled_rowset_count_for_current_tablet = 0;
5802
82
    bool current_tablet_skip_logged = false;
5803
82
    std::string next_scan_begin;
5804
82
    const int64_t rowset_batch_size_per_tablet =
5805
82
            std::max(1, config::recycle_rowsets_per_tablet_batch_size);
5806
82
    const int64_t delete_rowset_batch_size =
5807
82
            std::min(500000, config::recycle_rowsets_delete_batch_size);
5808
4.33k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5809
4.33k
        if (current_tablet_id != tablet_id) {
5810
48
            current_tablet_id = tablet_id;
5811
48
            recycled_rowset_count_for_current_tablet = 0;
5812
48
            current_tablet_skip_logged = false;
5813
48
        }
5814
4.33k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5815
7
            if (!current_tablet_skip_logged) {
5816
7
                LOG_INFO(
5817
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5818
7
                        .tag("instance_id", instance_id_)
5819
7
                        .tag("tablet_id", tablet_id)
5820
7
                        .tag("limit", rowset_batch_size_per_tablet);
5821
7
                current_tablet_skip_logged = true;
5822
7
            }
5823
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5824
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5825
7
            return false;
5826
7
        }
5827
4.32k
        ++recycled_rowset_count_for_current_tablet;
5828
4.32k
        return true;
5829
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5808
7
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5809
7
        if (current_tablet_id != tablet_id) {
5810
7
            current_tablet_id = tablet_id;
5811
7
            recycled_rowset_count_for_current_tablet = 0;
5812
7
            current_tablet_skip_logged = false;
5813
7
        }
5814
7
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5815
0
            if (!current_tablet_skip_logged) {
5816
0
                LOG_INFO(
5817
0
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5818
0
                        .tag("instance_id", instance_id_)
5819
0
                        .tag("tablet_id", tablet_id)
5820
0
                        .tag("limit", rowset_batch_size_per_tablet);
5821
0
                current_tablet_skip_logged = true;
5822
0
            }
5823
0
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5824
0
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5825
0
            return false;
5826
0
        }
5827
7
        ++recycled_rowset_count_for_current_tablet;
5828
7
        return true;
5829
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_6clEl
Line
Count
Source
5808
4.32k
    auto try_reserve_tablet_recycle_slot = [&](int64_t tablet_id) -> bool {
5809
4.32k
        if (current_tablet_id != tablet_id) {
5810
41
            current_tablet_id = tablet_id;
5811
41
            recycled_rowset_count_for_current_tablet = 0;
5812
41
            current_tablet_skip_logged = false;
5813
41
        }
5814
4.32k
        if (recycled_rowset_count_for_current_tablet >= rowset_batch_size_per_tablet) {
5815
7
            if (!current_tablet_skip_logged) {
5816
7
                LOG_INFO(
5817
7
                        "skip recycle rowsets for tablet because per-tablet batch limit is reached")
5818
7
                        .tag("instance_id", instance_id_)
5819
7
                        .tag("tablet_id", tablet_id)
5820
7
                        .tag("limit", rowset_batch_size_per_tablet);
5821
7
                current_tablet_skip_logged = true;
5822
7
            }
5823
7
            const int64_t next_tablet_id = tablet_id == INT64_MAX ? INT64_MAX : tablet_id + 1;
5824
7
            recycle_rowset_key({instance_id_, next_tablet_id, ""}, &next_scan_begin);
5825
7
            return false;
5826
7
        }
5827
4.32k
        ++recycled_rowset_count_for_current_tablet;
5828
4.32k
        return true;
5829
4.32k
    };
5830
4.33k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5831
4.33k
        if (next_scan_begin.empty()) {
5832
4.32k
            return false;
5833
4.32k
        }
5834
7
        *begin = std::move(next_scan_begin);
5835
7
        next_scan_begin.clear();
5836
7
        return true;
5837
4.33k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5830
7
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5831
7
        if (next_scan_begin.empty()) {
5832
7
            return false;
5833
7
        }
5834
0
        *begin = std::move(next_scan_begin);
5835
0
        next_scan_begin.clear();
5836
0
        return true;
5837
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_5clEPNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
5830
4.32k
    auto next_scan_begin_getter = [&](std::string* begin) -> bool {
5831
4.32k
        if (next_scan_begin.empty()) {
5832
4.32k
            return false;
5833
4.32k
        }
5834
7
        *begin = std::move(next_scan_begin);
5835
7
        next_scan_begin.clear();
5836
7
        return true;
5837
4.32k
    };
5838
5839
82
    std::vector<std::string> rowset_keys_to_mark_recycled;
5840
82
    std::vector<std::string> rowset_keys_to_abort_job;
5841
5842
82
    std::mutex async_recycled_rowset_keys_mutex;
5843
82
    std::vector<std::string> async_recycled_rowset_keys;
5844
82
    std::vector<std::string> rowset_keys_without_data;
5845
82
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5846
82
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5847
82
    worker_pool->start();
5848
82
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5849
82
                                            int64_t partition_id, int64_t tablet_id,
5850
903
                                            const std::string& rowset_id) {
5851
        // Try to delete rowset data in background thread
5852
903
        int ret = worker_pool->submit_with_timeout(
5853
903
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5854
785
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5856
0
                        return;
5857
0
                    }
5858
785
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5859
785
                        0) {
5860
0
                        return;
5861
0
                    }
5862
785
                    std::vector<std::string> keys;
5863
785
                    {
5864
785
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5865
785
                        async_recycled_rowset_keys.push_back(std::move(key));
5866
785
                        if (async_recycled_rowset_keys.size() > 100) {
5867
5
                            keys.swap(async_recycled_rowset_keys);
5868
5
                        }
5869
785
                    }
5870
785
                    if (keys.empty()) return;
5871
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5872
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5873
0
                                     << instance_id_;
5874
5
                    } else {
5875
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5876
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5877
5
                                           num_recycled, start_time);
5878
5
                    }
5879
5
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5853
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5854
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5856
0
                        return;
5857
0
                    }
5858
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5859
1
                        0) {
5860
0
                        return;
5861
0
                    }
5862
1
                    std::vector<std::string> keys;
5863
1
                    {
5864
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5865
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5866
1
                        if (async_recycled_rowset_keys.size() > 100) {
5867
0
                            keys.swap(async_recycled_rowset_keys);
5868
0
                        }
5869
1
                    }
5870
1
                    if (keys.empty()) return;
5871
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5872
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5873
0
                                     << instance_id_;
5874
0
                    } else {
5875
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5876
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5877
0
                                           num_recycled, start_time);
5878
0
                    }
5879
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5853
784
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5854
784
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5856
0
                        return;
5857
0
                    }
5858
784
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5859
784
                        0) {
5860
0
                        return;
5861
0
                    }
5862
784
                    std::vector<std::string> keys;
5863
784
                    {
5864
784
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5865
784
                        async_recycled_rowset_keys.push_back(std::move(key));
5866
784
                        if (async_recycled_rowset_keys.size() > 100) {
5867
5
                            keys.swap(async_recycled_rowset_keys);
5868
5
                        }
5869
784
                    }
5870
784
                    if (keys.empty()) return;
5871
5
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5872
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5873
0
                                     << instance_id_;
5874
5
                    } else {
5875
5
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5876
5
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5877
5
                                           num_recycled, start_time);
5878
5
                    }
5879
5
                },
5880
903
                0);
5881
903
        if (ret == 0) return 0;
5882
        // Submit task failed, delete rowset data in current thread
5883
118
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5884
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5885
0
            return -1;
5886
0
        }
5887
118
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5888
0
            return -1;
5889
0
        }
5890
118
        rowset_keys_without_data.push_back(std::move(key));
5891
118
        return 0;
5892
118
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5850
1
                                            const std::string& rowset_id) {
5851
        // Try to delete rowset data in background thread
5852
1
        int ret = worker_pool->submit_with_timeout(
5853
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5854
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5855
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5856
1
                        return;
5857
1
                    }
5858
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5859
1
                        0) {
5860
1
                        return;
5861
1
                    }
5862
1
                    std::vector<std::string> keys;
5863
1
                    {
5864
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5865
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5866
1
                        if (async_recycled_rowset_keys.size() > 100) {
5867
1
                            keys.swap(async_recycled_rowset_keys);
5868
1
                        }
5869
1
                    }
5870
1
                    if (keys.empty()) return;
5871
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5872
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5873
1
                                     << instance_id_;
5874
1
                    } else {
5875
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5876
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5877
1
                                           num_recycled, start_time);
5878
1
                    }
5879
1
                },
5880
1
                0);
5881
1
        if (ret == 0) return 0;
5882
        // Submit task failed, delete rowset data in current thread
5883
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5884
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5885
0
            return -1;
5886
0
        }
5887
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5888
0
            return -1;
5889
0
        }
5890
0
        rowset_keys_without_data.push_back(std::move(key));
5891
0
        return 0;
5892
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5850
902
                                            const std::string& rowset_id) {
5851
        // Try to delete rowset data in background thread
5852
902
        int ret = worker_pool->submit_with_timeout(
5853
902
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5854
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5855
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5856
902
                        return;
5857
902
                    }
5858
902
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5859
902
                        0) {
5860
902
                        return;
5861
902
                    }
5862
902
                    std::vector<std::string> keys;
5863
902
                    {
5864
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5865
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5866
902
                        if (async_recycled_rowset_keys.size() > 100) {
5867
902
                            keys.swap(async_recycled_rowset_keys);
5868
902
                        }
5869
902
                    }
5870
902
                    if (keys.empty()) return;
5871
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5872
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5873
902
                                     << instance_id_;
5874
902
                    } else {
5875
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5876
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5877
902
                                           num_recycled, start_time);
5878
902
                    }
5879
902
                },
5880
902
                0);
5881
902
        if (ret == 0) return 0;
5882
        // Submit task failed, delete rowset data in current thread
5883
118
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5884
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5885
0
            return -1;
5886
0
        }
5887
118
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5888
0
            return -1;
5889
0
        }
5890
118
        rowset_keys_without_data.push_back(std::move(key));
5891
118
        return 0;
5892
118
    };
5893
5894
82
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5895
5896
4.33k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5897
4.33k
        ++num_scanned;
5898
4.33k
        total_rowset_key_size += k.size();
5899
4.33k
        total_rowset_value_size += v.size();
5900
4.33k
        RecycleRowsetPB rowset;
5901
4.33k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5902
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5903
0
            return -1;
5904
0
        }
5905
5906
4.33k
        int64_t current_time = ::time(nullptr);
5907
4.33k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5908
5909
4.33k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5910
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5911
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5912
4.33k
        if (current_time < expiration) { // not expired
5913
0
            return 0;
5914
0
        }
5915
4.33k
        ++num_expired;
5916
4.33k
        expired_rowset_size += v.size();
5917
5918
4.33k
        int64_t tablet_id =
5919
4.33k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5920
4.33k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5921
7
            return 0;
5922
7
        }
5923
5924
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5925
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5926
                // in old version, keep this key-value pair and it needs to be checked manually
5927
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5928
0
                return -1;
5929
0
            }
5930
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5931
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5932
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5933
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5934
2
                rowset_keys_without_data.emplace_back(k);
5935
2
                return 0;
5936
2
            }
5937
            // decode rowset_id
5938
250
            auto k1 = k;
5939
250
            k1.remove_prefix(1);
5940
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5941
250
            decode_key(&k1, &out);
5942
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5943
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5944
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5945
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5946
250
                      << " task_type=" << metrics_context.operation_type;
5947
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5948
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5949
0
                return -1;
5950
0
            }
5951
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5952
250
            metrics_context.total_recycled_num++;
5953
250
            segment_metrics_context_.total_recycled_data_size +=
5954
250
                    rowset.rowset_meta().total_disk_size();
5955
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5956
250
            return 0;
5957
250
        }
5958
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5959
5960
        // TODO(plat1ko): check rowset not referenced
5961
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5962
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5963
0
                LOG_INFO("recycle rowset that has empty resource id");
5964
0
            } else {
5965
                // other situations, keep this key-value pair and it needs to be checked manually
5966
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5967
0
                return -1;
5968
0
            }
5969
0
        }
5970
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5971
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5972
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5973
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5974
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5975
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5976
4.07k
                  << " rowset_meta_size=" << v.size()
5977
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5978
4.07k
                  << " task_type=" << metrics_context.operation_type;
5979
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5980
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5981
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5982
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5983
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5984
13
                                 "kv "
5985
13
                                 "at next turn, instance_id="
5986
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5987
13
                              << " version=[" << rowset_meta->start_version() << '-'
5988
13
                              << rowset_meta->end_version() << "]";
5989
13
                    return 0;
5990
13
                }
5991
23
            }
5992
5993
925
            num_prepare += 1;
5994
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5995
925
                rowset_meta->end_version() != 1) {
5996
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5997
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5998
272
                                 "instance_id="
5999
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
6000
272
                              << " version=[" << rowset_meta->start_version() << '-'
6001
272
                              << rowset_meta->end_version() << "]";
6002
272
                    rowset_keys_to_abort_job.emplace_back(k);
6003
272
                    return 0;
6004
272
                }
6005
273
            }
6006
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6007
653
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
6008
653
                                             rowset_meta->rowset_id_v2()) != 0) {
6009
0
                return -1;
6010
0
            }
6011
3.13k
        } else {
6012
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
6013
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
6014
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
6015
3.13k
            } else {
6016
3
                ++num_empty_rowset;
6017
3
                rowset_keys_without_data.emplace_back(k);
6018
3
            }
6019
3.13k
        }
6020
3.79k
        return 0;
6021
4.07k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5896
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5897
7
        ++num_scanned;
5898
7
        total_rowset_key_size += k.size();
5899
7
        total_rowset_value_size += v.size();
5900
7
        RecycleRowsetPB rowset;
5901
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5902
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5903
0
            return -1;
5904
0
        }
5905
5906
7
        int64_t current_time = ::time(nullptr);
5907
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5908
5909
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5910
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5911
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5912
7
        if (current_time < expiration) { // not expired
5913
0
            return 0;
5914
0
        }
5915
7
        ++num_expired;
5916
7
        expired_rowset_size += v.size();
5917
5918
7
        int64_t tablet_id =
5919
7
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5920
7
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5921
0
            return 0;
5922
0
        }
5923
5924
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5925
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5926
                // in old version, keep this key-value pair and it needs to be checked manually
5927
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5928
0
                return -1;
5929
0
            }
5930
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5931
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5932
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5933
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5934
0
                rowset_keys_without_data.emplace_back(k);
5935
0
                return 0;
5936
0
            }
5937
            // decode rowset_id
5938
0
            auto k1 = k;
5939
0
            k1.remove_prefix(1);
5940
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5941
0
            decode_key(&k1, &out);
5942
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5943
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5944
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5945
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5946
0
                      << " task_type=" << metrics_context.operation_type;
5947
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5948
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5949
0
                return -1;
5950
0
            }
5951
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5952
0
            metrics_context.total_recycled_num++;
5953
0
            segment_metrics_context_.total_recycled_data_size +=
5954
0
                    rowset.rowset_meta().total_disk_size();
5955
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5956
0
            return 0;
5957
0
        }
5958
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5959
5960
        // TODO(plat1ko): check rowset not referenced
5961
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5962
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5963
0
                LOG_INFO("recycle rowset that has empty resource id");
5964
0
            } else {
5965
                // other situations, keep this key-value pair and it needs to be checked manually
5966
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5967
0
                return -1;
5968
0
            }
5969
0
        }
5970
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5971
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5972
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5973
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5974
7
                  << "] txn_id=" << rowset_meta->txn_id()
5975
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5976
7
                  << " rowset_meta_size=" << v.size()
5977
7
                  << " creation_time=" << rowset_meta->creation_time()
5978
7
                  << " task_type=" << metrics_context.operation_type;
5979
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5980
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5981
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5982
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5983
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5984
4
                                 "kv "
5985
4
                                 "at next turn, instance_id="
5986
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5987
4
                              << " version=[" << rowset_meta->start_version() << '-'
5988
4
                              << rowset_meta->end_version() << "]";
5989
4
                    return 0;
5990
4
                }
5991
6
            }
5992
5993
3
            num_prepare += 1;
5994
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5995
3
                rowset_meta->end_version() != 1) {
5996
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5997
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5998
2
                                 "instance_id="
5999
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
6000
2
                              << " version=[" << rowset_meta->start_version() << '-'
6001
2
                              << rowset_meta->end_version() << "]";
6002
2
                    rowset_keys_to_abort_job.emplace_back(k);
6003
2
                    return 0;
6004
2
                }
6005
2
            }
6006
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6007
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
6008
1
                                             rowset_meta->rowset_id_v2()) != 0) {
6009
0
                return -1;
6010
0
            }
6011
1
        } else {
6012
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
6013
0
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
6014
0
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
6015
0
            } else {
6016
0
                ++num_empty_rowset;
6017
0
                rowset_keys_without_data.emplace_back(k);
6018
0
            }
6019
0
        }
6020
1
        return 0;
6021
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_4clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5896
4.32k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5897
4.32k
        ++num_scanned;
5898
4.32k
        total_rowset_key_size += k.size();
5899
4.32k
        total_rowset_value_size += v.size();
5900
4.32k
        RecycleRowsetPB rowset;
5901
4.32k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5902
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5903
0
            return -1;
5904
0
        }
5905
5906
4.32k
        int64_t current_time = ::time(nullptr);
5907
4.32k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5908
5909
4.32k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5910
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5911
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5912
4.32k
        if (current_time < expiration) { // not expired
5913
0
            return 0;
5914
0
        }
5915
4.32k
        ++num_expired;
5916
4.32k
        expired_rowset_size += v.size();
5917
5918
4.32k
        int64_t tablet_id =
5919
4.32k
                rowset.has_type() ? rowset.rowset_meta().tablet_id() : rowset.tablet_id();
5920
4.32k
        if (!try_reserve_tablet_recycle_slot(tablet_id)) {
5921
7
            return 0;
5922
7
        }
5923
5924
4.32k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5925
252
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5926
                // in old version, keep this key-value pair and it needs to be checked manually
5927
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5928
0
                return -1;
5929
0
            }
5930
252
            if (rowset.resource_id().empty()) [[unlikely]] {
5931
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5932
2
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5933
2
                          << hex(k) << " value=" << proto_to_json(rowset);
5934
2
                rowset_keys_without_data.emplace_back(k);
5935
2
                return 0;
5936
2
            }
5937
            // decode rowset_id
5938
250
            auto k1 = k;
5939
250
            k1.remove_prefix(1);
5940
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5941
250
            decode_key(&k1, &out);
5942
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5943
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5944
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5945
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5946
250
                      << " task_type=" << metrics_context.operation_type;
5947
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5948
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5949
0
                return -1;
5950
0
            }
5951
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5952
250
            metrics_context.total_recycled_num++;
5953
250
            segment_metrics_context_.total_recycled_data_size +=
5954
250
                    rowset.rowset_meta().total_disk_size();
5955
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5956
250
            return 0;
5957
250
        }
5958
4.07k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5959
5960
        // TODO(plat1ko): check rowset not referenced
5961
4.07k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5962
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5963
0
                LOG_INFO("recycle rowset that has empty resource id");
5964
0
            } else {
5965
                // other situations, keep this key-value pair and it needs to be checked manually
5966
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5967
0
                return -1;
5968
0
            }
5969
0
        }
5970
4.07k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5971
4.07k
                  << " tablet_id=" << rowset_meta->tablet_id()
5972
4.07k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5973
4.07k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5974
4.07k
                  << "] txn_id=" << rowset_meta->txn_id()
5975
4.07k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5976
4.07k
                  << " rowset_meta_size=" << v.size()
5977
4.07k
                  << " creation_time=" << rowset_meta->creation_time()
5978
4.07k
                  << " task_type=" << metrics_context.operation_type;
5979
4.07k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5980
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5981
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5982
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5983
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5984
9
                                 "kv "
5985
9
                                 "at next turn, instance_id="
5986
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5987
9
                              << " version=[" << rowset_meta->start_version() << '-'
5988
9
                              << rowset_meta->end_version() << "]";
5989
9
                    return 0;
5990
9
                }
5991
17
            }
5992
5993
922
            num_prepare += 1;
5994
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5995
922
                rowset_meta->end_version() != 1) {
5996
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5997
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5998
270
                                 "instance_id="
5999
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
6000
270
                              << " version=[" << rowset_meta->start_version() << '-'
6001
270
                              << rowset_meta->end_version() << "]";
6002
270
                    rowset_keys_to_abort_job.emplace_back(k);
6003
270
                    return 0;
6004
270
                }
6005
271
            }
6006
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6007
652
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
6008
652
                                             rowset_meta->rowset_id_v2()) != 0) {
6009
0
                return -1;
6010
0
            }
6011
3.13k
        } else {
6012
3.13k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
6013
3.13k
            if (rowset_meta->num_segments() > 0) { // Skip empty rowset
6014
3.13k
                rowsets.emplace_back(std::string(k), std::move(*rowset_meta));
6015
3.13k
            } else {
6016
3
                ++num_empty_rowset;
6017
3
                rowset_keys_without_data.emplace_back(k);
6018
3
            }
6019
3.13k
        }
6020
3.79k
        return 0;
6021
4.07k
    };
6022
6023
82
    auto submit_delete_rowset_data_job = [&](std::vector<std::string> rowset_keys,
6024
82
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
6025
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
6026
23
                             rowsets_to_delete = std::move(rowsets)]() {
6027
23
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6028
23
            if (!rowsets_to_delete.empty() &&
6029
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6030
18
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6031
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6032
0
                return;
6033
0
            }
6034
23
            if (!versioned_delete_bitmap_key_groups.empty() &&
6035
23
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6036
3
                                                         versioned_delete_bitmap_key_groups) != 0) {
6037
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6038
0
                             << instance_id_;
6039
0
                return;
6040
0
            }
6041
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6042
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6043
0
                return;
6044
0
            }
6045
6046
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6047
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
6026
23
                             rowsets_to_delete = std::move(rowsets)]() {
6027
23
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6028
23
            if (!rowsets_to_delete.empty() &&
6029
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6030
18
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6031
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6032
0
                return;
6033
0
            }
6034
23
            if (!versioned_delete_bitmap_key_groups.empty() &&
6035
23
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6036
3
                                                         versioned_delete_bitmap_key_groups) != 0) {
6037
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6038
0
                             << instance_id_;
6039
0
                return;
6040
0
            }
6041
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6042
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6043
0
                return;
6044
0
            }
6045
6046
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6047
23
        });
6048
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
6024
23
                                             std::map<std::string, RowsetMetaCloudPB> rowsets) {
6025
23
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys),
6026
23
                             rowsets_to_delete = std::move(rowsets)]() {
6027
23
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6028
23
            if (!rowsets_to_delete.empty() &&
6029
23
                delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6030
23
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6031
23
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6032
23
                return;
6033
23
            }
6034
23
            if (!versioned_delete_bitmap_key_groups.empty() &&
6035
23
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6036
23
                                                         versioned_delete_bitmap_key_groups) != 0) {
6037
23
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6038
23
                             << instance_id_;
6039
23
                return;
6040
23
            }
6041
23
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6042
23
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6043
23
                return;
6044
23
            }
6045
6046
23
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6047
23
        });
6048
23
    };
6049
6050
82
    bool scan_finished = false;
6051
144
    auto loop_done = [&]() -> int {
6052
144
        std::vector<std::string> mark_keys_to_process;
6053
144
        std::vector<std::string> abort_job_keys_to_process;
6054
144
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6055
144
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6056
144
        if (!mark_keys_to_process.empty()) {
6057
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6058
11
                    *worker_pool, std::move(mark_keys_to_process));
6059
11
        }
6060
144
        if (!abort_job_keys_to_process.empty()) {
6061
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6062
15
                                               &num_recycled);
6063
15
        }
6064
144
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
6065
62
            return 0;
6066
62
        }
6067
6068
82
        DORIS_CLOUD_DEFER {
6069
            // if return -1 in loop done, rowset info in memory is not cleared,
6070
            // it can lead to memory accumulation
6071
82
            rowset_keys_without_data.clear();
6072
82
            rowsets.clear();
6073
82
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
6068
7
        DORIS_CLOUD_DEFER {
6069
            // if return -1 in loop done, rowset info in memory is not cleared,
6070
            // it can lead to memory accumulation
6071
7
            rowset_keys_without_data.clear();
6072
7
            rowsets.clear();
6073
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
6068
75
        DORIS_CLOUD_DEFER {
6069
            // if return -1 in loop done, rowset info in memory is not cleared,
6070
            // it can lead to memory accumulation
6071
75
            rowset_keys_without_data.clear();
6072
75
            rowsets.clear();
6073
75
        };
6074
82
        std::random_device rd;
6075
82
        std::mt19937 g(rd());
6076
82
        std::ranges::shuffle(rowsets, g);
6077
6078
82
        std::vector<std::string> rowset_keys_to_delete;
6079
82
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6080
        // rowset_id -> rowset_meta
6081
        // store rowset id and meta for statistics rs size when delete
6082
82
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6083
82
        std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6084
6085
82
        size_t rowsets_per_batch_size = 0;
6086
3.13k
        for (auto& rowset : rowsets) {
6087
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6088
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6089
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6090
3.12k
                continue;
6091
3.12k
            }
6092
6093
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6094
8
                                          std::move(rowsets_to_delete));
6095
8
            rowsets_per_batch_size = 0;
6096
8
            rowset_keys_to_delete.clear();
6097
8
            rowsets_to_delete.clear();
6098
8
        }
6099
6100
82
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6101
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6102
10
                                          std::move(rowsets_to_delete));
6103
10
        }
6104
6105
87
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6106
5
            auto begin = rowset_keys_without_data.begin() + i;
6107
5
            auto end = rowset_keys_without_data.begin() +
6108
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6109
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6110
5
                                                           std::make_move_iterator(end));
6111
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6112
5
        }
6113
82
        return 0;
6114
144
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
6051
14
    auto loop_done = [&]() -> int {
6052
14
        std::vector<std::string> mark_keys_to_process;
6053
14
        std::vector<std::string> abort_job_keys_to_process;
6054
14
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6055
14
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6056
14
        if (!mark_keys_to_process.empty()) {
6057
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6058
4
                    *worker_pool, std::move(mark_keys_to_process));
6059
4
        }
6060
14
        if (!abort_job_keys_to_process.empty()) {
6061
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6062
2
                                               &num_recycled);
6063
2
        }
6064
14
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
6065
7
            return 0;
6066
7
        }
6067
6068
7
        DORIS_CLOUD_DEFER {
6069
            // if return -1 in loop done, rowset info in memory is not cleared,
6070
            // it can lead to memory accumulation
6071
7
            rowset_keys_without_data.clear();
6072
7
            rowsets.clear();
6073
7
        };
6074
7
        std::random_device rd;
6075
7
        std::mt19937 g(rd());
6076
7
        std::ranges::shuffle(rowsets, g);
6077
6078
7
        std::vector<std::string> rowset_keys_to_delete;
6079
7
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6080
        // rowset_id -> rowset_meta
6081
        // store rowset id and meta for statistics rs size when delete
6082
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6083
7
        std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6084
6085
7
        size_t rowsets_per_batch_size = 0;
6086
7
        for (auto& rowset : rowsets) {
6087
0
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6088
0
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6089
0
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6090
0
                continue;
6091
0
            }
6092
6093
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6094
0
                                          std::move(rowsets_to_delete));
6095
0
            rowsets_per_batch_size = 0;
6096
0
            rowset_keys_to_delete.clear();
6097
0
            rowsets_to_delete.clear();
6098
0
        }
6099
6100
7
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6101
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6102
0
                                          std::move(rowsets_to_delete));
6103
0
        }
6104
6105
7
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6106
0
            auto begin = rowset_keys_without_data.begin() + i;
6107
0
            auto end = rowset_keys_without_data.begin() +
6108
0
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6109
0
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6110
0
                                                           std::make_move_iterator(end));
6111
0
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6112
0
        }
6113
7
        return 0;
6114
14
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clEv
Line
Count
Source
6051
130
    auto loop_done = [&]() -> int {
6052
130
        std::vector<std::string> mark_keys_to_process;
6053
130
        std::vector<std::string> abort_job_keys_to_process;
6054
130
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6055
130
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6056
130
        if (!mark_keys_to_process.empty()) {
6057
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6058
7
                    *worker_pool, std::move(mark_keys_to_process));
6059
7
        }
6060
130
        if (!abort_job_keys_to_process.empty()) {
6061
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6062
13
                                               &num_recycled);
6063
13
        }
6064
130
        if (!scan_finished && rowsets.size() < delete_rowset_batch_size) {
6065
55
            return 0;
6066
55
        }
6067
6068
75
        DORIS_CLOUD_DEFER {
6069
            // if return -1 in loop done, rowset info in memory is not cleared,
6070
            // it can lead to memory accumulation
6071
75
            rowset_keys_without_data.clear();
6072
75
            rowsets.clear();
6073
75
        };
6074
75
        std::random_device rd;
6075
75
        std::mt19937 g(rd());
6076
75
        std::ranges::shuffle(rowsets, g);
6077
6078
75
        std::vector<std::string> rowset_keys_to_delete;
6079
75
        rowset_keys_to_delete.reserve(rowset_batch_size_per_tablet);
6080
        // rowset_id -> rowset_meta
6081
        // store rowset id and meta for statistics rs size when delete
6082
75
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6083
75
        std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6084
6085
75
        size_t rowsets_per_batch_size = 0;
6086
3.13k
        for (auto& rowset : rowsets) {
6087
3.13k
            rowset_keys_to_delete.emplace_back(std::move(rowset.key));
6088
3.13k
            rowsets_to_delete.emplace(rowset.meta.rowset_id_v2(), std::move(rowset.meta));
6089
3.13k
            if (++rowsets_per_batch_size < rowset_batch_size_per_tablet) {
6090
3.12k
                continue;
6091
3.12k
            }
6092
6093
8
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6094
8
                                          std::move(rowsets_to_delete));
6095
8
            rowsets_per_batch_size = 0;
6096
8
            rowset_keys_to_delete.clear();
6097
8
            rowsets_to_delete.clear();
6098
8
        }
6099
6100
75
        if (!rowset_keys_to_delete.empty() || !rowsets_to_delete.empty()) {
6101
10
            submit_delete_rowset_data_job(std::move(rowset_keys_to_delete),
6102
10
                                          std::move(rowsets_to_delete));
6103
10
        }
6104
6105
80
        for (size_t i = 0; i < rowset_keys_without_data.size(); i += rowset_batch_size_per_tablet) {
6106
5
            auto begin = rowset_keys_without_data.begin() + i;
6107
5
            auto end = rowset_keys_without_data.begin() +
6108
5
                       std::min(i + rowset_batch_size_per_tablet, rowset_keys_without_data.size());
6109
5
            std::vector<std::string> rowset_keys_to_remove(std::make_move_iterator(begin),
6110
5
                                                           std::make_move_iterator(end));
6111
5
            submit_delete_rowset_data_job(std::move(rowset_keys_to_remove), {});
6112
5
        }
6113
75
        return 0;
6114
130
    };
6115
6116
82
    if (config::enable_recycler_stats_metrics) {
6117
0
        scan_and_statistics_rowsets();
6118
0
    }
6119
    // recycle_func and loop_done for scan and recycle
6120
82
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv), loop_done,
6121
82
                               std::move(next_scan_begin_getter));
6122
82
    scan_finished = true;
6123
    // if the size of rowsets is always less than delete_rowset_batch_size
6124
    // it need to submit the task directly
6125
    // else if the size of rowsets is greater than delete_rowset_batch_size,
6126
    // but there are residual, whether due to failed or unsuccessful cleanup, this behavior is idempotent
6127
82
    if (loop_done() != 0) {
6128
0
        ret = -1;
6129
0
    }
6130
6131
82
    worker_pool->stop();
6132
6133
82
    if (!async_recycled_rowset_keys.empty()) {
6134
6
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6135
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6136
0
            return -1;
6137
6
        } else {
6138
6
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6139
6
        }
6140
6
    }
6141
6142
    // Report final metrics after all concurrent tasks completed
6143
82
    segment_metrics_context_.report();
6144
82
    metrics_context.report();
6145
6146
82
    return ret;
6147
82
}
6148
6149
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
6150
1
                                                     int64_t tablet_id, std::string* next_key) {
6151
1
    DCHECK(next_key != nullptr);
6152
1
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
6153
0
        return -1;
6154
0
    }
6155
1
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
6156
1
    return 0;
6157
1
}
6158
6159
13
int InstanceRecycler::recycle_restore_jobs() {
6160
13
    const std::string task_name = "recycle_restore_jobs";
6161
13
    int64_t num_scanned = 0;
6162
13
    int64_t num_expired = 0;
6163
13
    int64_t num_recycled = 0;
6164
13
    int64_t num_aborted = 0;
6165
6166
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6167
6168
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6169
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6170
13
    std::string restore_job_key0;
6171
13
    std::string restore_job_key1;
6172
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6173
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6174
6175
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6176
6177
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6178
13
    register_recycle_task(task_name, start_time);
6179
6180
13
    DORIS_CLOUD_DEFER {
6181
13
        unregister_recycle_task(task_name);
6182
13
        int64_t cost =
6183
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6184
13
        metrics_context.finish_report();
6185
6186
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6187
13
                .tag("instance_id", instance_id_)
6188
13
                .tag("num_scanned", num_scanned)
6189
13
                .tag("num_expired", num_expired)
6190
13
                .tag("num_recycled", num_recycled)
6191
13
                .tag("num_aborted", num_aborted);
6192
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6180
13
    DORIS_CLOUD_DEFER {
6181
13
        unregister_recycle_task(task_name);
6182
13
        int64_t cost =
6183
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6184
13
        metrics_context.finish_report();
6185
6186
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6187
13
                .tag("instance_id", instance_id_)
6188
13
                .tag("num_scanned", num_scanned)
6189
13
                .tag("num_expired", num_expired)
6190
13
                .tag("num_recycled", num_recycled)
6191
13
                .tag("num_aborted", num_aborted);
6192
13
    };
6193
6194
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6195
6196
13
    std::vector<std::string_view> restore_job_keys;
6197
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6198
41
        ++num_scanned;
6199
41
        RestoreJobCloudPB restore_job_pb;
6200
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6201
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6202
0
            return -1;
6203
0
        }
6204
41
        int64_t expiration =
6205
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6206
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6207
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6208
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6209
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6210
0
                   << " state=" << restore_job_pb.state();
6211
41
        int64_t current_time = ::time(nullptr);
6212
41
        if (current_time < expiration) { // not expired
6213
0
            return 0;
6214
0
        }
6215
41
        ++num_expired;
6216
6217
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6218
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6219
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6220
6221
41
        std::unique_ptr<Transaction> txn;
6222
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6223
41
        if (err != TxnErrorCode::TXN_OK) {
6224
0
            LOG_WARNING("failed to recycle restore job")
6225
0
                    .tag("err", err)
6226
0
                    .tag("tablet id", tablet_id)
6227
0
                    .tag("instance_id", instance_id_)
6228
0
                    .tag("reason", "failed to create txn");
6229
0
            return -1;
6230
0
        }
6231
6232
41
        std::string val;
6233
41
        err = txn->get(k, &val);
6234
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6235
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6236
0
            return 0;
6237
0
        }
6238
41
        if (err != TxnErrorCode::TXN_OK) {
6239
0
            LOG_WARNING("failed to get kv");
6240
0
            return -1;
6241
0
        }
6242
41
        restore_job_pb.Clear();
6243
41
        if (!restore_job_pb.ParseFromString(val)) {
6244
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6245
0
            return -1;
6246
0
        }
6247
6248
        // PREPARED or COMMITTED, change state to DROPPED and return
6249
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6250
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6251
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6252
0
            restore_job_pb.set_need_recycle_data(true);
6253
0
            txn->put(k, restore_job_pb.SerializeAsString());
6254
0
            err = txn->commit();
6255
0
            if (err != TxnErrorCode::TXN_OK) {
6256
0
                LOG_WARNING("failed to commit txn: {}", err);
6257
0
                return -1;
6258
0
            }
6259
0
            num_aborted++;
6260
0
            return 0;
6261
0
        }
6262
6263
        // Change state to RECYCLING
6264
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6265
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6266
21
            txn->put(k, restore_job_pb.SerializeAsString());
6267
21
            err = txn->commit();
6268
21
            if (err != TxnErrorCode::TXN_OK) {
6269
0
                LOG_WARNING("failed to commit txn: {}", err);
6270
0
                return -1;
6271
0
            }
6272
21
            return 0;
6273
21
        }
6274
6275
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6276
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6277
6278
        // Recycle all data associated with the restore job.
6279
        // This includes rowsets, segments, and related resources.
6280
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6281
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6282
0
            LOG_WARNING("failed to recycle tablet")
6283
0
                    .tag("tablet_id", tablet_id)
6284
0
                    .tag("instance_id", instance_id_);
6285
0
            return -1;
6286
0
        }
6287
6288
        // delete all restore job rowset kv
6289
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6290
6291
20
        err = txn->commit();
6292
20
        if (err != TxnErrorCode::TXN_OK) {
6293
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6294
0
                    .tag("err", err)
6295
0
                    .tag("tablet id", tablet_id)
6296
0
                    .tag("instance_id", instance_id_)
6297
0
                    .tag("reason", "failed to commit txn");
6298
0
            return -1;
6299
0
        }
6300
6301
20
        metrics_context.total_recycled_num = ++num_recycled;
6302
20
        metrics_context.report();
6303
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6304
20
        restore_job_keys.push_back(k);
6305
6306
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6307
20
                  << " tablet_id=" << tablet_id;
6308
20
        return 0;
6309
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
6197
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6198
41
        ++num_scanned;
6199
41
        RestoreJobCloudPB restore_job_pb;
6200
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6201
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6202
0
            return -1;
6203
0
        }
6204
41
        int64_t expiration =
6205
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6206
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6207
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6208
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6209
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6210
0
                   << " state=" << restore_job_pb.state();
6211
41
        int64_t current_time = ::time(nullptr);
6212
41
        if (current_time < expiration) { // not expired
6213
0
            return 0;
6214
0
        }
6215
41
        ++num_expired;
6216
6217
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6218
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6219
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6220
6221
41
        std::unique_ptr<Transaction> txn;
6222
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6223
41
        if (err != TxnErrorCode::TXN_OK) {
6224
0
            LOG_WARNING("failed to recycle restore job")
6225
0
                    .tag("err", err)
6226
0
                    .tag("tablet id", tablet_id)
6227
0
                    .tag("instance_id", instance_id_)
6228
0
                    .tag("reason", "failed to create txn");
6229
0
            return -1;
6230
0
        }
6231
6232
41
        std::string val;
6233
41
        err = txn->get(k, &val);
6234
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6235
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6236
0
            return 0;
6237
0
        }
6238
41
        if (err != TxnErrorCode::TXN_OK) {
6239
0
            LOG_WARNING("failed to get kv");
6240
0
            return -1;
6241
0
        }
6242
41
        restore_job_pb.Clear();
6243
41
        if (!restore_job_pb.ParseFromString(val)) {
6244
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6245
0
            return -1;
6246
0
        }
6247
6248
        // PREPARED or COMMITTED, change state to DROPPED and return
6249
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6250
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6251
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6252
0
            restore_job_pb.set_need_recycle_data(true);
6253
0
            txn->put(k, restore_job_pb.SerializeAsString());
6254
0
            err = txn->commit();
6255
0
            if (err != TxnErrorCode::TXN_OK) {
6256
0
                LOG_WARNING("failed to commit txn: {}", err);
6257
0
                return -1;
6258
0
            }
6259
0
            num_aborted++;
6260
0
            return 0;
6261
0
        }
6262
6263
        // Change state to RECYCLING
6264
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6265
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6266
21
            txn->put(k, restore_job_pb.SerializeAsString());
6267
21
            err = txn->commit();
6268
21
            if (err != TxnErrorCode::TXN_OK) {
6269
0
                LOG_WARNING("failed to commit txn: {}", err);
6270
0
                return -1;
6271
0
            }
6272
21
            return 0;
6273
21
        }
6274
6275
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6276
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6277
6278
        // Recycle all data associated with the restore job.
6279
        // This includes rowsets, segments, and related resources.
6280
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6281
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6282
0
            LOG_WARNING("failed to recycle tablet")
6283
0
                    .tag("tablet_id", tablet_id)
6284
0
                    .tag("instance_id", instance_id_);
6285
0
            return -1;
6286
0
        }
6287
6288
        // delete all restore job rowset kv
6289
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6290
6291
20
        err = txn->commit();
6292
20
        if (err != TxnErrorCode::TXN_OK) {
6293
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6294
0
                    .tag("err", err)
6295
0
                    .tag("tablet id", tablet_id)
6296
0
                    .tag("instance_id", instance_id_)
6297
0
                    .tag("reason", "failed to commit txn");
6298
0
            return -1;
6299
0
        }
6300
6301
20
        metrics_context.total_recycled_num = ++num_recycled;
6302
20
        metrics_context.report();
6303
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6304
20
        restore_job_keys.push_back(k);
6305
6306
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6307
20
                  << " tablet_id=" << tablet_id;
6308
20
        return 0;
6309
20
    };
6310
6311
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6312
3
        if (restore_job_keys.empty()) return 0;
6313
1
        DORIS_CLOUD_DEFER {
6314
1
            restore_job_keys.clear();
6315
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6313
1
        DORIS_CLOUD_DEFER {
6314
1
            restore_job_keys.clear();
6315
1
        };
6316
6317
1
        std::unique_ptr<Transaction> txn;
6318
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6319
1
        if (err != TxnErrorCode::TXN_OK) {
6320
0
            LOG_WARNING("failed to recycle restore job")
6321
0
                    .tag("err", err)
6322
0
                    .tag("instance_id", instance_id_)
6323
0
                    .tag("reason", "failed to create txn");
6324
0
            return -1;
6325
0
        }
6326
20
        for (auto& k : restore_job_keys) {
6327
20
            txn->remove(k);
6328
20
        }
6329
1
        err = txn->commit();
6330
1
        if (err != TxnErrorCode::TXN_OK) {
6331
0
            LOG_WARNING("failed to recycle restore job")
6332
0
                    .tag("err", err)
6333
0
                    .tag("instance_id", instance_id_)
6334
0
                    .tag("reason", "failed to commit txn");
6335
0
            return -1;
6336
0
        }
6337
1
        return 0;
6338
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6311
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6312
3
        if (restore_job_keys.empty()) return 0;
6313
1
        DORIS_CLOUD_DEFER {
6314
1
            restore_job_keys.clear();
6315
1
        };
6316
6317
1
        std::unique_ptr<Transaction> txn;
6318
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6319
1
        if (err != TxnErrorCode::TXN_OK) {
6320
0
            LOG_WARNING("failed to recycle restore job")
6321
0
                    .tag("err", err)
6322
0
                    .tag("instance_id", instance_id_)
6323
0
                    .tag("reason", "failed to create txn");
6324
0
            return -1;
6325
0
        }
6326
20
        for (auto& k : restore_job_keys) {
6327
20
            txn->remove(k);
6328
20
        }
6329
1
        err = txn->commit();
6330
1
        if (err != TxnErrorCode::TXN_OK) {
6331
0
            LOG_WARNING("failed to recycle restore job")
6332
0
                    .tag("err", err)
6333
0
                    .tag("instance_id", instance_id_)
6334
0
                    .tag("reason", "failed to commit txn");
6335
0
            return -1;
6336
0
        }
6337
1
        return 0;
6338
1
    };
6339
6340
13
    if (config::enable_recycler_stats_metrics) {
6341
0
        scan_and_statistics_restore_jobs();
6342
0
    }
6343
6344
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6345
13
                            std::move(loop_done));
6346
13
}
6347
6348
11
int InstanceRecycler::recycle_versioned_rowsets() {
6349
11
    const std::string task_name = "recycle_rowsets";
6350
11
    int64_t num_scanned = 0;
6351
11
    int64_t num_expired = 0;
6352
11
    int64_t num_prepare = 0;
6353
11
    int64_t num_compacted = 0;
6354
11
    int64_t num_empty_rowset = 0;
6355
11
    size_t total_rowset_key_size = 0;
6356
11
    size_t total_rowset_value_size = 0;
6357
11
    size_t expired_rowset_size = 0;
6358
11
    std::atomic_long num_recycled = 0;
6359
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6360
6361
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6362
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6363
11
    std::string recyc_rs_key0;
6364
11
    std::string recyc_rs_key1;
6365
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6366
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6367
6368
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6369
6370
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6371
11
    register_recycle_task(task_name, start_time);
6372
6373
11
    DORIS_CLOUD_DEFER {
6374
11
        unregister_recycle_task(task_name);
6375
11
        int64_t cost =
6376
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6377
11
        metrics_context.finish_report();
6378
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6379
11
                .tag("instance_id", instance_id_)
6380
11
                .tag("num_scanned", num_scanned)
6381
11
                .tag("num_expired", num_expired)
6382
11
                .tag("num_recycled", num_recycled)
6383
11
                .tag("num_recycled.prepare", num_prepare)
6384
11
                .tag("num_recycled.compacted", num_compacted)
6385
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6386
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6387
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6388
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6389
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6373
11
    DORIS_CLOUD_DEFER {
6374
11
        unregister_recycle_task(task_name);
6375
11
        int64_t cost =
6376
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6377
11
        metrics_context.finish_report();
6378
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6379
11
                .tag("instance_id", instance_id_)
6380
11
                .tag("num_scanned", num_scanned)
6381
11
                .tag("num_expired", num_expired)
6382
11
                .tag("num_recycled", num_recycled)
6383
11
                .tag("num_recycled.prepare", num_prepare)
6384
11
                .tag("num_recycled.compacted", num_compacted)
6385
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6386
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6387
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6388
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6389
11
    };
6390
6391
11
    std::vector<std::string> orphan_rowset_keys;
6392
6393
    // Store keys of rowset recycled by background workers
6394
11
    std::mutex async_recycled_rowset_keys_mutex;
6395
11
    std::vector<std::string> async_recycled_rowset_keys;
6396
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6397
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6398
11
    worker_pool->start();
6399
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6400
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6401
        // Try to delete rowset data in background thread
6402
400
        int ret = worker_pool->submit_with_timeout(
6403
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6404
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6405
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6406
400
                        return;
6407
400
                    }
6408
                    // The async recycled rowsets are staled format or has not been used,
6409
                    // so we don't need to check the rowset ref count key.
6410
0
                    std::vector<std::string> keys;
6411
0
                    {
6412
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6413
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6414
0
                        if (async_recycled_rowset_keys.size() > 100) {
6415
0
                            keys.swap(async_recycled_rowset_keys);
6416
0
                        }
6417
0
                    }
6418
0
                    if (keys.empty()) return;
6419
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6420
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6421
0
                                     << instance_id_;
6422
0
                    } else {
6423
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6424
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6425
0
                                           num_recycled, start_time);
6426
0
                    }
6427
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
6403
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6404
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6405
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6406
400
                        return;
6407
400
                    }
6408
                    // The async recycled rowsets are staled format or has not been used,
6409
                    // so we don't need to check the rowset ref count key.
6410
0
                    std::vector<std::string> keys;
6411
0
                    {
6412
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6413
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6414
0
                        if (async_recycled_rowset_keys.size() > 100) {
6415
0
                            keys.swap(async_recycled_rowset_keys);
6416
0
                        }
6417
0
                    }
6418
0
                    if (keys.empty()) return;
6419
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6420
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6421
0
                                     << instance_id_;
6422
0
                    } else {
6423
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6424
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6425
0
                                           num_recycled, start_time);
6426
0
                    }
6427
0
                },
6428
400
                0);
6429
400
        if (ret == 0) return 0;
6430
        // Submit task failed, delete rowset data in current thread
6431
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6432
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6433
0
            return -1;
6434
0
        }
6435
0
        orphan_rowset_keys.push_back(std::move(key));
6436
0
        return 0;
6437
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
6400
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6401
        // Try to delete rowset data in background thread
6402
400
        int ret = worker_pool->submit_with_timeout(
6403
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6404
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6405
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6406
400
                        return;
6407
400
                    }
6408
                    // The async recycled rowsets are staled format or has not been used,
6409
                    // so we don't need to check the rowset ref count key.
6410
400
                    std::vector<std::string> keys;
6411
400
                    {
6412
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6413
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6414
400
                        if (async_recycled_rowset_keys.size() > 100) {
6415
400
                            keys.swap(async_recycled_rowset_keys);
6416
400
                        }
6417
400
                    }
6418
400
                    if (keys.empty()) return;
6419
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6420
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6421
400
                                     << instance_id_;
6422
400
                    } else {
6423
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6424
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6425
400
                                           num_recycled, start_time);
6426
400
                    }
6427
400
                },
6428
400
                0);
6429
400
        if (ret == 0) return 0;
6430
        // Submit task failed, delete rowset data in current thread
6431
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6432
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6433
0
            return -1;
6434
0
        }
6435
0
        orphan_rowset_keys.push_back(std::move(key));
6436
0
        return 0;
6437
0
    };
6438
6439
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6440
6441
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6442
2.01k
        ++num_scanned;
6443
2.01k
        total_rowset_key_size += k.size();
6444
2.01k
        total_rowset_value_size += v.size();
6445
2.01k
        RecycleRowsetPB rowset;
6446
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6447
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6448
0
            return -1;
6449
0
        }
6450
6451
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6452
6453
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6454
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6455
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6456
2.01k
        int64_t current_time = ::time(nullptr);
6457
2.01k
        if (current_time < final_expiration) { // not expired
6458
0
            return 0;
6459
0
        }
6460
2.01k
        ++num_expired;
6461
2.01k
        expired_rowset_size += v.size();
6462
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6463
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6464
                // in old version, keep this key-value pair and it needs to be checked manually
6465
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6466
0
                return -1;
6467
0
            }
6468
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6469
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6470
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6471
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6472
0
                orphan_rowset_keys.emplace_back(k);
6473
0
                return -1;
6474
0
            }
6475
            // decode rowset_id
6476
0
            auto k1 = k;
6477
0
            k1.remove_prefix(1);
6478
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6479
0
            decode_key(&k1, &out);
6480
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6481
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6482
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6483
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6484
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6485
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6486
0
                return -1;
6487
0
            }
6488
0
            return 0;
6489
0
        }
6490
        // TODO(plat1ko): check rowset not referenced
6491
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6492
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6493
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6494
0
                LOG_INFO("recycle rowset that has empty resource id");
6495
0
            } else {
6496
                // other situations, keep this key-value pair and it needs to be checked manually
6497
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6498
0
                return -1;
6499
0
            }
6500
0
        }
6501
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6502
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6503
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6504
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6505
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6506
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6507
2.01k
                  << " rowset_meta_size=" << v.size()
6508
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6509
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6510
            // unable to calculate file path, can only be deleted by rowset id prefix
6511
400
            num_prepare += 1;
6512
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6513
400
                                             rowset_meta->tablet_id(),
6514
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6515
0
                return -1;
6516
0
            }
6517
1.61k
        } else {
6518
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6519
1.61k
            worker_pool->submit(
6520
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6521
                        // The load & compact rowset keys are recycled during recycling operation logs.
6522
1.61k
                        RowsetDeleteTask task;
6523
1.61k
                        task.rowset_meta = rowset_meta;
6524
1.61k
                        task.recycle_rowset_key = k;
6525
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6526
1.60k
                            return;
6527
1.60k
                        }
6528
13
                        num_compacted += is_compacted;
6529
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6530
13
                        if (rowset_meta.num_segments() == 0) {
6531
0
                            ++num_empty_rowset;
6532
0
                        }
6533
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
6520
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6521
                        // The load & compact rowset keys are recycled during recycling operation logs.
6522
1.61k
                        RowsetDeleteTask task;
6523
1.61k
                        task.rowset_meta = rowset_meta;
6524
1.61k
                        task.recycle_rowset_key = k;
6525
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6526
1.60k
                            return;
6527
1.60k
                        }
6528
13
                        num_compacted += is_compacted;
6529
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6530
13
                        if (rowset_meta.num_segments() == 0) {
6531
0
                            ++num_empty_rowset;
6532
0
                        }
6533
13
                    });
6534
1.61k
        }
6535
2.01k
        return 0;
6536
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
6441
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6442
2.01k
        ++num_scanned;
6443
2.01k
        total_rowset_key_size += k.size();
6444
2.01k
        total_rowset_value_size += v.size();
6445
2.01k
        RecycleRowsetPB rowset;
6446
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6447
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6448
0
            return -1;
6449
0
        }
6450
6451
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6452
6453
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6454
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6455
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6456
2.01k
        int64_t current_time = ::time(nullptr);
6457
2.01k
        if (current_time < final_expiration) { // not expired
6458
0
            return 0;
6459
0
        }
6460
2.01k
        ++num_expired;
6461
2.01k
        expired_rowset_size += v.size();
6462
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6463
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6464
                // in old version, keep this key-value pair and it needs to be checked manually
6465
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6466
0
                return -1;
6467
0
            }
6468
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6469
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6470
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6471
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6472
0
                orphan_rowset_keys.emplace_back(k);
6473
0
                return -1;
6474
0
            }
6475
            // decode rowset_id
6476
0
            auto k1 = k;
6477
0
            k1.remove_prefix(1);
6478
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6479
0
            decode_key(&k1, &out);
6480
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6481
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6482
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6483
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6484
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6485
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6486
0
                return -1;
6487
0
            }
6488
0
            return 0;
6489
0
        }
6490
        // TODO(plat1ko): check rowset not referenced
6491
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6492
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6493
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6494
0
                LOG_INFO("recycle rowset that has empty resource id");
6495
0
            } else {
6496
                // other situations, keep this key-value pair and it needs to be checked manually
6497
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6498
0
                return -1;
6499
0
            }
6500
0
        }
6501
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6502
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6503
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6504
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6505
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6506
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6507
2.01k
                  << " rowset_meta_size=" << v.size()
6508
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6509
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6510
            // unable to calculate file path, can only be deleted by rowset id prefix
6511
400
            num_prepare += 1;
6512
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6513
400
                                             rowset_meta->tablet_id(),
6514
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6515
0
                return -1;
6516
0
            }
6517
1.61k
        } else {
6518
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6519
1.61k
            worker_pool->submit(
6520
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6521
                        // The load & compact rowset keys are recycled during recycling operation logs.
6522
1.61k
                        RowsetDeleteTask task;
6523
1.61k
                        task.rowset_meta = rowset_meta;
6524
1.61k
                        task.recycle_rowset_key = k;
6525
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6526
1.61k
                            return;
6527
1.61k
                        }
6528
1.61k
                        num_compacted += is_compacted;
6529
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6530
1.61k
                        if (rowset_meta.num_segments() == 0) {
6531
1.61k
                            ++num_empty_rowset;
6532
1.61k
                        }
6533
1.61k
                    });
6534
1.61k
        }
6535
2.01k
        return 0;
6536
2.01k
    };
6537
6538
11
    if (config::enable_recycler_stats_metrics) {
6539
0
        scan_and_statistics_rowsets();
6540
0
    }
6541
6542
11
    auto loop_done = [&]() -> int {
6543
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6544
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6545
0
        }
6546
6
        orphan_rowset_keys.clear();
6547
6
        return 0;
6548
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6542
6
    auto loop_done = [&]() -> int {
6543
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6544
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6545
0
        }
6546
6
        orphan_rowset_keys.clear();
6547
6
        return 0;
6548
6
    };
6549
6550
    // recycle_func and loop_done for scan and recycle
6551
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6552
11
                               std::move(loop_done));
6553
6554
11
    worker_pool->stop();
6555
6556
11
    if (!async_recycled_rowset_keys.empty()) {
6557
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6558
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6559
0
            return -1;
6560
0
        } else {
6561
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6562
0
        }
6563
0
    }
6564
6565
    // Report final metrics after all concurrent tasks completed
6566
11
    segment_metrics_context_.report();
6567
11
    metrics_context.report();
6568
6569
11
    return ret;
6570
11
}
6571
6572
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6573
1.61k
    constexpr int MAX_RETRY = 10;
6574
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6575
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6576
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6577
1.61k
    std::string_view reference_instance_id = instance_id_;
6578
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6579
8
        reference_instance_id = rowset_meta.reference_instance_id();
6580
8
    }
6581
6582
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6583
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6584
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6585
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6586
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6587
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6588
1.61k
        std::unique_ptr<Transaction> txn;
6589
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6590
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6591
0
            LOG_WARNING("failed to create txn").tag("err", err);
6592
0
            return -1;
6593
0
        }
6594
6595
1.61k
        std::string rowset_ref_count_key =
6596
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6597
1.61k
        int64_t ref_count = 0;
6598
1.61k
        {
6599
1.61k
            std::string value;
6600
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6601
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6602
                // This is the old version rowset, we could recycle it directly.
6603
1.60k
                ref_count = 1;
6604
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6605
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6606
0
                return -1;
6607
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6608
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6609
0
                return -1;
6610
0
            }
6611
1.61k
        }
6612
6613
1.61k
        if (ref_count == 1) {
6614
            // It would not be added since it is recycling.
6615
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6616
1.60k
                LOG_WARNING("failed to delete rowset data");
6617
1.60k
                return -1;
6618
1.60k
            }
6619
6620
            // Reset the transaction to avoid timeout.
6621
10
            err = txn_kv_->create_txn(&txn);
6622
10
            if (err != TxnErrorCode::TXN_OK) {
6623
0
                LOG_WARNING("failed to create txn").tag("err", err);
6624
0
                return -1;
6625
0
            }
6626
10
            txn->remove(rowset_ref_count_key);
6627
10
            LOG_INFO("delete rowset data ref count key")
6628
10
                    .tag("txn_id", rowset_meta.txn_id())
6629
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6630
6631
10
            std::string dbm_start_key =
6632
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6633
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6634
10
                    {reference_instance_id, tablet_id, rowset_id,
6635
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6636
10
            txn->remove(dbm_start_key, dbm_end_key);
6637
10
            LOG_INFO("remove delete bitmap kv")
6638
10
                    .tag("begin", hex(dbm_start_key))
6639
10
                    .tag("end", hex(dbm_end_key));
6640
6641
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6642
10
                    {reference_instance_id, tablet_id, rowset_id});
6643
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6644
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6645
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6646
10
            LOG_INFO("remove versioned delete bitmap kv")
6647
10
                    .tag("begin", hex(versioned_dbm_start_key))
6648
10
                    .tag("end", hex(versioned_dbm_end_key));
6649
10
        } else {
6650
            // Decrease the rowset ref count.
6651
            //
6652
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6653
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6654
3
            txn->atomic_add(rowset_ref_count_key, -1);
6655
3
            LOG_INFO("decrease rowset data ref count")
6656
3
                    .tag("txn_id", rowset_meta.txn_id())
6657
3
                    .tag("ref_count", ref_count - 1)
6658
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6659
3
        }
6660
6661
13
        if (!task.versioned_rowset_key.empty()) {
6662
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6663
0
                                                          task.versionstamp);
6664
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6665
0
        }
6666
6667
13
        if (!task.non_versioned_rowset_key.empty()) {
6668
0
            txn->remove(task.non_versioned_rowset_key);
6669
0
            LOG_INFO("remove non versioned rowset key")
6670
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6671
0
        }
6672
6673
        // empty when recycle ref rowsets for deleted instance
6674
13
        if (!task.recycle_rowset_key.empty()) {
6675
13
            txn->remove(task.recycle_rowset_key);
6676
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6677
13
        }
6678
6679
13
        err = txn->commit();
6680
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6681
            // The rowset ref count key has been changed, we need to retry.
6682
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6683
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6684
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6685
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6686
0
            continue;
6687
13
        } else if (err != TxnErrorCode::TXN_OK) {
6688
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6689
0
            return -1;
6690
0
        }
6691
13
        LOG_INFO("recycle rowset meta and data success");
6692
13
        return 0;
6693
13
    }
6694
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6695
0
            .tag("tablet_id", tablet_id)
6696
0
            .tag("rowset_id", rowset_id)
6697
0
            .tag("retry", MAX_RETRY);
6698
0
    return -1;
6699
1.61k
}
6700
6701
37
int InstanceRecycler::recycle_tmp_rowsets() {
6702
37
    const std::string task_name = "recycle_tmp_rowsets";
6703
37
    int64_t num_scanned = 0;
6704
37
    int64_t num_expired = 0;
6705
37
    std::atomic_long num_recycled = 0;
6706
37
    size_t expired_rowset_size = 0;
6707
37
    size_t total_rowset_key_size = 0;
6708
37
    size_t total_rowset_value_size = 0;
6709
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6710
6711
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6712
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6713
37
    std::string tmp_rs_key0;
6714
37
    std::string tmp_rs_key1;
6715
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6716
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6717
6718
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6719
6720
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6721
37
    register_recycle_task(task_name, start_time);
6722
6723
37
    DORIS_CLOUD_DEFER {
6724
37
        unregister_recycle_task(task_name);
6725
37
        int64_t cost =
6726
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6727
37
        metrics_context.finish_report();
6728
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6729
37
                .tag("instance_id", instance_id_)
6730
37
                .tag("num_scanned", num_scanned)
6731
37
                .tag("num_expired", num_expired)
6732
37
                .tag("num_recycled", num_recycled)
6733
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6734
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6735
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6736
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6723
12
    DORIS_CLOUD_DEFER {
6724
12
        unregister_recycle_task(task_name);
6725
12
        int64_t cost =
6726
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6727
12
        metrics_context.finish_report();
6728
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6729
12
                .tag("instance_id", instance_id_)
6730
12
                .tag("num_scanned", num_scanned)
6731
12
                .tag("num_expired", num_expired)
6732
12
                .tag("num_recycled", num_recycled)
6733
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6734
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6735
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6736
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6723
25
    DORIS_CLOUD_DEFER {
6724
25
        unregister_recycle_task(task_name);
6725
25
        int64_t cost =
6726
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6727
25
        metrics_context.finish_report();
6728
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6729
25
                .tag("instance_id", instance_id_)
6730
25
                .tag("num_scanned", num_scanned)
6731
25
                .tag("num_expired", num_expired)
6732
25
                .tag("num_recycled", num_recycled)
6733
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6734
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6735
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6736
25
    };
6737
6738
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6739
37
    std::vector<std::string> tmp_rowset_keys;
6740
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6741
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6742
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6743
6744
    // rowset_id -> rowset_meta
6745
    // store tmp_rowset id and meta for statistics rs size when delete
6746
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6747
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6748
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6749
37
    worker_pool->start();
6750
6751
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6752
6753
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6754
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6755
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6756
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6757
53.2k
                                    std::string_view k, std::string_view v) -> int {
6758
53.2k
        ++num_scanned;
6759
53.2k
        total_rowset_key_size += k.size();
6760
53.2k
        total_rowset_value_size += v.size();
6761
53.2k
        doris::RowsetMetaCloudPB rowset;
6762
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6763
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6764
0
            return -1;
6765
0
        }
6766
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6767
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6768
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6769
0
                   << " txn_expiration=" << rowset.txn_expiration()
6770
0
                   << " rowset_creation_time=" << rowset.creation_time();
6771
53.2k
        int64_t current_time = ::time(nullptr);
6772
53.2k
        if (current_time < expiration) { // not expired
6773
0
            return 0;
6774
0
        }
6775
53.2k
        ++num_expired;
6776
53.2k
        expired_rowset_size += v.size();
6777
53.2k
        if (!rowset.has_resource_id()) {
6778
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6779
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6780
0
                return -1;
6781
0
            }
6782
            // might be a delete pred rowset
6783
0
            tmp_rowset_keys.emplace_back(k);
6784
0
            return 0;
6785
0
        }
6786
6787
        // TODO(plat1ko): check rowset not referenced
6788
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6789
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6790
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6791
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6792
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6793
53.2k
                  << " num_expired=" << num_expired
6794
53.2k
                  << " task_type=" << metrics_context.operation_type;
6795
6796
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6797
16
            if (need_mark_rowset_as_recycled(rowset)) {
6798
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6799
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6800
9
                             "at next turn, instance_id="
6801
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6802
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6803
9
                return 0;
6804
9
            }
6805
16
        }
6806
6807
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6808
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6809
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6810
261
                             "instance_id="
6811
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6812
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6813
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6814
261
                return 0;
6815
261
            }
6816
265
        }
6817
6818
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6819
        // Remove the rowset ref count key directly since it has not been used.
6820
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6821
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6822
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6823
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6824
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6825
6826
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6827
53.0k
        return 0;
6828
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6757
16
                                    std::string_view k, std::string_view v) -> int {
6758
16
        ++num_scanned;
6759
16
        total_rowset_key_size += k.size();
6760
16
        total_rowset_value_size += v.size();
6761
16
        doris::RowsetMetaCloudPB rowset;
6762
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6763
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6764
0
            return -1;
6765
0
        }
6766
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6767
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6768
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6769
0
                   << " txn_expiration=" << rowset.txn_expiration()
6770
0
                   << " rowset_creation_time=" << rowset.creation_time();
6771
16
        int64_t current_time = ::time(nullptr);
6772
16
        if (current_time < expiration) { // not expired
6773
0
            return 0;
6774
0
        }
6775
16
        ++num_expired;
6776
16
        expired_rowset_size += v.size();
6777
16
        if (!rowset.has_resource_id()) {
6778
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6779
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6780
0
                return -1;
6781
0
            }
6782
            // might be a delete pred rowset
6783
0
            tmp_rowset_keys.emplace_back(k);
6784
0
            return 0;
6785
0
        }
6786
6787
        // TODO(plat1ko): check rowset not referenced
6788
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6789
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6790
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6791
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6792
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6793
16
                  << " num_expired=" << num_expired
6794
16
                  << " task_type=" << metrics_context.operation_type;
6795
6796
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6797
16
            if (need_mark_rowset_as_recycled(rowset)) {
6798
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6799
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6800
9
                             "at next turn, instance_id="
6801
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6802
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6803
9
                return 0;
6804
9
            }
6805
16
        }
6806
6807
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6808
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6809
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6810
3
                             "instance_id="
6811
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6812
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6813
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6814
3
                return 0;
6815
3
            }
6816
7
        }
6817
6818
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6819
        // Remove the rowset ref count key directly since it has not been used.
6820
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6821
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6822
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6823
4
                  << "key=" << hex(rowset_ref_count_key);
6824
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6825
6826
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6827
4
        return 0;
6828
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6757
53.2k
                                    std::string_view k, std::string_view v) -> int {
6758
53.2k
        ++num_scanned;
6759
53.2k
        total_rowset_key_size += k.size();
6760
53.2k
        total_rowset_value_size += v.size();
6761
53.2k
        doris::RowsetMetaCloudPB rowset;
6762
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6763
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6764
0
            return -1;
6765
0
        }
6766
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6767
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6768
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6769
0
                   << " txn_expiration=" << rowset.txn_expiration()
6770
0
                   << " rowset_creation_time=" << rowset.creation_time();
6771
53.2k
        int64_t current_time = ::time(nullptr);
6772
53.2k
        if (current_time < expiration) { // not expired
6773
0
            return 0;
6774
0
        }
6775
53.2k
        ++num_expired;
6776
53.2k
        expired_rowset_size += v.size();
6777
53.2k
        if (!rowset.has_resource_id()) {
6778
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6779
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6780
0
                return -1;
6781
0
            }
6782
            // might be a delete pred rowset
6783
0
            tmp_rowset_keys.emplace_back(k);
6784
0
            return 0;
6785
0
        }
6786
6787
        // TODO(plat1ko): check rowset not referenced
6788
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6789
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6790
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6791
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6792
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6793
53.2k
                  << " num_expired=" << num_expired
6794
53.2k
                  << " task_type=" << metrics_context.operation_type;
6795
6796
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6797
0
            if (need_mark_rowset_as_recycled(rowset)) {
6798
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6799
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6800
0
                             "at next turn, instance_id="
6801
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6802
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6803
0
                return 0;
6804
0
            }
6805
0
        }
6806
6807
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6808
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6809
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6810
258
                             "instance_id="
6811
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6812
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6813
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6814
258
                return 0;
6815
258
            }
6816
258
        }
6817
6818
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6819
        // Remove the rowset ref count key directly since it has not been used.
6820
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6821
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6822
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6823
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6824
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6825
6826
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6827
53.0k
        return 0;
6828
53.2k
    };
6829
6830
37
    auto loop_done = [&]() -> int {
6831
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6832
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6833
24
        std::vector<std::string> mark_keys_to_process;
6834
24
        std::vector<std::string> abort_keys_to_process;
6835
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6836
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6837
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6838
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6839
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6840
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6841
24
        if (!mark_keys_to_process.empty()) {
6842
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6843
7
                    *worker_pool, std::move(mark_keys_to_process));
6844
7
        }
6845
24
        if (!abort_keys_to_process.empty()) {
6846
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6847
5
                                           &num_recycled, &metrics_context);
6848
5
        }
6849
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6850
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6851
24
                             tmp_rowset_ref_count_keys_to_delete =
6852
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6853
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6854
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6855
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6856
24
                                   metrics_context) != 0) {
6857
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6858
2
                return;
6859
2
            }
6860
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6861
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6862
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6863
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6864
0
                                 << rs.ShortDebugString();
6865
0
                    return;
6866
0
                }
6867
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6868
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6869
0
                                 << rs.ShortDebugString();
6870
0
                    return;
6871
0
                }
6872
51.0k
            }
6873
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6874
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6875
0
                return;
6876
0
            }
6877
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6878
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6879
0
                return;
6880
0
            }
6881
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6882
22
            return;
6883
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6854
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6855
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6856
12
                                   metrics_context) != 0) {
6857
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6858
0
                return;
6859
0
            }
6860
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6861
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6862
4
                                                       rs.rowset_id_v2()) != 0) {
6863
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6864
0
                                 << rs.ShortDebugString();
6865
0
                    return;
6866
0
                }
6867
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6868
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6869
0
                                 << rs.ShortDebugString();
6870
0
                    return;
6871
0
                }
6872
4
            }
6873
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6874
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6875
0
                return;
6876
0
            }
6877
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6878
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6879
0
                return;
6880
0
            }
6881
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6882
12
            return;
6883
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6854
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6855
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6856
12
                                   metrics_context) != 0) {
6857
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6858
2
                return;
6859
2
            }
6860
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6861
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6862
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6863
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6864
0
                                 << rs.ShortDebugString();
6865
0
                    return;
6866
0
                }
6867
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6868
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6869
0
                                 << rs.ShortDebugString();
6870
0
                    return;
6871
0
                }
6872
51.0k
            }
6873
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6874
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6875
0
                return;
6876
0
            }
6877
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6878
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6879
0
                return;
6880
0
            }
6881
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6882
10
            return;
6883
10
        });
6884
24
        return 0;
6885
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6830
12
    auto loop_done = [&]() -> int {
6831
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6832
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6833
12
        std::vector<std::string> mark_keys_to_process;
6834
12
        std::vector<std::string> abort_keys_to_process;
6835
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6836
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6837
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6838
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6839
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6840
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6841
12
        if (!mark_keys_to_process.empty()) {
6842
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6843
7
                    *worker_pool, std::move(mark_keys_to_process));
6844
7
        }
6845
12
        if (!abort_keys_to_process.empty()) {
6846
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6847
3
                                           &num_recycled, &metrics_context);
6848
3
        }
6849
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6850
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6851
12
                             tmp_rowset_ref_count_keys_to_delete =
6852
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6853
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6854
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6855
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6856
12
                                   metrics_context) != 0) {
6857
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6858
12
                return;
6859
12
            }
6860
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6861
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6862
12
                                                       rs.rowset_id_v2()) != 0) {
6863
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6864
12
                                 << rs.ShortDebugString();
6865
12
                    return;
6866
12
                }
6867
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6868
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6869
12
                                 << rs.ShortDebugString();
6870
12
                    return;
6871
12
                }
6872
12
            }
6873
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6874
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6875
12
                return;
6876
12
            }
6877
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6878
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6879
12
                return;
6880
12
            }
6881
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6882
12
            return;
6883
12
        });
6884
12
        return 0;
6885
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6830
12
    auto loop_done = [&]() -> int {
6831
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6832
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6833
12
        std::vector<std::string> mark_keys_to_process;
6834
12
        std::vector<std::string> abort_keys_to_process;
6835
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6836
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6837
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6838
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6839
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6840
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6841
12
        if (!mark_keys_to_process.empty()) {
6842
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6843
0
                    *worker_pool, std::move(mark_keys_to_process));
6844
0
        }
6845
12
        if (!abort_keys_to_process.empty()) {
6846
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6847
2
                                           &num_recycled, &metrics_context);
6848
2
        }
6849
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6850
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6851
12
                             tmp_rowset_ref_count_keys_to_delete =
6852
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6853
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6854
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6855
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6856
12
                                   metrics_context) != 0) {
6857
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6858
12
                return;
6859
12
            }
6860
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6861
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6862
12
                                                       rs.rowset_id_v2()) != 0) {
6863
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6864
12
                                 << rs.ShortDebugString();
6865
12
                    return;
6866
12
                }
6867
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6868
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6869
12
                                 << rs.ShortDebugString();
6870
12
                    return;
6871
12
                }
6872
12
            }
6873
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6874
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6875
12
                return;
6876
12
            }
6877
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6878
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6879
12
                return;
6880
12
            }
6881
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6882
12
            return;
6883
12
        });
6884
12
        return 0;
6885
12
    };
6886
6887
37
    if (config::enable_recycler_stats_metrics) {
6888
0
        scan_and_statistics_tmp_rowsets();
6889
0
    }
6890
    // recycle_func and loop_done for scan and recycle
6891
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6892
37
                               std::move(loop_done));
6893
6894
37
    worker_pool->stop();
6895
6896
    // Report final metrics after all concurrent tasks completed
6897
37
    segment_metrics_context_.report();
6898
37
    metrics_context.report();
6899
6900
37
    return ret;
6901
37
}
6902
6903
int InstanceRecycler::scan_and_recycle(
6904
        std::string begin, std::string_view end,
6905
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6906
369
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6907
369
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6908
369
    int ret = 0;
6909
369
    int64_t cnt = 0;
6910
369
    int get_range_retried = 0;
6911
369
    std::string err;
6912
369
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6913
369
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6914
369
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6915
369
                  << " ret=" << ret << " err=" << err;
6916
369
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6912
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6913
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6914
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6915
39
                  << " ret=" << ret << " err=" << err;
6916
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6912
330
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6913
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6914
330
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6915
330
                  << " ret=" << ret << " err=" << err;
6916
330
    };
6917
6918
369
    std::unique_ptr<RangeGetIterator> it;
6919
593
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6920
408
        if (get_range_retried > 1000) {
6921
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6922
0
            ret = -3;
6923
0
            return ret;
6924
0
        }
6925
408
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6926
408
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6927
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6928
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6929
0
                         << " get_range_retried=" << get_range_retried;
6930
0
            ++get_range_retried;
6931
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6932
0
            continue; // try again
6933
0
        }
6934
408
        if (!it->has_next()) {
6935
184
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6936
184
            break; // scan finished
6937
184
        }
6938
224
        bool begin_updated = false;
6939
224
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6940
224
                  << ") iterator->size()=" << it->size();
6941
138k
        while (it->has_next()) {
6942
138k
            ++cnt;
6943
            // recycle corresponding resources
6944
138k
            auto [k, v] = it->next();
6945
138k
            if (!it->has_next()) {
6946
218
                begin = k;
6947
218
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6948
218
            }
6949
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6950
138k
            if (recycle_func(k, v) != 0) {
6951
4.00k
                err = "recycle_func error";
6952
4.00k
                ret = -1;
6953
4.00k
            }
6954
138k
            if (next_begin_getter) {
6955
4.33k
                std::string next_begin;
6956
4.33k
                if (next_begin_getter(&next_begin)) {
6957
7
                    if (next_begin > k) {
6958
7
                        begin = std::move(next_begin);
6959
7
                        begin_updated = true;
6960
7
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6961
0
                                   << " after key=" << hex(k);
6962
7
                        break;
6963
7
                    }
6964
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6965
0
                            .tag("next_begin", hex(next_begin))
6966
0
                            .tag("current_key", hex(k));
6967
0
                }
6968
4.33k
            }
6969
138k
        }
6970
224
        if (!begin_updated) {
6971
217
            begin.push_back('\x00'); // Update to next smallest key for iteration
6972
217
        } else {
6973
7
            it.reset();
6974
7
        }
6975
6976
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6977
        // if we want to continue scanning, the recycle_func should not return non-zero
6978
224
        if (loop_done && loop_done() != 0) {
6979
8
            err = "loop_done error";
6980
8
            ret = -1;
6981
8
        }
6982
224
    }
6983
369
    return ret;
6984
369
}
6985
6986
19
int InstanceRecycler::abort_timeout_txn() {
6987
19
    const std::string task_name = "abort_timeout_txn";
6988
19
    int64_t num_scanned = 0;
6989
19
    int64_t num_timeout = 0;
6990
19
    int64_t num_abort = 0;
6991
19
    int64_t num_advance = 0;
6992
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6993
6994
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6995
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6996
19
    std::string begin_txn_running_key;
6997
19
    std::string end_txn_running_key;
6998
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6999
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7000
7001
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
7002
7003
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7004
19
    register_recycle_task(task_name, start_time);
7005
7006
19
    DORIS_CLOUD_DEFER {
7007
19
        unregister_recycle_task(task_name);
7008
19
        int64_t cost =
7009
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7010
19
        metrics_context.finish_report();
7011
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
7012
19
                .tag("instance_id", instance_id_)
7013
19
                .tag("num_scanned", num_scanned)
7014
19
                .tag("num_timeout", num_timeout)
7015
19
                .tag("num_abort", num_abort)
7016
19
                .tag("num_advance", num_advance);
7017
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
7006
3
    DORIS_CLOUD_DEFER {
7007
3
        unregister_recycle_task(task_name);
7008
3
        int64_t cost =
7009
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7010
3
        metrics_context.finish_report();
7011
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
7012
3
                .tag("instance_id", instance_id_)
7013
3
                .tag("num_scanned", num_scanned)
7014
3
                .tag("num_timeout", num_timeout)
7015
3
                .tag("num_abort", num_abort)
7016
3
                .tag("num_advance", num_advance);
7017
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
7006
16
    DORIS_CLOUD_DEFER {
7007
16
        unregister_recycle_task(task_name);
7008
16
        int64_t cost =
7009
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7010
16
        metrics_context.finish_report();
7011
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
7012
16
                .tag("instance_id", instance_id_)
7013
16
                .tag("num_scanned", num_scanned)
7014
16
                .tag("num_timeout", num_timeout)
7015
16
                .tag("num_abort", num_abort)
7016
16
                .tag("num_advance", num_advance);
7017
16
    };
7018
7019
19
    int64_t current_time =
7020
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7021
7022
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
7023
19
                                  &current_time, &metrics_context,
7024
19
                                  this](std::string_view k, std::string_view v) -> int {
7025
9
        ++num_scanned;
7026
7027
9
        std::unique_ptr<Transaction> txn;
7028
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7029
9
        if (err != TxnErrorCode::TXN_OK) {
7030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7031
0
            return -1;
7032
0
        }
7033
9
        std::string_view k1 = k;
7034
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
7035
9
        k1.remove_prefix(1); // Remove key space
7036
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7037
9
        if (decode_key(&k1, &out) != 0) {
7038
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
7039
0
            return -1;
7040
0
        }
7041
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7042
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7043
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7044
        // Update txn_info
7045
9
        std::string txn_inf_key, txn_inf_val;
7046
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7047
9
        err = txn->get(txn_inf_key, &txn_inf_val);
7048
9
        if (err != TxnErrorCode::TXN_OK) {
7049
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
7050
0
            return -1;
7051
0
        }
7052
9
        TxnInfoPB txn_info;
7053
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
7054
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
7055
0
            return -1;
7056
0
        }
7057
7058
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
7059
3
            txn.reset();
7060
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
7061
3
            std::shared_ptr<TxnLazyCommitTask> task =
7062
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
7063
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
7064
3
            if (ret.first != MetaServiceCode::OK) {
7065
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7066
0
                             << "msg=" << ret.second;
7067
0
                return -1;
7068
0
            }
7069
3
            ++num_advance;
7070
3
            return 0;
7071
6
        } else {
7072
6
            TxnRunningPB txn_running_pb;
7073
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7074
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7075
0
                return -1;
7076
0
            }
7077
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7078
4
                return 0;
7079
4
            }
7080
2
            ++num_timeout;
7081
7082
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7083
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7084
2
            txn_info.set_finish_time(current_time);
7085
2
            txn_info.set_reason("timeout");
7086
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7087
2
            txn_inf_val.clear();
7088
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7089
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7090
0
                return -1;
7091
0
            }
7092
2
            txn->put(txn_inf_key, txn_inf_val);
7093
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7094
            // Put recycle txn key
7095
2
            std::string recyc_txn_key, recyc_txn_val;
7096
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7097
2
            RecycleTxnPB recycle_txn_pb;
7098
2
            recycle_txn_pb.set_creation_time(current_time);
7099
2
            recycle_txn_pb.set_label(txn_info.label());
7100
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7101
0
                LOG_WARNING("failed to serialize txn recycle info")
7102
0
                        .tag("key", hex(k))
7103
0
                        .tag("db_id", db_id)
7104
0
                        .tag("txn_id", txn_id);
7105
0
                return -1;
7106
0
            }
7107
2
            txn->put(recyc_txn_key, recyc_txn_val);
7108
            // Remove txn running key
7109
2
            txn->remove(k);
7110
2
            err = txn->commit();
7111
2
            if (err != TxnErrorCode::TXN_OK) {
7112
0
                LOG_WARNING("failed to commit txn err={}", err)
7113
0
                        .tag("key", hex(k))
7114
0
                        .tag("db_id", db_id)
7115
0
                        .tag("txn_id", txn_id);
7116
0
                return -1;
7117
0
            }
7118
2
            metrics_context.total_recycled_num = ++num_abort;
7119
2
            metrics_context.report();
7120
2
        }
7121
7122
2
        return 0;
7123
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7024
3
                                  this](std::string_view k, std::string_view v) -> int {
7025
3
        ++num_scanned;
7026
7027
3
        std::unique_ptr<Transaction> txn;
7028
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7029
3
        if (err != TxnErrorCode::TXN_OK) {
7030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7031
0
            return -1;
7032
0
        }
7033
3
        std::string_view k1 = k;
7034
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
7035
3
        k1.remove_prefix(1); // Remove key space
7036
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7037
3
        if (decode_key(&k1, &out) != 0) {
7038
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
7039
0
            return -1;
7040
0
        }
7041
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7042
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7043
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7044
        // Update txn_info
7045
3
        std::string txn_inf_key, txn_inf_val;
7046
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7047
3
        err = txn->get(txn_inf_key, &txn_inf_val);
7048
3
        if (err != TxnErrorCode::TXN_OK) {
7049
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
7050
0
            return -1;
7051
0
        }
7052
3
        TxnInfoPB txn_info;
7053
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
7054
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
7055
0
            return -1;
7056
0
        }
7057
7058
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
7059
3
            txn.reset();
7060
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
7061
3
            std::shared_ptr<TxnLazyCommitTask> task =
7062
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
7063
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
7064
3
            if (ret.first != MetaServiceCode::OK) {
7065
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7066
0
                             << "msg=" << ret.second;
7067
0
                return -1;
7068
0
            }
7069
3
            ++num_advance;
7070
3
            return 0;
7071
3
        } else {
7072
0
            TxnRunningPB txn_running_pb;
7073
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7074
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7075
0
                return -1;
7076
0
            }
7077
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7078
0
                return 0;
7079
0
            }
7080
0
            ++num_timeout;
7081
7082
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7083
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7084
0
            txn_info.set_finish_time(current_time);
7085
0
            txn_info.set_reason("timeout");
7086
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7087
0
            txn_inf_val.clear();
7088
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7089
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7090
0
                return -1;
7091
0
            }
7092
0
            txn->put(txn_inf_key, txn_inf_val);
7093
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7094
            // Put recycle txn key
7095
0
            std::string recyc_txn_key, recyc_txn_val;
7096
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7097
0
            RecycleTxnPB recycle_txn_pb;
7098
0
            recycle_txn_pb.set_creation_time(current_time);
7099
0
            recycle_txn_pb.set_label(txn_info.label());
7100
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7101
0
                LOG_WARNING("failed to serialize txn recycle info")
7102
0
                        .tag("key", hex(k))
7103
0
                        .tag("db_id", db_id)
7104
0
                        .tag("txn_id", txn_id);
7105
0
                return -1;
7106
0
            }
7107
0
            txn->put(recyc_txn_key, recyc_txn_val);
7108
            // Remove txn running key
7109
0
            txn->remove(k);
7110
0
            err = txn->commit();
7111
0
            if (err != TxnErrorCode::TXN_OK) {
7112
0
                LOG_WARNING("failed to commit txn err={}", err)
7113
0
                        .tag("key", hex(k))
7114
0
                        .tag("db_id", db_id)
7115
0
                        .tag("txn_id", txn_id);
7116
0
                return -1;
7117
0
            }
7118
0
            metrics_context.total_recycled_num = ++num_abort;
7119
0
            metrics_context.report();
7120
0
        }
7121
7122
0
        return 0;
7123
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7024
6
                                  this](std::string_view k, std::string_view v) -> int {
7025
6
        ++num_scanned;
7026
7027
6
        std::unique_ptr<Transaction> txn;
7028
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7029
6
        if (err != TxnErrorCode::TXN_OK) {
7030
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7031
0
            return -1;
7032
0
        }
7033
6
        std::string_view k1 = k;
7034
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
7035
6
        k1.remove_prefix(1); // Remove key space
7036
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7037
6
        if (decode_key(&k1, &out) != 0) {
7038
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
7039
0
            return -1;
7040
0
        }
7041
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7042
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7043
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7044
        // Update txn_info
7045
6
        std::string txn_inf_key, txn_inf_val;
7046
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7047
6
        err = txn->get(txn_inf_key, &txn_inf_val);
7048
6
        if (err != TxnErrorCode::TXN_OK) {
7049
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
7050
0
            return -1;
7051
0
        }
7052
6
        TxnInfoPB txn_info;
7053
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
7054
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
7055
0
            return -1;
7056
0
        }
7057
7058
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
7059
0
            txn.reset();
7060
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
7061
0
            std::shared_ptr<TxnLazyCommitTask> task =
7062
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
7063
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
7064
0
            if (ret.first != MetaServiceCode::OK) {
7065
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
7066
0
                             << "msg=" << ret.second;
7067
0
                return -1;
7068
0
            }
7069
0
            ++num_advance;
7070
0
            return 0;
7071
6
        } else {
7072
6
            TxnRunningPB txn_running_pb;
7073
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7074
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7075
0
                return -1;
7076
0
            }
7077
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7078
4
                return 0;
7079
4
            }
7080
2
            ++num_timeout;
7081
7082
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7083
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7084
2
            txn_info.set_finish_time(current_time);
7085
2
            txn_info.set_reason("timeout");
7086
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7087
2
            txn_inf_val.clear();
7088
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7089
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7090
0
                return -1;
7091
0
            }
7092
2
            txn->put(txn_inf_key, txn_inf_val);
7093
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7094
            // Put recycle txn key
7095
2
            std::string recyc_txn_key, recyc_txn_val;
7096
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7097
2
            RecycleTxnPB recycle_txn_pb;
7098
2
            recycle_txn_pb.set_creation_time(current_time);
7099
2
            recycle_txn_pb.set_label(txn_info.label());
7100
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7101
0
                LOG_WARNING("failed to serialize txn recycle info")
7102
0
                        .tag("key", hex(k))
7103
0
                        .tag("db_id", db_id)
7104
0
                        .tag("txn_id", txn_id);
7105
0
                return -1;
7106
0
            }
7107
2
            txn->put(recyc_txn_key, recyc_txn_val);
7108
            // Remove txn running key
7109
2
            txn->remove(k);
7110
2
            err = txn->commit();
7111
2
            if (err != TxnErrorCode::TXN_OK) {
7112
0
                LOG_WARNING("failed to commit txn err={}", err)
7113
0
                        .tag("key", hex(k))
7114
0
                        .tag("db_id", db_id)
7115
0
                        .tag("txn_id", txn_id);
7116
0
                return -1;
7117
0
            }
7118
2
            metrics_context.total_recycled_num = ++num_abort;
7119
2
            metrics_context.report();
7120
2
        }
7121
7122
2
        return 0;
7123
6
    };
7124
7125
19
    if (config::enable_recycler_stats_metrics) {
7126
0
        scan_and_statistics_abort_timeout_txn();
7127
0
    }
7128
    // recycle_func and loop_done for scan and recycle
7129
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7130
19
                            std::move(handle_txn_running_kv));
7131
19
}
7132
7133
22
int InstanceRecycler::recycle_expired_txn_label() {
7134
22
    const std::string task_name = "recycle_expired_txn_label";
7135
22
    int64_t num_scanned = 0;
7136
22
    int64_t num_expired = 0;
7137
22
    std::atomic_long num_recycled = 0;
7138
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7139
22
    int ret = 0;
7140
7141
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7142
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7143
22
    std::string begin_recycle_txn_key;
7144
22
    std::string end_recycle_txn_key;
7145
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7146
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7147
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
7148
7149
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
7150
7151
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7152
22
    register_recycle_task(task_name, start_time);
7153
22
    DORIS_CLOUD_DEFER {
7154
22
        unregister_recycle_task(task_name);
7155
22
        int64_t cost =
7156
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7157
22
        metrics_context.finish_report();
7158
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7159
22
                .tag("instance_id", instance_id_)
7160
22
                .tag("num_scanned", num_scanned)
7161
22
                .tag("num_expired", num_expired)
7162
22
                .tag("num_recycled", num_recycled);
7163
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7153
1
    DORIS_CLOUD_DEFER {
7154
1
        unregister_recycle_task(task_name);
7155
1
        int64_t cost =
7156
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7157
1
        metrics_context.finish_report();
7158
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7159
1
                .tag("instance_id", instance_id_)
7160
1
                .tag("num_scanned", num_scanned)
7161
1
                .tag("num_expired", num_expired)
7162
1
                .tag("num_recycled", num_recycled);
7163
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7153
21
    DORIS_CLOUD_DEFER {
7154
21
        unregister_recycle_task(task_name);
7155
21
        int64_t cost =
7156
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7157
21
        metrics_context.finish_report();
7158
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7159
21
                .tag("instance_id", instance_id_)
7160
21
                .tag("num_scanned", num_scanned)
7161
21
                .tag("num_expired", num_expired)
7162
21
                .tag("num_recycled", num_recycled);
7163
21
    };
7164
7165
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7166
7167
22
    SyncExecutor<int> concurrent_delete_executor(
7168
22
            _thread_pool_group.s3_producer_pool,
7169
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7170
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7170
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7170
38.0k
            [](const int& ret) { return ret != 0; });
7171
7172
22
    int64_t current_time_ms =
7173
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7174
7175
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7176
50.0k
        ++num_scanned;
7177
50.0k
        RecycleTxnPB recycle_txn_pb;
7178
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7179
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7180
0
            return -1;
7181
0
        }
7182
50.0k
        if ((config::force_immediate_recycle) ||
7183
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7184
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7185
50.0k
             current_time_ms)) {
7186
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7187
38.0k
            num_expired++;
7188
7189
38.0k
            std::string_view k1 = k;
7190
38.0k
            k1.remove_prefix(1); // Remove key space
7191
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7192
38.0k
            if (decode_key(&k1, &out) != 0) {
7193
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7194
0
                return -1;
7195
0
            }
7196
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7197
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7198
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7199
38.0k
        }
7200
50.0k
        return 0;
7201
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7175
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7176
1
        ++num_scanned;
7177
1
        RecycleTxnPB recycle_txn_pb;
7178
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7179
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7180
0
            return -1;
7181
0
        }
7182
1
        if ((config::force_immediate_recycle) ||
7183
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7184
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7185
1
             current_time_ms)) {
7186
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7187
1
            num_expired++;
7188
7189
1
            std::string_view k1 = k;
7190
1
            k1.remove_prefix(1); // Remove key space
7191
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7192
1
            if (decode_key(&k1, &out) != 0) {
7193
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7194
0
                return -1;
7195
0
            }
7196
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7197
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7198
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7199
1
        }
7200
1
        return 0;
7201
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7175
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7176
50.0k
        ++num_scanned;
7177
50.0k
        RecycleTxnPB recycle_txn_pb;
7178
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7179
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7180
0
            return -1;
7181
0
        }
7182
50.0k
        if ((config::force_immediate_recycle) ||
7183
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7184
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7185
50.0k
             current_time_ms)) {
7186
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7187
38.0k
            num_expired++;
7188
7189
38.0k
            std::string_view k1 = k;
7190
38.0k
            k1.remove_prefix(1); // Remove key space
7191
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7192
38.0k
            if (decode_key(&k1, &out) != 0) {
7193
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7194
0
                return -1;
7195
0
            }
7196
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7197
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7198
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7199
38.0k
        }
7200
50.0k
        return 0;
7201
50.0k
    };
7202
7203
    // int 0 for success, 1 for conflict, -1 for error
7204
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7205
38.0k
        std::string_view k1 = k;
7206
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7207
38.0k
        k1.remove_prefix(1); // Remove key space
7208
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7209
38.0k
        int ret = decode_key(&k1, &out);
7210
38.0k
        if (ret != 0) {
7211
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7212
0
            return -1;
7213
0
        }
7214
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7215
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7216
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7217
38.0k
        std::unique_ptr<Transaction> txn;
7218
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7219
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7220
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7221
0
            return -1;
7222
0
        }
7223
        // Remove txn index kv
7224
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7225
38.0k
        txn->remove(index_key);
7226
        // Remove txn info kv
7227
38.0k
        std::string info_key, info_val;
7228
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7229
38.0k
        err = txn->get(info_key, &info_val);
7230
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7231
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7232
0
            return -1;
7233
0
        }
7234
38.0k
        TxnInfoPB txn_info;
7235
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7236
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7237
0
            return -1;
7238
0
        }
7239
38.0k
        txn->remove(info_key);
7240
        // Remove sub txn index kvs
7241
38.0k
        std::vector<std::string> sub_txn_index_keys;
7242
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7243
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7244
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7245
38.0k
        }
7246
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7247
38.0k
            txn->remove(sub_txn_index_key);
7248
38.0k
        }
7249
        // Update txn label
7250
38.0k
        std::string label_key, label_val;
7251
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7252
38.0k
        err = txn->get(label_key, &label_val);
7253
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7254
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7255
0
                         << " err=" << err;
7256
0
            return -1;
7257
0
        }
7258
38.0k
        TxnLabelPB txn_label;
7259
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7260
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7261
0
            return -1;
7262
0
        }
7263
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7264
38.0k
        if (it != txn_label.txn_ids().end()) {
7265
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7266
38.0k
        }
7267
38.0k
        if (txn_label.txn_ids().empty()) {
7268
38.0k
            txn->remove(label_key);
7269
38.0k
            TEST_SYNC_POINT_CALLBACK(
7270
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7271
38.0k
        } else {
7272
11
            if (!txn_label.SerializeToString(&label_val)) {
7273
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7274
0
                return -1;
7275
0
            }
7276
11
            TEST_SYNC_POINT_CALLBACK(
7277
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7278
11
            txn->atomic_set_ver_value(label_key, label_val);
7279
11
            TEST_SYNC_POINT_CALLBACK(
7280
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7281
11
        }
7282
        // Remove recycle txn kv
7283
38.0k
        txn->remove(k);
7284
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7285
38.0k
        err = txn->commit();
7286
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7287
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7288
4
                TEST_SYNC_POINT_CALLBACK(
7289
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7290
                // log the txn_id and label
7291
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7292
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7293
4
                             << " txn_label=" << txn_info.label();
7294
4
                return 1;
7295
4
            }
7296
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7297
0
            return -1;
7298
4
        }
7299
38.0k
        ++num_recycled;
7300
7301
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7302
38.0k
        return 0;
7303
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7204
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7205
1
        std::string_view k1 = k;
7206
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7207
1
        k1.remove_prefix(1); // Remove key space
7208
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7209
1
        int ret = decode_key(&k1, &out);
7210
1
        if (ret != 0) {
7211
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7212
0
            return -1;
7213
0
        }
7214
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7215
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7216
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7217
1
        std::unique_ptr<Transaction> txn;
7218
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7219
1
        if (err != TxnErrorCode::TXN_OK) {
7220
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7221
0
            return -1;
7222
0
        }
7223
        // Remove txn index kv
7224
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7225
1
        txn->remove(index_key);
7226
        // Remove txn info kv
7227
1
        std::string info_key, info_val;
7228
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7229
1
        err = txn->get(info_key, &info_val);
7230
1
        if (err != TxnErrorCode::TXN_OK) {
7231
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7232
0
            return -1;
7233
0
        }
7234
1
        TxnInfoPB txn_info;
7235
1
        if (!txn_info.ParseFromString(info_val)) {
7236
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7237
0
            return -1;
7238
0
        }
7239
1
        txn->remove(info_key);
7240
        // Remove sub txn index kvs
7241
1
        std::vector<std::string> sub_txn_index_keys;
7242
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7243
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7244
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7245
0
        }
7246
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7247
0
            txn->remove(sub_txn_index_key);
7248
0
        }
7249
        // Update txn label
7250
1
        std::string label_key, label_val;
7251
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7252
1
        err = txn->get(label_key, &label_val);
7253
1
        if (err != TxnErrorCode::TXN_OK) {
7254
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7255
0
                         << " err=" << err;
7256
0
            return -1;
7257
0
        }
7258
1
        TxnLabelPB txn_label;
7259
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7260
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7261
0
            return -1;
7262
0
        }
7263
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7264
1
        if (it != txn_label.txn_ids().end()) {
7265
1
            txn_label.mutable_txn_ids()->erase(it);
7266
1
        }
7267
1
        if (txn_label.txn_ids().empty()) {
7268
1
            txn->remove(label_key);
7269
1
            TEST_SYNC_POINT_CALLBACK(
7270
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7271
1
        } else {
7272
0
            if (!txn_label.SerializeToString(&label_val)) {
7273
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7274
0
                return -1;
7275
0
            }
7276
0
            TEST_SYNC_POINT_CALLBACK(
7277
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7278
0
            txn->atomic_set_ver_value(label_key, label_val);
7279
0
            TEST_SYNC_POINT_CALLBACK(
7280
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7281
0
        }
7282
        // Remove recycle txn kv
7283
1
        txn->remove(k);
7284
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7285
1
        err = txn->commit();
7286
1
        if (err != TxnErrorCode::TXN_OK) {
7287
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7288
0
                TEST_SYNC_POINT_CALLBACK(
7289
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7290
                // log the txn_id and label
7291
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7292
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7293
0
                             << " txn_label=" << txn_info.label();
7294
0
                return 1;
7295
0
            }
7296
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7297
0
            return -1;
7298
0
        }
7299
1
        ++num_recycled;
7300
7301
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7302
1
        return 0;
7303
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7204
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7205
38.0k
        std::string_view k1 = k;
7206
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7207
38.0k
        k1.remove_prefix(1); // Remove key space
7208
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7209
38.0k
        int ret = decode_key(&k1, &out);
7210
38.0k
        if (ret != 0) {
7211
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7212
0
            return -1;
7213
0
        }
7214
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7215
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7216
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7217
38.0k
        std::unique_ptr<Transaction> txn;
7218
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7219
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7220
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7221
0
            return -1;
7222
0
        }
7223
        // Remove txn index kv
7224
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7225
38.0k
        txn->remove(index_key);
7226
        // Remove txn info kv
7227
38.0k
        std::string info_key, info_val;
7228
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7229
38.0k
        err = txn->get(info_key, &info_val);
7230
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7231
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7232
0
            return -1;
7233
0
        }
7234
38.0k
        TxnInfoPB txn_info;
7235
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7236
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7237
0
            return -1;
7238
0
        }
7239
38.0k
        txn->remove(info_key);
7240
        // Remove sub txn index kvs
7241
38.0k
        std::vector<std::string> sub_txn_index_keys;
7242
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7243
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7244
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7245
38.0k
        }
7246
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7247
38.0k
            txn->remove(sub_txn_index_key);
7248
38.0k
        }
7249
        // Update txn label
7250
38.0k
        std::string label_key, label_val;
7251
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7252
38.0k
        err = txn->get(label_key, &label_val);
7253
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7254
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7255
0
                         << " err=" << err;
7256
0
            return -1;
7257
0
        }
7258
38.0k
        TxnLabelPB txn_label;
7259
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7260
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7261
0
            return -1;
7262
0
        }
7263
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7264
38.0k
        if (it != txn_label.txn_ids().end()) {
7265
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7266
38.0k
        }
7267
38.0k
        if (txn_label.txn_ids().empty()) {
7268
38.0k
            txn->remove(label_key);
7269
38.0k
            TEST_SYNC_POINT_CALLBACK(
7270
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7271
38.0k
        } else {
7272
11
            if (!txn_label.SerializeToString(&label_val)) {
7273
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7274
0
                return -1;
7275
0
            }
7276
11
            TEST_SYNC_POINT_CALLBACK(
7277
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7278
11
            txn->atomic_set_ver_value(label_key, label_val);
7279
11
            TEST_SYNC_POINT_CALLBACK(
7280
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7281
11
        }
7282
        // Remove recycle txn kv
7283
38.0k
        txn->remove(k);
7284
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7285
38.0k
        err = txn->commit();
7286
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7287
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7288
4
                TEST_SYNC_POINT_CALLBACK(
7289
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7290
                // log the txn_id and label
7291
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7292
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7293
4
                             << " txn_label=" << txn_info.label();
7294
4
                return 1;
7295
4
            }
7296
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7297
0
            return -1;
7298
4
        }
7299
38.0k
        ++num_recycled;
7300
7301
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7302
38.0k
        return 0;
7303
38.0k
    };
7304
7305
22
    auto loop_done = [&]() -> int {
7306
15
        DORIS_CLOUD_DEFER {
7307
15
            recycle_txn_keys_by_label.clear();
7308
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7306
1
        DORIS_CLOUD_DEFER {
7307
1
            recycle_txn_keys_by_label.clear();
7308
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7306
14
        DORIS_CLOUD_DEFER {
7307
14
            recycle_txn_keys_by_label.clear();
7308
14
        };
7309
15
        TEST_SYNC_POINT_CALLBACK(
7310
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7311
15
                &recycle_txn_keys_by_label);
7312
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7313
38.0k
            int ret = delete_recycle_txn_kv(k);
7314
38.0k
            TEST_SYNC_POINT_CALLBACK(
7315
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7316
38.0k
                    &ret);
7317
38.0k
            if (ret == 1) {
7318
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7319
4
                for (int i = 1; i <= max_retry; ++i) {
7320
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7321
3
                    ret = delete_recycle_txn_kv(k);
7322
3
                    TEST_SYNC_POINT_CALLBACK(
7323
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7324
3
                            "error",
7325
3
                            &ret);
7326
3
                    if (ret != 1) {
7327
1
                        break;
7328
1
                    }
7329
                    // random sleep 0-100 ms to retry
7330
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7331
2
                }
7332
2
            }
7333
38.0k
            return ret;
7334
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7312
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7313
1
            int ret = delete_recycle_txn_kv(k);
7314
1
            TEST_SYNC_POINT_CALLBACK(
7315
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7316
1
                    &ret);
7317
1
            if (ret == 1) {
7318
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7319
0
                for (int i = 1; i <= max_retry; ++i) {
7320
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7321
0
                    ret = delete_recycle_txn_kv(k);
7322
0
                    TEST_SYNC_POINT_CALLBACK(
7323
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7324
0
                            "error",
7325
0
                            &ret);
7326
0
                    if (ret != 1) {
7327
0
                        break;
7328
0
                    }
7329
                    // random sleep 0-100 ms to retry
7330
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7331
0
                }
7332
0
            }
7333
1
            return ret;
7334
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7312
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7313
38.0k
            int ret = delete_recycle_txn_kv(k);
7314
38.0k
            TEST_SYNC_POINT_CALLBACK(
7315
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7316
38.0k
                    &ret);
7317
38.0k
            if (ret == 1) {
7318
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7319
4
                for (int i = 1; i <= max_retry; ++i) {
7320
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7321
3
                    ret = delete_recycle_txn_kv(k);
7322
3
                    TEST_SYNC_POINT_CALLBACK(
7323
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7324
3
                            "error",
7325
3
                            &ret);
7326
3
                    if (ret != 1) {
7327
1
                        break;
7328
1
                    }
7329
                    // random sleep 0-100 ms to retry
7330
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7331
2
                }
7332
2
            }
7333
38.0k
            return ret;
7334
38.0k
        };
7335
7336
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7337
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7338
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7339
0
                           << " txn_count=" << txn_keys.size();
7340
38.0k
                for (const auto& k : txn_keys) {
7341
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7342
38.0k
                    if (ret != 0) {
7343
2
                        LOG_WARNING("failed to delete recycle txn kv")
7344
2
                                .tag("instance id", instance_id_)
7345
2
                                .tag("key", hex(k))
7346
2
                                .tag("label_key", hex(label_key));
7347
2
                        return -1;
7348
2
                    }
7349
38.0k
                }
7350
38.0k
                return 0;
7351
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7337
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7338
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7339
0
                           << " txn_count=" << txn_keys.size();
7340
1
                for (const auto& k : txn_keys) {
7341
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7342
1
                    if (ret != 0) {
7343
0
                        LOG_WARNING("failed to delete recycle txn kv")
7344
0
                                .tag("instance id", instance_id_)
7345
0
                                .tag("key", hex(k))
7346
0
                                .tag("label_key", hex(label_key));
7347
0
                        return -1;
7348
0
                    }
7349
1
                }
7350
1
                return 0;
7351
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7337
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7338
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7339
0
                           << " txn_count=" << txn_keys.size();
7340
38.0k
                for (const auto& k : txn_keys) {
7341
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7342
38.0k
                    if (ret != 0) {
7343
2
                        LOG_WARNING("failed to delete recycle txn kv")
7344
2
                                .tag("instance id", instance_id_)
7345
2
                                .tag("key", hex(k))
7346
2
                                .tag("label_key", hex(label_key));
7347
2
                        return -1;
7348
2
                    }
7349
38.0k
                }
7350
38.0k
                return 0;
7351
38.0k
            });
7352
38.0k
        }
7353
15
        bool finished = true;
7354
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7355
38.0k
        for (int r : rets) {
7356
38.0k
            if (r != 0) {
7357
2
                ret = -1;
7358
2
            }
7359
38.0k
        }
7360
7361
15
        ret = finished ? ret : -1;
7362
7363
        // Update metrics after all concurrent tasks completed
7364
15
        metrics_context.total_recycled_num = num_recycled.load();
7365
15
        metrics_context.report();
7366
7367
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7368
7369
15
        if (ret != 0) {
7370
6
            LOG_WARNING("recycle txn kv ret!=0")
7371
6
                    .tag("finished", finished)
7372
6
                    .tag("ret", ret)
7373
6
                    .tag("instance_id", instance_id_);
7374
6
            return ret;
7375
6
        }
7376
9
        return ret;
7377
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7305
1
    auto loop_done = [&]() -> int {
7306
1
        DORIS_CLOUD_DEFER {
7307
1
            recycle_txn_keys_by_label.clear();
7308
1
        };
7309
1
        TEST_SYNC_POINT_CALLBACK(
7310
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7311
1
                &recycle_txn_keys_by_label);
7312
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7313
1
            int ret = delete_recycle_txn_kv(k);
7314
1
            TEST_SYNC_POINT_CALLBACK(
7315
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7316
1
                    &ret);
7317
1
            if (ret == 1) {
7318
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7319
1
                for (int i = 1; i <= max_retry; ++i) {
7320
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7321
1
                    ret = delete_recycle_txn_kv(k);
7322
1
                    TEST_SYNC_POINT_CALLBACK(
7323
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7324
1
                            "error",
7325
1
                            &ret);
7326
1
                    if (ret != 1) {
7327
1
                        break;
7328
1
                    }
7329
                    // random sleep 0-100 ms to retry
7330
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7331
1
                }
7332
1
            }
7333
1
            return ret;
7334
1
        };
7335
7336
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7337
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7338
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7339
1
                           << " txn_count=" << txn_keys.size();
7340
1
                for (const auto& k : txn_keys) {
7341
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7342
1
                    if (ret != 0) {
7343
1
                        LOG_WARNING("failed to delete recycle txn kv")
7344
1
                                .tag("instance id", instance_id_)
7345
1
                                .tag("key", hex(k))
7346
1
                                .tag("label_key", hex(label_key));
7347
1
                        return -1;
7348
1
                    }
7349
1
                }
7350
1
                return 0;
7351
1
            });
7352
1
        }
7353
1
        bool finished = true;
7354
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7355
1
        for (int r : rets) {
7356
1
            if (r != 0) {
7357
0
                ret = -1;
7358
0
            }
7359
1
        }
7360
7361
1
        ret = finished ? ret : -1;
7362
7363
        // Update metrics after all concurrent tasks completed
7364
1
        metrics_context.total_recycled_num = num_recycled.load();
7365
1
        metrics_context.report();
7366
7367
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7368
7369
1
        if (ret != 0) {
7370
0
            LOG_WARNING("recycle txn kv ret!=0")
7371
0
                    .tag("finished", finished)
7372
0
                    .tag("ret", ret)
7373
0
                    .tag("instance_id", instance_id_);
7374
0
            return ret;
7375
0
        }
7376
1
        return ret;
7377
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7305
14
    auto loop_done = [&]() -> int {
7306
14
        DORIS_CLOUD_DEFER {
7307
14
            recycle_txn_keys_by_label.clear();
7308
14
        };
7309
14
        TEST_SYNC_POINT_CALLBACK(
7310
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7311
14
                &recycle_txn_keys_by_label);
7312
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7313
14
            int ret = delete_recycle_txn_kv(k);
7314
14
            TEST_SYNC_POINT_CALLBACK(
7315
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7316
14
                    &ret);
7317
14
            if (ret == 1) {
7318
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7319
14
                for (int i = 1; i <= max_retry; ++i) {
7320
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7321
14
                    ret = delete_recycle_txn_kv(k);
7322
14
                    TEST_SYNC_POINT_CALLBACK(
7323
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7324
14
                            "error",
7325
14
                            &ret);
7326
14
                    if (ret != 1) {
7327
14
                        break;
7328
14
                    }
7329
                    // random sleep 0-100 ms to retry
7330
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7331
14
                }
7332
14
            }
7333
14
            return ret;
7334
14
        };
7335
7336
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7337
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7338
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7339
38.0k
                           << " txn_count=" << txn_keys.size();
7340
38.0k
                for (const auto& k : txn_keys) {
7341
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7342
38.0k
                    if (ret != 0) {
7343
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7344
38.0k
                                .tag("instance id", instance_id_)
7345
38.0k
                                .tag("key", hex(k))
7346
38.0k
                                .tag("label_key", hex(label_key));
7347
38.0k
                        return -1;
7348
38.0k
                    }
7349
38.0k
                }
7350
38.0k
                return 0;
7351
38.0k
            });
7352
38.0k
        }
7353
14
        bool finished = true;
7354
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7355
38.0k
        for (int r : rets) {
7356
38.0k
            if (r != 0) {
7357
2
                ret = -1;
7358
2
            }
7359
38.0k
        }
7360
7361
14
        ret = finished ? ret : -1;
7362
7363
        // Update metrics after all concurrent tasks completed
7364
14
        metrics_context.total_recycled_num = num_recycled.load();
7365
14
        metrics_context.report();
7366
7367
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7368
7369
14
        if (ret != 0) {
7370
6
            LOG_WARNING("recycle txn kv ret!=0")
7371
6
                    .tag("finished", finished)
7372
6
                    .tag("ret", ret)
7373
6
                    .tag("instance_id", instance_id_);
7374
6
            return ret;
7375
6
        }
7376
8
        return ret;
7377
14
    };
7378
7379
22
    if (config::enable_recycler_stats_metrics) {
7380
0
        scan_and_statistics_expired_txn_label();
7381
0
    }
7382
    // recycle_func and loop_done for scan and recycle
7383
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7384
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7385
22
}
7386
7387
struct CopyJobIdTuple {
7388
    std::string instance_id;
7389
    std::string stage_id;
7390
    long table_id;
7391
    std::string copy_id;
7392
    std::string stage_path;
7393
};
7394
struct BatchObjStoreAccessor {
7395
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7396
                          TxnKv* txn_kv)
7397
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7398
3
    ~BatchObjStoreAccessor() {
7399
3
        if (!paths_.empty()) {
7400
3
            consume();
7401
3
        }
7402
3
    }
7403
7404
    /**
7405
    * To implicitely do batch work and submit the batch delete task to s3
7406
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7407
    *
7408
    * @param copy_job The protubuf struct consists of the copy job files.
7409
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7410
    *            it would last until we finish the delete task, here we need pass one string value
7411
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7412
    */
7413
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7414
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7415
5
        auto& file_keys = copy_file_keys_[key];
7416
5
        file_keys.log_trace =
7417
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7418
5
                            instance_id, stage_id, table_id, copy_id, path);
7419
5
        std::string_view log_trace = file_keys.log_trace;
7420
2.03k
        for (const auto& file : copy_job.object_files()) {
7421
2.03k
            auto relative_path = file.relative_path();
7422
2.03k
            paths_.push_back(relative_path);
7423
2.03k
            file_keys.keys.push_back(copy_file_key(
7424
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7425
2.03k
            LOG_INFO(log_trace)
7426
2.03k
                    .tag("relative_path", relative_path)
7427
2.03k
                    .tag("batch_count", batch_count_);
7428
2.03k
        }
7429
5
        LOG_INFO(log_trace)
7430
5
                .tag("objects_num", copy_job.object_files().size())
7431
5
                .tag("batch_count", batch_count_);
7432
        // 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
7433
        // recommend using delete objects when objects num is less than 10)
7434
5
        if (paths_.size() < 1000) {
7435
3
            return;
7436
3
        }
7437
2
        consume();
7438
2
    }
7439
7440
private:
7441
5
    void consume() {
7442
5
        DORIS_CLOUD_DEFER {
7443
5
            paths_.clear();
7444
5
            copy_file_keys_.clear();
7445
5
            batch_count_++;
7446
7447
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7448
5
                        batch_count_);
7449
5
        };
7450
7451
5
        StopWatch sw;
7452
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7453
5
        if (0 != accessor_->delete_files(paths_)) {
7454
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7455
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7456
2
            return;
7457
2
        }
7458
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7459
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7460
        // delete fdb's keys
7461
3
        for (auto& file_keys : copy_file_keys_) {
7462
3
            auto& [log_trace, keys] = file_keys.second;
7463
3
            std::unique_ptr<Transaction> txn;
7464
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7465
0
                LOG(WARNING) << "failed to create txn";
7466
0
                continue;
7467
0
            }
7468
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7469
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7470
            // limited, should not cause the txn commit failed.
7471
1.02k
            for (const auto& key : keys) {
7472
1.02k
                txn->remove(key);
7473
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7474
1.02k
            }
7475
3
            txn->remove(file_keys.first);
7476
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7477
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7478
0
                continue;
7479
0
            }
7480
3
        }
7481
3
    }
7482
    std::shared_ptr<StorageVaultAccessor> accessor_;
7483
    // the path of the s3 files to be deleted
7484
    std::vector<std::string> paths_;
7485
    struct CopyFiles {
7486
        std::string log_trace;
7487
        std::vector<std::string> keys;
7488
    };
7489
    // pair<std::string, std::vector<std::string>>
7490
    // first: instance_id_ stage_id table_id query_id
7491
    // second: keys to be deleted
7492
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7493
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7494
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7495
    // which can together uniquely identifies different tasks for tracing log
7496
    uint64_t& batch_count_;
7497
    TxnKv* txn_kv_;
7498
};
7499
7500
13
int InstanceRecycler::recycle_copy_jobs() {
7501
13
    int64_t num_scanned = 0;
7502
13
    int64_t num_finished = 0;
7503
13
    int64_t num_expired = 0;
7504
13
    int64_t num_recycled = 0;
7505
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7506
13
    uint64_t batch_count = 0;
7507
13
    const std::string task_name = "recycle_copy_jobs";
7508
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7509
7510
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7511
7512
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7513
13
    register_recycle_task(task_name, start_time);
7514
7515
13
    DORIS_CLOUD_DEFER {
7516
13
        unregister_recycle_task(task_name);
7517
13
        int64_t cost =
7518
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7519
13
        metrics_context.finish_report();
7520
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7521
13
                .tag("instance_id", instance_id_)
7522
13
                .tag("num_scanned", num_scanned)
7523
13
                .tag("num_finished", num_finished)
7524
13
                .tag("num_expired", num_expired)
7525
13
                .tag("num_recycled", num_recycled);
7526
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7515
13
    DORIS_CLOUD_DEFER {
7516
13
        unregister_recycle_task(task_name);
7517
13
        int64_t cost =
7518
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7519
13
        metrics_context.finish_report();
7520
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7521
13
                .tag("instance_id", instance_id_)
7522
13
                .tag("num_scanned", num_scanned)
7523
13
                .tag("num_finished", num_finished)
7524
13
                .tag("num_expired", num_expired)
7525
13
                .tag("num_recycled", num_recycled);
7526
13
    };
7527
7528
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7529
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7530
13
    std::string key0;
7531
13
    std::string key1;
7532
13
    copy_job_key(key_info0, &key0);
7533
13
    copy_job_key(key_info1, &key1);
7534
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7535
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7536
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7537
16
                         this](std::string_view k, std::string_view v) -> int {
7538
16
        ++num_scanned;
7539
16
        CopyJobPB copy_job;
7540
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7541
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7542
0
            return -1;
7543
0
        }
7544
7545
        // decode copy job key
7546
16
        auto k1 = k;
7547
16
        k1.remove_prefix(1);
7548
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7549
16
        decode_key(&k1, &out);
7550
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7551
        // -> CopyJobPB
7552
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7553
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7554
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7555
7556
16
        bool check_storage = true;
7557
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7558
12
            ++num_finished;
7559
7560
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7561
7
                auto it = stage_accessor_map.find(stage_id);
7562
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7563
7
                std::string_view path;
7564
7
                if (it != stage_accessor_map.end()) {
7565
2
                    accessor = it->second;
7566
5
                } else {
7567
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7568
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7569
5
                                                      &inner_accessor);
7570
5
                    if (ret < 0) { // error
7571
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7572
0
                        return -1;
7573
5
                    } else if (ret == 0) {
7574
3
                        path = inner_accessor->uri();
7575
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7576
3
                                inner_accessor, batch_count, txn_kv_.get());
7577
3
                        stage_accessor_map.emplace(stage_id, accessor);
7578
3
                    } else { // stage not found, skip check storage
7579
2
                        check_storage = false;
7580
2
                    }
7581
5
                }
7582
7
                if (check_storage) {
7583
                    // TODO delete objects with key and etag is not supported
7584
5
                    accessor->add(std::move(copy_job), std::string(k),
7585
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7586
5
                    return 0;
7587
5
                }
7588
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7589
5
                int64_t current_time =
7590
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7591
5
                if (copy_job.finish_time_ms() > 0) {
7592
2
                    if (!config::force_immediate_recycle &&
7593
2
                        current_time < copy_job.finish_time_ms() +
7594
2
                                               config::copy_job_max_retention_second * 1000) {
7595
1
                        return 0;
7596
1
                    }
7597
3
                } else {
7598
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7599
3
                    if (!config::force_immediate_recycle &&
7600
3
                        current_time < copy_job.start_time_ms() +
7601
3
                                               config::copy_job_max_retention_second * 1000) {
7602
1
                        return 0;
7603
1
                    }
7604
3
                }
7605
5
            }
7606
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7607
4
            int64_t current_time =
7608
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7609
            // if copy job is timeout: delete all copy file kvs and copy job kv
7610
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7611
2
                return 0;
7612
2
            }
7613
2
            ++num_expired;
7614
2
        }
7615
7616
        // delete all copy files
7617
7
        std::vector<std::string> copy_file_keys;
7618
70
        for (auto& file : copy_job.object_files()) {
7619
70
            copy_file_keys.push_back(copy_file_key(
7620
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7621
70
        }
7622
7
        std::unique_ptr<Transaction> txn;
7623
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7624
0
            LOG(WARNING) << "failed to create txn";
7625
0
            return -1;
7626
0
        }
7627
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7628
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7629
        // limited, should not cause the txn commit failed.
7630
70
        for (const auto& key : copy_file_keys) {
7631
70
            txn->remove(key);
7632
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7633
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7634
70
                      << ", query_id=" << copy_id;
7635
70
        }
7636
7
        txn->remove(k);
7637
7
        TxnErrorCode err = txn->commit();
7638
7
        if (err != TxnErrorCode::TXN_OK) {
7639
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7640
0
            return -1;
7641
0
        }
7642
7643
7
        metrics_context.total_recycled_num = ++num_recycled;
7644
7
        metrics_context.report();
7645
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7646
7
        return 0;
7647
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
7537
16
                         this](std::string_view k, std::string_view v) -> int {
7538
16
        ++num_scanned;
7539
16
        CopyJobPB copy_job;
7540
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7541
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7542
0
            return -1;
7543
0
        }
7544
7545
        // decode copy job key
7546
16
        auto k1 = k;
7547
16
        k1.remove_prefix(1);
7548
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7549
16
        decode_key(&k1, &out);
7550
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7551
        // -> CopyJobPB
7552
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7553
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7554
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7555
7556
16
        bool check_storage = true;
7557
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7558
12
            ++num_finished;
7559
7560
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7561
7
                auto it = stage_accessor_map.find(stage_id);
7562
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7563
7
                std::string_view path;
7564
7
                if (it != stage_accessor_map.end()) {
7565
2
                    accessor = it->second;
7566
5
                } else {
7567
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7568
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7569
5
                                                      &inner_accessor);
7570
5
                    if (ret < 0) { // error
7571
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7572
0
                        return -1;
7573
5
                    } else if (ret == 0) {
7574
3
                        path = inner_accessor->uri();
7575
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7576
3
                                inner_accessor, batch_count, txn_kv_.get());
7577
3
                        stage_accessor_map.emplace(stage_id, accessor);
7578
3
                    } else { // stage not found, skip check storage
7579
2
                        check_storage = false;
7580
2
                    }
7581
5
                }
7582
7
                if (check_storage) {
7583
                    // TODO delete objects with key and etag is not supported
7584
5
                    accessor->add(std::move(copy_job), std::string(k),
7585
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7586
5
                    return 0;
7587
5
                }
7588
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7589
5
                int64_t current_time =
7590
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7591
5
                if (copy_job.finish_time_ms() > 0) {
7592
2
                    if (!config::force_immediate_recycle &&
7593
2
                        current_time < copy_job.finish_time_ms() +
7594
2
                                               config::copy_job_max_retention_second * 1000) {
7595
1
                        return 0;
7596
1
                    }
7597
3
                } else {
7598
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7599
3
                    if (!config::force_immediate_recycle &&
7600
3
                        current_time < copy_job.start_time_ms() +
7601
3
                                               config::copy_job_max_retention_second * 1000) {
7602
1
                        return 0;
7603
1
                    }
7604
3
                }
7605
5
            }
7606
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7607
4
            int64_t current_time =
7608
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7609
            // if copy job is timeout: delete all copy file kvs and copy job kv
7610
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7611
2
                return 0;
7612
2
            }
7613
2
            ++num_expired;
7614
2
        }
7615
7616
        // delete all copy files
7617
7
        std::vector<std::string> copy_file_keys;
7618
70
        for (auto& file : copy_job.object_files()) {
7619
70
            copy_file_keys.push_back(copy_file_key(
7620
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7621
70
        }
7622
7
        std::unique_ptr<Transaction> txn;
7623
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7624
0
            LOG(WARNING) << "failed to create txn";
7625
0
            return -1;
7626
0
        }
7627
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7628
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7629
        // limited, should not cause the txn commit failed.
7630
70
        for (const auto& key : copy_file_keys) {
7631
70
            txn->remove(key);
7632
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7633
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7634
70
                      << ", query_id=" << copy_id;
7635
70
        }
7636
7
        txn->remove(k);
7637
7
        TxnErrorCode err = txn->commit();
7638
7
        if (err != TxnErrorCode::TXN_OK) {
7639
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7640
0
            return -1;
7641
0
        }
7642
7643
7
        metrics_context.total_recycled_num = ++num_recycled;
7644
7
        metrics_context.report();
7645
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7646
7
        return 0;
7647
7
    };
7648
7649
13
    if (config::enable_recycler_stats_metrics) {
7650
0
        scan_and_statistics_copy_jobs();
7651
0
    }
7652
    // recycle_func and loop_done for scan and recycle
7653
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7654
13
}
7655
7656
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7657
                                             const StagePB::StageType& stage_type,
7658
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7659
5
#ifdef UNIT_TEST
7660
    // In unit test, external use the same accessor as the internal stage
7661
5
    auto it = accessor_map_.find(stage_id);
7662
5
    if (it != accessor_map_.end()) {
7663
3
        *accessor = it->second;
7664
3
    } else {
7665
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7666
2
        return 1;
7667
2
    }
7668
#else
7669
    // init s3 accessor and add to accessor map
7670
    auto stage_it =
7671
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7672
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7673
7674
    if (stage_it == instance_info_.stages().end()) {
7675
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7676
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7677
        return 1;
7678
    }
7679
7680
    const auto& object_store_info = stage_it->obj_info();
7681
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7682
7683
    S3Conf s3_conf;
7684
    if (stage_type == StagePB::EXTERNAL) {
7685
        if (stage_access_type == StagePB::AKSK) {
7686
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7687
            if (!conf) {
7688
                return -1;
7689
            }
7690
7691
            s3_conf = std::move(*conf);
7692
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7693
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7694
            if (!conf) {
7695
                return -1;
7696
            }
7697
7698
            s3_conf = std::move(*conf);
7699
            if (instance_info_.ram_user().has_encryption_info()) {
7700
                AkSkPair plain_ak_sk_pair;
7701
                int ret = decrypt_ak_sk_helper(
7702
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7703
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7704
                if (ret != 0) {
7705
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7706
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7707
                    return -1;
7708
                }
7709
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7710
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7711
            } else {
7712
                s3_conf.ak = instance_info_.ram_user().ak();
7713
                s3_conf.sk = instance_info_.ram_user().sk();
7714
            }
7715
        } else {
7716
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7717
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7718
            return -1;
7719
        }
7720
    } else if (stage_type == StagePB::INTERNAL) {
7721
        int idx = stoi(object_store_info.id());
7722
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7723
            LOG(WARNING) << "invalid idx: " << idx;
7724
            return -1;
7725
        }
7726
7727
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7728
        auto conf = S3Conf::from_obj_store_info(old_obj);
7729
        if (!conf) {
7730
            return -1;
7731
        }
7732
7733
        s3_conf = std::move(*conf);
7734
        s3_conf.prefix = object_store_info.prefix();
7735
    } else {
7736
        LOG(WARNING) << "unknown stage type " << stage_type;
7737
        return -1;
7738
    }
7739
7740
    std::shared_ptr<S3Accessor> s3_accessor;
7741
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7742
    if (ret != 0) {
7743
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7744
        return -1;
7745
    }
7746
7747
    *accessor = std::move(s3_accessor);
7748
#endif
7749
3
    return 0;
7750
5
}
7751
7752
11
int InstanceRecycler::recycle_stage() {
7753
11
    int64_t num_scanned = 0;
7754
11
    int64_t num_recycled = 0;
7755
11
    const std::string task_name = "recycle_stage";
7756
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7757
7758
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7759
7760
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7761
11
    register_recycle_task(task_name, start_time);
7762
7763
11
    DORIS_CLOUD_DEFER {
7764
11
        unregister_recycle_task(task_name);
7765
11
        int64_t cost =
7766
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7767
11
        metrics_context.finish_report();
7768
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7769
11
                .tag("instance_id", instance_id_)
7770
11
                .tag("num_scanned", num_scanned)
7771
11
                .tag("num_recycled", num_recycled);
7772
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7763
11
    DORIS_CLOUD_DEFER {
7764
11
        unregister_recycle_task(task_name);
7765
11
        int64_t cost =
7766
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7767
11
        metrics_context.finish_report();
7768
        LOG_WARNING("recycle stage, cost={}s", cost)
7769
11
                .tag("instance_id", instance_id_)
7770
11
                .tag("num_scanned", num_scanned)
7771
11
                .tag("num_recycled", num_recycled);
7772
11
    };
7773
7774
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7775
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7776
11
    std::string key0 = recycle_stage_key(key_info0);
7777
11
    std::string key1 = recycle_stage_key(key_info1);
7778
7779
11
    std::vector<std::string_view> stage_keys;
7780
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7781
11
                         this](std::string_view k, std::string_view v) -> int {
7782
1
        ++num_scanned;
7783
1
        RecycleStagePB recycle_stage;
7784
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7785
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7786
0
            return -1;
7787
0
        }
7788
7789
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7790
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7791
0
            LOG(WARNING) << "invalid idx: " << idx;
7792
0
            return -1;
7793
0
        }
7794
7795
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7796
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7797
1
                [&] {
7798
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7799
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7800
1
                    if (!s3_conf) {
7801
1
                        return -1;
7802
1
                    }
7803
7804
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7805
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7806
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7807
1
                    if (ret != 0) {
7808
1
                        return -1;
7809
1
                    }
7810
7811
1
                    accessor = std::move(s3_accessor);
7812
1
                    return 0;
7813
1
                }(),
7814
1
                "recycle_stage:get_accessor", &accessor);
7815
7816
1
        if (ret != 0) {
7817
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7818
0
            return ret;
7819
0
        }
7820
7821
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7822
1
                .tag("instance_id", instance_id_)
7823
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7824
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7825
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7826
1
                .tag("obj_info_id", idx)
7827
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7828
1
        ret = accessor->delete_all();
7829
1
        if (ret != 0) {
7830
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7831
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7832
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7833
0
                         << ", ret=" << ret;
7834
0
            return -1;
7835
0
        }
7836
1
        metrics_context.total_recycled_num = ++num_recycled;
7837
1
        metrics_context.report();
7838
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7839
1
        stage_keys.push_back(k);
7840
1
        return 0;
7841
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7781
1
                         this](std::string_view k, std::string_view v) -> int {
7782
1
        ++num_scanned;
7783
1
        RecycleStagePB recycle_stage;
7784
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7785
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7786
0
            return -1;
7787
0
        }
7788
7789
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7790
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7791
0
            LOG(WARNING) << "invalid idx: " << idx;
7792
0
            return -1;
7793
0
        }
7794
7795
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7796
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7797
1
                [&] {
7798
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7799
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7800
1
                    if (!s3_conf) {
7801
1
                        return -1;
7802
1
                    }
7803
7804
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7805
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7806
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7807
1
                    if (ret != 0) {
7808
1
                        return -1;
7809
1
                    }
7810
7811
1
                    accessor = std::move(s3_accessor);
7812
1
                    return 0;
7813
1
                }(),
7814
1
                "recycle_stage:get_accessor", &accessor);
7815
7816
1
        if (ret != 0) {
7817
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7818
0
            return ret;
7819
0
        }
7820
7821
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7822
1
                .tag("instance_id", instance_id_)
7823
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7824
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7825
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7826
1
                .tag("obj_info_id", idx)
7827
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7828
1
        ret = accessor->delete_all();
7829
1
        if (ret != 0) {
7830
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7831
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7832
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7833
0
                         << ", ret=" << ret;
7834
0
            return -1;
7835
0
        }
7836
1
        metrics_context.total_recycled_num = ++num_recycled;
7837
1
        metrics_context.report();
7838
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7839
1
        stage_keys.push_back(k);
7840
1
        return 0;
7841
1
    };
7842
7843
11
    auto loop_done = [&stage_keys, this]() -> int {
7844
1
        if (stage_keys.empty()) return 0;
7845
1
        DORIS_CLOUD_DEFER {
7846
1
            stage_keys.clear();
7847
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7845
1
        DORIS_CLOUD_DEFER {
7846
1
            stage_keys.clear();
7847
1
        };
7848
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7849
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7850
0
            return -1;
7851
0
        }
7852
1
        return 0;
7853
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7843
1
    auto loop_done = [&stage_keys, this]() -> int {
7844
1
        if (stage_keys.empty()) return 0;
7845
1
        DORIS_CLOUD_DEFER {
7846
1
            stage_keys.clear();
7847
1
        };
7848
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7849
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7850
0
            return -1;
7851
0
        }
7852
1
        return 0;
7853
1
    };
7854
11
    if (config::enable_recycler_stats_metrics) {
7855
0
        scan_and_statistics_stage();
7856
0
    }
7857
    // recycle_func and loop_done for scan and recycle
7858
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7859
11
}
7860
7861
10
int InstanceRecycler::recycle_expired_stage_objects() {
7862
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7863
7864
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7865
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7866
7867
10
    DORIS_CLOUD_DEFER {
7868
10
        int64_t cost =
7869
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7870
10
        metrics_context.finish_report();
7871
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7872
10
                .tag("instance_id", instance_id_);
7873
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7867
10
    DORIS_CLOUD_DEFER {
7868
10
        int64_t cost =
7869
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7870
10
        metrics_context.finish_report();
7871
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7872
10
                .tag("instance_id", instance_id_);
7873
10
    };
7874
7875
10
    int ret = 0;
7876
7877
10
    if (config::enable_recycler_stats_metrics) {
7878
0
        scan_and_statistics_expired_stage_objects();
7879
0
    }
7880
7881
10
    for (const auto& stage : instance_info_.stages()) {
7882
0
        std::stringstream ss;
7883
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7884
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7885
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7886
0
           << ", prefix=" << stage.obj_info().prefix();
7887
7888
0
        if (stopped()) {
7889
0
            break;
7890
0
        }
7891
0
        if (stage.type() == StagePB::EXTERNAL) {
7892
0
            continue;
7893
0
        }
7894
0
        int idx = stoi(stage.obj_info().id());
7895
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7896
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7897
0
            continue;
7898
0
        }
7899
7900
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7901
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7902
0
        if (!s3_conf) {
7903
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7904
0
            continue;
7905
0
        }
7906
7907
0
        s3_conf->prefix = stage.obj_info().prefix();
7908
0
        std::shared_ptr<S3Accessor> accessor;
7909
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7910
0
        if (ret1 != 0) {
7911
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7912
0
            ret = -1;
7913
0
            continue;
7914
0
        }
7915
7916
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7917
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7918
0
            ret = -1;
7919
0
            continue;
7920
0
        }
7921
7922
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7923
0
        int64_t expiration_time =
7924
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7925
0
                config::internal_stage_objects_expire_time_second;
7926
0
        if (config::force_immediate_recycle) {
7927
0
            expiration_time = INT64_MAX;
7928
0
        }
7929
0
        ret1 = accessor->delete_all(expiration_time);
7930
0
        if (ret1 != 0) {
7931
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7932
0
                         << ss.str();
7933
0
            ret = -1;
7934
0
            continue;
7935
0
        }
7936
0
        metrics_context.total_recycled_num++;
7937
0
        metrics_context.report();
7938
0
    }
7939
10
    return ret;
7940
10
}
7941
7942
268
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7943
268
    std::lock_guard lock(recycle_tasks_mutex);
7944
268
    running_recycle_tasks[task_name] = start_time;
7945
268
}
7946
7947
267
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7948
267
    std::lock_guard lock(recycle_tasks_mutex);
7949
267
    DCHECK(running_recycle_tasks[task_name] > 0);
7950
267
    running_recycle_tasks.erase(task_name);
7951
267
}
7952
7953
3
bool InstanceRecycler::check_recycle_tasks() {
7954
3
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7955
3
    {
7956
3
        std::lock_guard lock(recycle_tasks_mutex);
7957
3
        tmp_running_recycle_tasks = running_recycle_tasks;
7958
3
    }
7959
7960
3
    bool found = false;
7961
3
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7962
3
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7963
2
        int64_t cost = now - start_time;
7964
2
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7965
2
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7966
2
                    .tag("instance_id", instance_id_)
7967
2
                    .tag("task", task_name);
7968
2
            found = true;
7969
2
        }
7970
2
    }
7971
7972
3
    return found;
7973
3
}
7974
7975
// Scan and statistics indexes that need to be recycled
7976
1
int InstanceRecycler::scan_and_statistics_indexes() {
7977
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7978
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7979
7980
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7981
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7982
1
    std::string index_key0;
7983
1
    std::string index_key1;
7984
1
    recycle_index_key(index_key_info0, &index_key0);
7985
1
    recycle_index_key(index_key_info1, &index_key1);
7986
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7987
7988
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7989
1
        RecycleIndexPB index_pb;
7990
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7991
0
            return 0;
7992
0
        }
7993
1
        int64_t current_time = ::time(nullptr);
7994
1
        if (current_time <
7995
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7996
0
            return 0;
7997
0
        }
7998
        // decode index_id
7999
1
        auto k1 = k;
8000
1
        k1.remove_prefix(1);
8001
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8002
1
        decode_key(&k1, &out);
8003
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
8004
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
8005
1
        std::unique_ptr<Transaction> txn;
8006
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8007
1
        if (err != TxnErrorCode::TXN_OK) {
8008
0
            return 0;
8009
0
        }
8010
1
        std::string val;
8011
1
        err = txn->get(k, &val);
8012
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8013
0
            return 0;
8014
0
        }
8015
1
        if (err != TxnErrorCode::TXN_OK) {
8016
0
            return 0;
8017
0
        }
8018
1
        index_pb.Clear();
8019
1
        if (!index_pb.ParseFromString(val)) {
8020
0
            return 0;
8021
0
        }
8022
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
8023
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
8024
0
                LOG_WARNING("table stream recycle index is missing binding")
8025
0
                        .tag("instance_id", instance_id_)
8026
0
                        .tag("stream_id", index_id);
8027
0
                return 0;
8028
0
            }
8029
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
8030
2
                std::string end = prefix;
8031
2
                end.push_back('\xff');
8032
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
8033
6
                                                              std::string_view value) {
8034
6
                    stream_metrics_context.total_need_recycle_num++;
8035
6
                    stream_metrics_context.total_need_recycle_data_size +=
8036
6
                            key.size() + value.size();
8037
6
                    return 0;
8038
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
8033
6
                                                              std::string_view value) {
8034
6
                    stream_metrics_context.total_need_recycle_num++;
8035
6
                    stream_metrics_context.total_need_recycle_data_size +=
8036
6
                            key.size() + value.size();
8037
6
                    return 0;
8038
6
                };
8039
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
8040
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
8029
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
8030
2
                std::string end = prefix;
8031
2
                end.push_back('\xff');
8032
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
8033
2
                                                              std::string_view value) {
8034
2
                    stream_metrics_context.total_need_recycle_num++;
8035
2
                    stream_metrics_context.total_need_recycle_data_size +=
8036
2
                            key.size() + value.size();
8037
2
                    return 0;
8038
2
                };
8039
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
8040
2
            };
8041
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
8042
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
8043
1
                    index_id);
8044
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
8045
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
8046
1
                    index_id);
8047
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
8048
1
                scan_offset_prefix(versioned_prefix) != 0) {
8049
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
8050
0
                        .tag("instance_id", instance_id_)
8051
0
                        .tag("stream_id", index_id);
8052
0
            }
8053
1
            return 0;
8054
1
        }
8055
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
8056
0
            return 0;
8057
0
        }
8058
0
        metrics_context.total_need_recycle_num++;
8059
0
        return 0;
8060
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
7988
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7989
1
        RecycleIndexPB index_pb;
7990
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7991
0
            return 0;
7992
0
        }
7993
1
        int64_t current_time = ::time(nullptr);
7994
1
        if (current_time <
7995
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7996
0
            return 0;
7997
0
        }
7998
        // decode index_id
7999
1
        auto k1 = k;
8000
1
        k1.remove_prefix(1);
8001
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8002
1
        decode_key(&k1, &out);
8003
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
8004
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
8005
1
        std::unique_ptr<Transaction> txn;
8006
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8007
1
        if (err != TxnErrorCode::TXN_OK) {
8008
0
            return 0;
8009
0
        }
8010
1
        std::string val;
8011
1
        err = txn->get(k, &val);
8012
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8013
0
            return 0;
8014
0
        }
8015
1
        if (err != TxnErrorCode::TXN_OK) {
8016
0
            return 0;
8017
0
        }
8018
1
        index_pb.Clear();
8019
1
        if (!index_pb.ParseFromString(val)) {
8020
0
            return 0;
8021
0
        }
8022
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
8023
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
8024
0
                LOG_WARNING("table stream recycle index is missing binding")
8025
0
                        .tag("instance_id", instance_id_)
8026
0
                        .tag("stream_id", index_id);
8027
0
                return 0;
8028
0
            }
8029
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
8030
1
                std::string end = prefix;
8031
1
                end.push_back('\xff');
8032
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
8033
1
                                                              std::string_view value) {
8034
1
                    stream_metrics_context.total_need_recycle_num++;
8035
1
                    stream_metrics_context.total_need_recycle_data_size +=
8036
1
                            key.size() + value.size();
8037
1
                    return 0;
8038
1
                };
8039
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
8040
1
            };
8041
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
8042
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
8043
1
                    index_id);
8044
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
8045
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
8046
1
                    index_id);
8047
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
8048
1
                scan_offset_prefix(versioned_prefix) != 0) {
8049
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
8050
0
                        .tag("instance_id", instance_id_)
8051
0
                        .tag("stream_id", index_id);
8052
0
            }
8053
1
            return 0;
8054
1
        }
8055
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
8056
0
            return 0;
8057
0
        }
8058
0
        metrics_context.total_need_recycle_num++;
8059
0
        return 0;
8060
0
    };
8061
8062
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
8063
1
    metrics_context.report(true);
8064
1
    stream_metrics_context.report(true);
8065
1
    segment_metrics_context_.report(true);
8066
1
    tablet_metrics_context_.report(true);
8067
1
    return ret;
8068
1
}
8069
8070
// Scan and statistics partitions that need to be recycled
8071
0
int InstanceRecycler::scan_and_statistics_partitions() {
8072
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
8073
8074
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
8075
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
8076
0
    std::string part_key0;
8077
0
    std::string part_key1;
8078
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8079
8080
0
    recycle_partition_key(part_key_info0, &part_key0);
8081
0
    recycle_partition_key(part_key_info1, &part_key1);
8082
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
8083
0
        RecyclePartitionPB part_pb;
8084
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
8085
0
            return 0;
8086
0
        }
8087
0
        int64_t current_time = ::time(nullptr);
8088
0
        if (current_time <
8089
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
8090
0
            return 0;
8091
0
        }
8092
        // decode partition_id
8093
0
        auto k1 = k;
8094
0
        k1.remove_prefix(1);
8095
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8096
0
        decode_key(&k1, &out);
8097
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
8098
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
8099
        // Change state to RECYCLING
8100
0
        std::unique_ptr<Transaction> txn;
8101
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8102
0
        if (err != TxnErrorCode::TXN_OK) {
8103
0
            return 0;
8104
0
        }
8105
0
        std::string val;
8106
0
        err = txn->get(k, &val);
8107
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8108
0
            return 0;
8109
0
        }
8110
0
        if (err != TxnErrorCode::TXN_OK) {
8111
0
            return 0;
8112
0
        }
8113
0
        part_pb.Clear();
8114
0
        if (!part_pb.ParseFromString(val)) {
8115
0
            return 0;
8116
0
        }
8117
        // Partitions with PREPARED state MUST have no data
8118
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
8119
0
        int ret = 0;
8120
0
        for (int64_t index_id : part_pb.index_id()) {
8121
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
8122
0
                                            partition_id, is_empty_tablet) != 0) {
8123
0
                ret = 0;
8124
0
            }
8125
0
        }
8126
0
        metrics_context.total_need_recycle_num++;
8127
0
        return ret;
8128
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_
8129
8130
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
8131
0
    metrics_context.report(true);
8132
0
    segment_metrics_context_.report(true);
8133
0
    tablet_metrics_context_.report(true);
8134
0
    return ret;
8135
0
}
8136
8137
// Scan and statistics rowsets that need to be recycled
8138
0
int InstanceRecycler::scan_and_statistics_rowsets() {
8139
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
8140
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
8141
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
8142
0
    std::string recyc_rs_key0;
8143
0
    std::string recyc_rs_key1;
8144
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
8145
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
8146
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8147
8148
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
8149
0
        RecycleRowsetPB rowset;
8150
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8151
0
            return 0;
8152
0
        }
8153
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
8154
0
        int64_t current_time = ::time(nullptr);
8155
0
        if (current_time <
8156
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
8157
0
            return 0;
8158
0
        }
8159
8160
0
        if (!rowset.has_type()) {
8161
0
            if (!rowset.has_resource_id()) [[unlikely]] {
8162
0
                return 0;
8163
0
            }
8164
0
            if (rowset.resource_id().empty()) [[unlikely]] {
8165
0
                return 0;
8166
0
            }
8167
0
            metrics_context.total_need_recycle_num++;
8168
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8169
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
8170
0
            segment_metrics_context_.total_need_recycle_data_size +=
8171
0
                    rowset.rowset_meta().total_disk_size();
8172
0
            return 0;
8173
0
        }
8174
8175
0
        if (config::enable_mark_delete_rowset_before_recycle &&
8176
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
8177
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
8178
0
            return 0;
8179
0
        }
8180
8181
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
8182
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
8183
0
                return 0;
8184
0
            }
8185
0
        }
8186
0
        metrics_context.total_need_recycle_num++;
8187
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
8188
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
8189
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8190
0
        return 0;
8191
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_
8192
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8193
0
    metrics_context.report(true);
8194
0
    segment_metrics_context_.report(true);
8195
0
    return ret;
8196
0
}
8197
8198
// Scan and statistics tmp_rowsets that need to be recycled
8199
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8200
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8201
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8202
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8203
0
    std::string tmp_rs_key0;
8204
0
    std::string tmp_rs_key1;
8205
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8206
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8207
8208
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8209
8210
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8211
0
        doris::RowsetMetaCloudPB rowset;
8212
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8213
0
            return 0;
8214
0
        }
8215
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8216
0
        int64_t current_time = ::time(nullptr);
8217
0
        if (current_time < expiration) {
8218
0
            return 0;
8219
0
        }
8220
8221
0
        DCHECK_GT(rowset.txn_id(), 0)
8222
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8223
8224
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
8225
0
            return 0;
8226
0
        }
8227
8228
0
        if (!rowset.has_resource_id()) {
8229
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8230
0
                return 0;
8231
0
            }
8232
0
            return 0;
8233
0
        }
8234
8235
0
        metrics_context.total_need_recycle_num++;
8236
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8237
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8238
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8239
0
        return 0;
8240
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_
8241
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8242
0
    metrics_context.report(true);
8243
0
    segment_metrics_context_.report(true);
8244
0
    return ret;
8245
0
}
8246
8247
// Scan and statistics abort_timeout_txn that need to be recycled
8248
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8249
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8250
8251
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8252
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8253
0
    std::string begin_txn_running_key;
8254
0
    std::string end_txn_running_key;
8255
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8256
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8257
8258
0
    int64_t current_time =
8259
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8260
8261
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8262
0
                                               std::string_view k, std::string_view v) -> int {
8263
0
        std::unique_ptr<Transaction> txn;
8264
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8265
0
        if (err != TxnErrorCode::TXN_OK) {
8266
0
            return 0;
8267
0
        }
8268
0
        std::string_view k1 = k;
8269
0
        k1.remove_prefix(1);
8270
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8271
0
        if (decode_key(&k1, &out) != 0) {
8272
0
            return 0;
8273
0
        }
8274
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8275
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8276
        // Update txn_info
8277
0
        std::string txn_inf_key, txn_inf_val;
8278
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8279
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8280
0
        if (err != TxnErrorCode::TXN_OK) {
8281
0
            return 0;
8282
0
        }
8283
0
        TxnInfoPB txn_info;
8284
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8285
0
            return 0;
8286
0
        }
8287
8288
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8289
0
            TxnRunningPB txn_running_pb;
8290
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8291
0
                return 0;
8292
0
            }
8293
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8294
0
                return 0;
8295
0
            }
8296
0
            metrics_context.total_need_recycle_num++;
8297
0
        }
8298
0
        return 0;
8299
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_
8300
8301
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
8302
0
                               std::move(handle_abort_timeout_txn_kv));
8303
0
    metrics_context.report(true);
8304
0
    return ret;
8305
0
}
8306
8307
// Scan and statistics expired_txn_label that need to be recycled
8308
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8309
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8310
8311
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8312
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8313
0
    std::string begin_recycle_txn_key;
8314
0
    std::string end_recycle_txn_key;
8315
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8316
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8317
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8318
0
    int64_t current_time_ms =
8319
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8320
8321
    // for calculate the total num or bytes of recyled objects
8322
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8323
0
        RecycleTxnPB recycle_txn_pb;
8324
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8325
0
            return 0;
8326
0
        }
8327
0
        if ((config::force_immediate_recycle) ||
8328
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8329
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8330
0
             current_time_ms)) {
8331
0
            metrics_context.total_need_recycle_num++;
8332
0
        }
8333
0
        return 0;
8334
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_
8335
8336
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
8337
0
                               std::move(handle_expired_txn_label_kv));
8338
0
    metrics_context.report(true);
8339
0
    return ret;
8340
0
}
8341
8342
// Scan and statistics copy_jobs that need to be recycled
8343
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8344
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8345
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8346
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8347
0
    std::string key0;
8348
0
    std::string key1;
8349
0
    copy_job_key(key_info0, &key0);
8350
0
    copy_job_key(key_info1, &key1);
8351
8352
    // for calculate the total num or bytes of recyled objects
8353
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8354
0
        CopyJobPB copy_job;
8355
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8356
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8357
0
            return 0;
8358
0
        }
8359
8360
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8361
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8362
0
                int64_t current_time =
8363
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8364
0
                if (copy_job.finish_time_ms() > 0) {
8365
0
                    if (!config::force_immediate_recycle &&
8366
0
                        current_time < copy_job.finish_time_ms() +
8367
0
                                               config::copy_job_max_retention_second * 1000) {
8368
0
                        return 0;
8369
0
                    }
8370
0
                } else {
8371
0
                    if (!config::force_immediate_recycle &&
8372
0
                        current_time < copy_job.start_time_ms() +
8373
0
                                               config::copy_job_max_retention_second * 1000) {
8374
0
                        return 0;
8375
0
                    }
8376
0
                }
8377
0
            }
8378
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8379
0
            int64_t current_time =
8380
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8381
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8382
0
                return 0;
8383
0
            }
8384
0
        }
8385
0
        metrics_context.total_need_recycle_num++;
8386
0
        return 0;
8387
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_
8388
8389
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8390
0
    metrics_context.report(true);
8391
0
    return ret;
8392
0
}
8393
8394
// Scan and statistics stage that need to be recycled
8395
0
int InstanceRecycler::scan_and_statistics_stage() {
8396
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8397
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8398
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8399
0
    std::string key0 = recycle_stage_key(key_info0);
8400
0
    std::string key1 = recycle_stage_key(key_info1);
8401
8402
    // for calculate the total num or bytes of recyled objects
8403
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8404
0
                                                        std::string_view v) -> int {
8405
0
        RecycleStagePB recycle_stage;
8406
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8407
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8408
0
            return 0;
8409
0
        }
8410
8411
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8412
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8413
0
            LOG(WARNING) << "invalid idx: " << idx;
8414
0
            return 0;
8415
0
        }
8416
8417
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8418
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8419
0
                [&] {
8420
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8421
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8422
0
                    if (!s3_conf) {
8423
0
                        return 0;
8424
0
                    }
8425
8426
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8427
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8428
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8429
0
                    if (ret != 0) {
8430
0
                        return 0;
8431
0
                    }
8432
8433
0
                    accessor = std::move(s3_accessor);
8434
0
                    return 0;
8435
0
                }(),
8436
0
                "recycle_stage:get_accessor", &accessor);
8437
8438
0
        if (ret != 0) {
8439
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8440
0
            return 0;
8441
0
        }
8442
8443
0
        metrics_context.total_need_recycle_num++;
8444
0
        return 0;
8445
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_
8446
8447
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8448
0
    metrics_context.report(true);
8449
0
    return ret;
8450
0
}
8451
8452
// Scan and statistics expired_stage_objects that need to be recycled
8453
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8454
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8455
8456
    // for calculate the total num or bytes of recyled objects
8457
0
    auto scan_and_statistics = [&metrics_context, this]() {
8458
0
        for (const auto& stage : instance_info_.stages()) {
8459
0
            if (stopped()) {
8460
0
                break;
8461
0
            }
8462
0
            if (stage.type() == StagePB::EXTERNAL) {
8463
0
                continue;
8464
0
            }
8465
0
            int idx = stoi(stage.obj_info().id());
8466
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8467
0
                continue;
8468
0
            }
8469
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8470
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8471
0
            if (!s3_conf) {
8472
0
                continue;
8473
0
            }
8474
0
            s3_conf->prefix = stage.obj_info().prefix();
8475
0
            std::shared_ptr<S3Accessor> accessor;
8476
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8477
0
            if (ret1 != 0) {
8478
0
                continue;
8479
0
            }
8480
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8481
0
                continue;
8482
0
            }
8483
0
            metrics_context.total_need_recycle_num++;
8484
0
        }
8485
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8486
8487
0
    scan_and_statistics();
8488
0
    metrics_context.report(true);
8489
0
    return 0;
8490
0
}
8491
8492
// Scan and statistics versions that need to be recycled
8493
0
int InstanceRecycler::scan_and_statistics_versions() {
8494
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8495
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8496
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8497
8498
0
    int64_t last_scanned_table_id = 0;
8499
0
    bool is_recycled = false; // Is last scanned kv recycled
8500
    // for calculate the total num or bytes of recyled objects
8501
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8502
0
                                       std::string_view k, std::string_view) {
8503
0
        auto k1 = k;
8504
0
        k1.remove_prefix(1);
8505
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8506
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8507
0
        decode_key(&k1, &out);
8508
0
        DCHECK_EQ(out.size(), 6) << k;
8509
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8510
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8511
0
            metrics_context.total_need_recycle_num +=
8512
0
                    is_recycled; // Version kv of this table has been recycled
8513
0
            return 0;
8514
0
        }
8515
0
        last_scanned_table_id = table_id;
8516
0
        is_recycled = false;
8517
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8518
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8519
0
        std::unique_ptr<Transaction> txn;
8520
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8521
0
        if (err != TxnErrorCode::TXN_OK) {
8522
0
            return 0;
8523
0
        }
8524
0
        std::unique_ptr<RangeGetIterator> iter;
8525
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8526
0
        if (err != TxnErrorCode::TXN_OK) {
8527
0
            return 0;
8528
0
        }
8529
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8530
0
            return 0;
8531
0
        }
8532
0
        metrics_context.total_need_recycle_num++;
8533
0
        is_recycled = true;
8534
0
        return 0;
8535
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_
8536
8537
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8538
0
    metrics_context.report(true);
8539
0
    return ret;
8540
0
}
8541
8542
// Scan and statistics restore jobs that need to be recycled
8543
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8544
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8545
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8546
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8547
0
    std::string restore_job_key0;
8548
0
    std::string restore_job_key1;
8549
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8550
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8551
8552
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8553
8554
    // for calculate the total num or bytes of recyled objects
8555
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8556
0
        RestoreJobCloudPB restore_job_pb;
8557
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8558
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8559
0
            return 0;
8560
0
        }
8561
0
        int64_t expiration =
8562
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8563
0
        int64_t current_time = ::time(nullptr);
8564
0
        if (current_time < expiration) { // not expired
8565
0
            return 0;
8566
0
        }
8567
0
        metrics_context.total_need_recycle_num++;
8568
0
        if (restore_job_pb.need_recycle_data()) {
8569
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8570
0
        }
8571
0
        return 0;
8572
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_
8573
8574
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8575
0
    metrics_context.report(true);
8576
0
    return ret;
8577
0
}
8578
8579
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8580
3
    if (!should_recycle_versioned_keys()) {
8581
0
        return;
8582
0
    }
8583
8584
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8585
8586
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8587
3
    if (recycle_checker.init() != 0) {
8588
0
        return;
8589
0
    }
8590
8591
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8592
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8593
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8594
8595
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8596
8
    for (; iter->valid(); iter->next()) {
8597
5
        OperationLogPB operation_log;
8598
5
        if (!iter->parse_value(&operation_log)) {
8599
0
            continue;
8600
0
        }
8601
8602
5
        std::string_view key = iter->key();
8603
5
        Versionstamp log_versionstamp;
8604
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8605
0
            continue;
8606
0
        }
8607
8608
5
        OperationLogReferenceInfo ref_info;
8609
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8610
5
                                        &ref_info)) {
8611
4
            metrics_context.total_need_recycle_num++;
8612
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8613
4
        }
8614
5
    }
8615
8616
3
    metrics_context.report(true);
8617
3
}
8618
8619
int InstanceRecycler::classify_rowset_task_by_ref_count(
8620
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8621
60
    constexpr int MAX_RETRY = 10;
8622
60
    const auto& rowset_meta = task.rowset_meta;
8623
60
    int64_t tablet_id = rowset_meta.tablet_id();
8624
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8625
60
    std::string_view reference_instance_id = instance_id_;
8626
60
    if (rowset_meta.has_reference_instance_id()) {
8627
5
        reference_instance_id = rowset_meta.reference_instance_id();
8628
5
    }
8629
8630
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8631
61
        std::unique_ptr<Transaction> txn;
8632
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8633
61
        if (err != TxnErrorCode::TXN_OK) {
8634
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8635
0
                    .tag("instance_id", instance_id_)
8636
0
                    .tag("tablet_id", tablet_id)
8637
0
                    .tag("rowset_id", rowset_id)
8638
0
                    .tag("err", err);
8639
0
            return -1;
8640
0
        }
8641
8642
61
        std::string rowset_ref_count_key =
8643
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8644
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8645
8646
61
        int64_t ref_count = 0;
8647
61
        {
8648
61
            std::string value;
8649
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8650
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8651
0
                ref_count = 1;
8652
61
            } else if (err != TxnErrorCode::TXN_OK) {
8653
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8654
0
                        .tag("instance_id", instance_id_)
8655
0
                        .tag("tablet_id", tablet_id)
8656
0
                        .tag("rowset_id", rowset_id)
8657
0
                        .tag("err", err);
8658
0
                return -1;
8659
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8660
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8661
0
                        .tag("instance_id", instance_id_)
8662
0
                        .tag("tablet_id", tablet_id)
8663
0
                        .tag("rowset_id", rowset_id)
8664
0
                        .tag("value", hex(value));
8665
0
                return -1;
8666
0
            }
8667
61
        }
8668
8669
61
        if (ref_count > 1) {
8670
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8671
12
            txn->atomic_add(rowset_ref_count_key, -1);
8672
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8673
12
                    .tag("instance_id", instance_id_)
8674
12
                    .tag("tablet_id", tablet_id)
8675
12
                    .tag("rowset_id", rowset_id)
8676
12
                    .tag("ref_count", ref_count - 1)
8677
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8678
8679
12
            if (!task.recycle_rowset_key.empty()) {
8680
0
                txn->remove(task.recycle_rowset_key);
8681
0
                LOG_INFO("remove recycle rowset key in classification phase")
8682
0
                        .tag("key", hex(task.recycle_rowset_key));
8683
0
            }
8684
12
            if (!task.non_versioned_rowset_key.empty()) {
8685
12
                txn->remove(task.non_versioned_rowset_key);
8686
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8687
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8688
12
            }
8689
8690
12
            err = txn->commit();
8691
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8692
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8693
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8694
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8695
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8696
1
                continue;
8697
11
            } else if (err != TxnErrorCode::TXN_OK) {
8698
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8699
0
                        .tag("instance_id", instance_id_)
8700
0
                        .tag("tablet_id", tablet_id)
8701
0
                        .tag("rowset_id", rowset_id)
8702
0
                        .tag("err", err);
8703
0
                return -1;
8704
0
            }
8705
11
            return 1; // handled, not added to batch delete
8706
49
        } else {
8707
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8708
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8709
49
            LOG_INFO("add rowset to batch delete plan")
8710
49
                    .tag("instance_id", instance_id_)
8711
49
                    .tag("tablet_id", tablet_id)
8712
49
                    .tag("rowset_id", rowset_id)
8713
49
                    .tag("resource_id", rowset_meta.resource_id())
8714
49
                    .tag("ref_count", ref_count);
8715
8716
49
            batch_delete_tasks.push_back(std::move(task));
8717
49
            return 0; // added to batch delete
8718
49
        }
8719
61
    }
8720
8721
0
    LOG_WARNING("failed to classify rowset task after retry")
8722
0
            .tag("instance_id", instance_id_)
8723
0
            .tag("tablet_id", tablet_id)
8724
0
            .tag("rowset_id", rowset_id)
8725
0
            .tag("retry", MAX_RETRY);
8726
0
    return -1;
8727
60
}
8728
8729
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8730
10
    int ret = 0;
8731
49
    for (const auto& task : tasks) {
8732
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8733
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8734
8735
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8736
        // so we don't need to call it again here.
8737
8738
        // Remove all metadata keys in one transaction
8739
49
        std::unique_ptr<Transaction> txn;
8740
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8741
49
        if (err != TxnErrorCode::TXN_OK) {
8742
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8743
0
                    .tag("instance_id", instance_id_)
8744
0
                    .tag("tablet_id", tablet_id)
8745
0
                    .tag("rowset_id", rowset_id)
8746
0
                    .tag("err", err);
8747
0
            ret = -1;
8748
0
            continue;
8749
0
        }
8750
8751
49
        std::string_view reference_instance_id = instance_id_;
8752
49
        if (task.rowset_meta.has_reference_instance_id()) {
8753
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8754
0
        }
8755
8756
49
        txn->remove(task.rowset_ref_count_key);
8757
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8758
49
                .tag("instance_id", instance_id_)
8759
49
                .tag("tablet_id", tablet_id)
8760
49
                .tag("rowset_id", rowset_id)
8761
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8762
8763
49
        std::string dbm_start_key =
8764
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8765
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8766
49
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8767
49
                 std::numeric_limits<int64_t>::max()});
8768
49
        txn->remove(dbm_start_key, dbm_end_key);
8769
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8770
49
                .tag("instance_id", instance_id_)
8771
49
                .tag("tablet_id", tablet_id)
8772
49
                .tag("rowset_id", rowset_id)
8773
49
                .tag("begin", hex(dbm_start_key))
8774
49
                .tag("end", hex(dbm_end_key));
8775
8776
49
        std::string versioned_dbm_start_key =
8777
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8778
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8779
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8780
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8781
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8782
49
                .tag("instance_id", instance_id_)
8783
49
                .tag("tablet_id", tablet_id)
8784
49
                .tag("rowset_id", rowset_id)
8785
49
                .tag("begin", hex(versioned_dbm_start_key))
8786
49
                .tag("end", hex(versioned_dbm_end_key));
8787
8788
        // Remove versioned meta rowset key
8789
49
        if (!task.versioned_rowset_key.empty()) {
8790
49
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8791
49
                                                          task.versionstamp);
8792
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8793
49
                    .tag("instance_id", instance_id_)
8794
49
                    .tag("tablet_id", tablet_id)
8795
49
                    .tag("rowset_id", rowset_id)
8796
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8797
49
        }
8798
8799
49
        if (!task.non_versioned_rowset_key.empty()) {
8800
49
            txn->remove(task.non_versioned_rowset_key);
8801
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8802
49
                    .tag("instance_id", instance_id_)
8803
49
                    .tag("tablet_id", tablet_id)
8804
49
                    .tag("rowset_id", rowset_id)
8805
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8806
49
        }
8807
8808
        // Remove recycle_rowset_key last to ensure retry safety:
8809
        // if cleanup fails, this key remains and triggers next round retry.
8810
49
        if (!task.recycle_rowset_key.empty()) {
8811
0
            txn->remove(task.recycle_rowset_key);
8812
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8813
0
                    .tag("instance_id", instance_id_)
8814
0
                    .tag("tablet_id", tablet_id)
8815
0
                    .tag("rowset_id", rowset_id)
8816
0
                    .tag("key", hex(task.recycle_rowset_key));
8817
0
        }
8818
8819
49
        err = txn->commit();
8820
49
        if (err != TxnErrorCode::TXN_OK) {
8821
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8822
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8823
0
                    .tag("instance_id", instance_id_)
8824
0
                    .tag("tablet_id", tablet_id)
8825
0
                    .tag("rowset_id", rowset_id)
8826
0
                    .tag("err", err);
8827
0
            ret = -1;
8828
0
            continue;
8829
0
        }
8830
8831
49
        LOG_INFO("cleanup rowset metadata success")
8832
49
                .tag("instance_id", instance_id_)
8833
49
                .tag("tablet_id", tablet_id)
8834
49
                .tag("rowset_id", rowset_id);
8835
49
    }
8836
10
    return ret;
8837
10
}
8838
8839
} // namespace doris::cloud