Coverage Report

Created: 2026-09-16 10:37

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 <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
constexpr size_t kRowsetBatchGetSize = 256;
89
90
0
int64_t packed_file_retry_sleep_ms() {
91
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
92
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
93
0
    thread_local std::mt19937_64 gen(std::random_device {}());
94
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
95
0
    return dist(gen);
96
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
97
98
0
void sleep_for_packed_file_retry() {
99
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
100
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
101
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
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
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
110
111
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
869k
    const auto& locations = rowset.packed_slice_locations();
113
869k
    auto it = locations.find(path);
114
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
869k
           !it->second.packed_file_path().empty();
116
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
7
    const auto& locations = rowset.packed_slice_locations();
113
7
    auto it = locations.find(path);
114
7
    return it != locations.end() && it->second.has_packed_file_path() &&
115
7
           !it->second.packed_file_path().empty();
116
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
869k
    const auto& locations = rowset.packed_slice_locations();
113
869k
    auto it = locations.find(path);
114
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
869k
           !it->second.packed_file_path().empty();
116
869k
}
117
118
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
119
                                      const std::string& path,
120
869k
                                      std::vector<std::string>* file_paths) {
121
870k
    if (!is_packed_slice_path(rowset, path)) {
122
870k
        file_paths->push_back(path);
123
870k
    }
124
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
7
                                      std::vector<std::string>* file_paths) {
121
7
    if (!is_packed_slice_path(rowset, path)) {
122
7
        file_paths->push_back(path);
123
7
    }
124
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
869k
                                      std::vector<std::string>* file_paths) {
121
870k
    if (!is_packed_slice_path(rowset, path)) {
122
870k
        file_paths->push_back(path);
123
870k
    }
124
869k
}
125
126
} // namespace
127
128
// return 0 for success get a key, 1 for key not found, negative for error
129
16
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
16
    std::unique_ptr<Transaction> txn;
131
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
16
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
16
    switch (txn->get(key, &val, true)) {
136
6
    case TxnErrorCode::TXN_OK:
137
6
        return 0;
138
10
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
10
        return 1;
140
0
    default:
141
0
        return -1;
142
16
    };
143
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
10
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
10
    std::unique_ptr<Transaction> txn;
131
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
10
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
10
    switch (txn->get(key, &val, true)) {
136
3
    case TxnErrorCode::TXN_OK:
137
3
        return 0;
138
7
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
7
        return 1;
140
0
    default:
141
0
        return -1;
142
10
    };
143
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
6
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
6
    std::unique_ptr<Transaction> txn;
131
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
6
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
6
    switch (txn->get(key, &val, true)) {
136
3
    case TxnErrorCode::TXN_OK:
137
3
        return 0;
138
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
3
        return 1;
140
0
    default:
141
0
        return -1;
142
6
    };
143
0
}
144
145
// 0 for success, negative for error
146
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
147
330
                   std::unique_ptr<RangeGetIterator>& it) {
148
330
    std::unique_ptr<Transaction> txn;
149
330
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
330
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
330
    switch (txn->get(begin, end, &it, true)) {
154
330
    case TxnErrorCode::TXN_OK:
155
330
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
330
    };
161
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
19
                   std::unique_ptr<RangeGetIterator>& it) {
148
19
    std::unique_ptr<Transaction> txn;
149
19
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
19
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
19
    switch (txn->get(begin, end, &it, true)) {
154
19
    case TxnErrorCode::TXN_OK:
155
19
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
19
    };
161
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
311
                   std::unique_ptr<RangeGetIterator>& it) {
148
311
    std::unique_ptr<Transaction> txn;
149
311
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
311
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
311
    switch (txn->get(begin, end, &it, true)) {
154
311
    case TxnErrorCode::TXN_OK:
155
311
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
311
    };
161
0
}
162
163
// return 0 for success otherwise error
164
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
5
    std::unique_ptr<Transaction> txn;
166
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
5
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
9
    for (auto k : keys) {
171
9
        txn->remove(k);
172
9
    }
173
5
    switch (txn->commit()) {
174
5
    case TxnErrorCode::TXN_OK:
175
5
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
5
    }
181
5
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
164
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
5
    std::unique_ptr<Transaction> txn;
166
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
5
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
9
    for (auto k : keys) {
171
9
        txn->remove(k);
172
9
    }
173
5
    switch (txn->commit()) {
174
5
    case TxnErrorCode::TXN_OK:
175
5
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
5
    }
181
5
}
182
183
// return 0 for success otherwise error
184
385
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
385
    std::unique_ptr<Transaction> txn;
186
385
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
385
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
106k
    for (auto& k : keys) {
191
106k
        txn->remove(k);
192
106k
    }
193
385
    switch (txn->commit()) {
194
385
    case TxnErrorCode::TXN_OK:
195
385
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
385
    }
201
385
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
40
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
40
    std::unique_ptr<Transaction> txn;
186
40
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
40
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
40
    for (auto& k : keys) {
191
17
        txn->remove(k);
192
17
    }
193
40
    switch (txn->commit()) {
194
40
    case TxnErrorCode::TXN_OK:
195
40
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
40
    }
201
40
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
345
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
345
    std::unique_ptr<Transaction> txn;
186
345
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
345
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
106k
    for (auto& k : keys) {
191
106k
        txn->remove(k);
192
106k
    }
193
345
    switch (txn->commit()) {
194
345
    case TxnErrorCode::TXN_OK:
195
345
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
345
    }
201
345
}
202
203
// return 0 for success otherwise error
204
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
205
102k
                                       std::string_view end) {
206
102k
    std::unique_ptr<Transaction> txn;
207
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
102k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
102k
    txn->remove(begin, end);
212
102k
    switch (txn->commit()) {
213
102k
    case TxnErrorCode::TXN_OK:
214
102k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
102k
    }
220
102k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
14
                                       std::string_view end) {
206
14
    std::unique_ptr<Transaction> txn;
207
14
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
14
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
14
    txn->remove(begin, end);
212
14
    switch (txn->commit()) {
213
14
    case TxnErrorCode::TXN_OK:
214
14
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
14
    }
220
14
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
102k
                                       std::string_view end) {
206
102k
    std::unique_ptr<Transaction> txn;
207
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
102k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
102k
    txn->remove(begin, end);
212
102k
    switch (txn->commit()) {
213
102k
    case TxnErrorCode::TXN_OK:
214
102k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
102k
    }
220
102k
}
221
222
// Remove versioned delete bitmap keys grouped by rowset.
223
// Each inner vector represents all DBM shard keys for one rowset that MUST be deleted
224
// atomically in the same txn. Transaction splitting only occurs between rowsets, never
225
// within a rowset's shard keys.
226
//
227
// This ensures that a DBM blob with multiple shards is either fully deleted or not
228
// deleted at all, preventing partial deletion that would leave the blob unrecoverable.
229
//
230
// return 0 for success otherwise error
231
static int delete_versioned_delete_bitmap_by_rowset(
232
15
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
15
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
14
    size_t idx = 0;
237
29
    while (idx < rowset_dbm_key_groups.size()) {
238
15
        std::unique_ptr<Transaction> txn;
239
15
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
15
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
15
        bool has_keys = false;
245
1.58k
        while (idx < rowset_dbm_key_groups.size()) {
246
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
247
1.57k
            const auto keys_bytes =
248
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
249
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
249
1.61k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
250
251
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
252
1
                break;
253
1
            }
254
255
1.60k
            for (const auto& key : keys) {
256
1.60k
                txn->remove(key);
257
1.60k
            }
258
259
1.56k
            has_keys = true;
260
1.56k
            ++idx;
261
1.56k
        }
262
263
15
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
15
        err = txn->commit();
265
15
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
15
    }
270
14
    return 0;
271
14
}
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
232
15
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
15
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
14
    size_t idx = 0;
237
29
    while (idx < rowset_dbm_key_groups.size()) {
238
15
        std::unique_ptr<Transaction> txn;
239
15
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
15
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
15
        bool has_keys = false;
245
1.58k
        while (idx < rowset_dbm_key_groups.size()) {
246
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
247
1.57k
            const auto keys_bytes =
248
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
249
1.57k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
250
251
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
252
1
                break;
253
1
            }
254
255
1.60k
            for (const auto& key : keys) {
256
1.60k
                txn->remove(key);
257
1.60k
            }
258
259
1.56k
            has_keys = true;
260
1.56k
            ++idx;
261
1.56k
        }
262
263
15
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
15
        err = txn->commit();
265
15
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
15
    }
270
14
    return 0;
271
14
}
272
273
void scan_restore_job_rowset(
274
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
275
        std::string& msg,
276
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
277
278
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
279
                                      int64_t num_scanned, int64_t num_recycled,
280
50
                                      int64_t start_time) {
281
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
282
0
        int64_t cost =
283
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
284
0
        if (cost > config::recycle_task_threshold_seconds) {
285
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
286
0
                    .tag("instance_id", instance_id)
287
0
                    .tag("task", task_name)
288
0
                    .tag("num_scanned", num_scanned)
289
0
                    .tag("num_recycled", num_recycled);
290
0
        }
291
0
    }
292
50
    return;
293
50
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
280
50
                                      int64_t start_time) {
281
50
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
282
0
        int64_t cost =
283
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
284
0
        if (cost > config::recycle_task_threshold_seconds) {
285
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
286
0
                    .tag("instance_id", instance_id)
287
0
                    .tag("task", task_name)
288
0
                    .tag("num_scanned", num_scanned)
289
0
                    .tag("num_recycled", num_recycled);
290
0
        }
291
0
    }
292
50
    return;
293
50
}
294
295
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
296
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
297
298
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
299
6
                                                               "s3_producer_pool");
300
6
    s3_producer_pool->start();
301
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
302
6
                                                                  "recycle_tablet_pool");
303
6
    recycle_tablet_pool->start();
304
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
305
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
306
6
    group_recycle_function_pool->start();
307
6
    _thread_pool_group =
308
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
309
6
                                    std::move(group_recycle_function_pool));
310
311
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
312
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
313
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
314
6
}
315
316
6
Recycler::~Recycler() {
317
6
    if (!stopped()) {
318
0
        stop();
319
0
    }
320
6
}
321
322
5
void Recycler::instance_scanner_callback() {
323
    // sleep 60 seconds before scheduling for the launch procedure to complete:
324
    // some bad hdfs connection may cause some log to stdout stderr
325
    // which may pollute .out file and affect the script to check success
326
5
    std::this_thread::sleep_for(
327
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
328
974
    while (!stopped()) {
329
969
        if (config::enable_recycler) {
330
4
            std::vector<InstanceInfoPB> instances;
331
4
            get_all_instances(txn_kv_.get(), instances);
332
            // TODO(plat1ko): delete job recycle kv of non-existent instances
333
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
334
4
                std::stringstream ss;
335
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
336
4
                return ss.str();
337
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
333
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
334
4
                std::stringstream ss;
335
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
336
4
                return ss.str();
337
4
            }();
338
4
            if (!instances.empty()) {
339
                // enqueue instances
340
3
                std::lock_guard lock(mtx_);
341
30
                for (auto& instance : instances) {
342
30
                    if (filter_out_instance(instance.instance_id())) continue;
343
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
344
                    // skip instance already in pending queue
345
30
                    if (success) {
346
30
                        pending_instance_queue_.push_back(std::move(instance));
347
30
                    }
348
30
                }
349
3
                pending_instance_cond_.notify_all();
350
3
            }
351
965
        } else {
352
965
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
353
965
        }
354
969
        {
355
969
            std::unique_lock lock(mtx_);
356
969
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
357
1.93k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
357
1.93k
                               [&]() { return stopped(); });
358
969
        }
359
969
    }
360
5
}
361
362
9
void Recycler::recycle_callback() {
363
40
    while (!stopped()) {
364
37
        InstanceInfoPB instance;
365
37
        {
366
37
            std::unique_lock lock(mtx_);
367
37
            pending_instance_cond_.wait(
368
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
368
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
369
37
            if (stopped()) {
370
6
                return;
371
6
            }
372
31
            instance = std::move(pending_instance_queue_.front());
373
31
            pending_instance_queue_.pop_front();
374
31
            pending_instance_set_.erase(instance.instance_id());
375
31
        }
376
0
        auto& instance_id = instance.instance_id();
377
31
        {
378
31
            std::lock_guard lock(mtx_);
379
            // skip instance in recycling
380
31
            if (recycling_instance_map_.count(instance_id)) continue;
381
31
        }
382
31
        if (!config::enable_recycler) {
383
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
384
1
                         << " since enable_recycler is false";
385
1
            continue;
386
1
        }
387
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
388
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
389
390
30
        if (int r = instance_recycler->init(); r != 0) {
391
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
392
0
                         << " ret=" << r;
393
0
            continue;
394
0
        }
395
30
        std::string recycle_job_key;
396
30
        job_recycle_key({instance_id}, &recycle_job_key);
397
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
398
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
399
30
        if (ret != 0) { // Prepare failed
400
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
401
20
                         << " ret=" << ret;
402
20
            continue;
403
20
        } else {
404
10
            std::lock_guard lock(mtx_);
405
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
406
10
        }
407
10
        if (stopped()) return;
408
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
409
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
410
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
411
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
412
10
        ret = instance_recycler->do_recycle();
413
        // If instance recycler has been aborted, don't finish this job
414
415
10
        if (!instance_recycler->stopped()) {
416
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
417
10
                                        ret == 0, ctime_ms);
418
10
        }
419
10
        if (instance_recycler->stopped() || ret != 0) {
420
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
421
0
        }
422
10
        {
423
10
            std::lock_guard lock(mtx_);
424
10
            recycling_instance_map_.erase(instance_id);
425
10
        }
426
427
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
428
10
        auto elpased_ms = now - ctime_ms;
429
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
430
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
431
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
432
10
                                             now + config::recycle_interval_seconds * 1000);
433
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
434
10
        LOG(INFO) << "recycle instance done, "
435
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
436
10
                  << " now: " << now;
437
438
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
439
440
10
        LOG_WARNING("finish recycle instance")
441
10
                .tag("instance_id", instance_id)
442
10
                .tag("cost_ms", elpased_ms);
443
10
    }
444
9
}
445
446
4
void Recycler::lease_recycle_jobs() {
447
54
    while (!stopped()) {
448
50
        std::vector<std::string> instances;
449
50
        instances.reserve(recycling_instance_map_.size());
450
50
        {
451
50
            std::lock_guard lock(mtx_);
452
50
            for (auto& [id, _] : recycling_instance_map_) {
453
30
                instances.push_back(id);
454
30
            }
455
50
        }
456
50
        for (auto& i : instances) {
457
30
            std::string recycle_job_key;
458
30
            job_recycle_key({i}, &recycle_job_key);
459
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
460
30
            if (ret == 1) {
461
0
                std::lock_guard lock(mtx_);
462
0
                if (auto it = recycling_instance_map_.find(i);
463
0
                    it != recycling_instance_map_.end()) {
464
0
                    it->second->stop();
465
0
                }
466
0
            }
467
30
        }
468
50
        {
469
50
            std::unique_lock lock(mtx_);
470
50
            notifier_.wait_for(lock,
471
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
472
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
472
100
                               [&]() { return stopped(); });
473
50
        }
474
50
    }
475
4
}
476
477
4
void Recycler::check_recycle_tasks() {
478
7
    while (!stopped()) {
479
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
480
3
        {
481
3
            std::lock_guard lock(mtx_);
482
3
            recycling_instance_map = recycling_instance_map_;
483
3
        }
484
3
        for (auto& entry : recycling_instance_map) {
485
0
            entry.second->check_recycle_tasks();
486
0
        }
487
488
3
        std::unique_lock lock(mtx_);
489
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
490
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
490
6
                           [&]() { return stopped(); });
491
3
    }
492
4
}
493
494
4
int Recycler::start(brpc::Server* server) {
495
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
496
4
    S3Environment::getInstance();
497
498
4
    if (config::enable_checker) {
499
0
        checker_ = std::make_unique<Checker>(txn_kv_);
500
0
        int ret = checker_->start();
501
0
        std::string msg;
502
0
        if (ret != 0) {
503
0
            msg = "failed to start checker";
504
0
            LOG(ERROR) << msg;
505
0
            std::cerr << msg << std::endl;
506
0
            return ret;
507
0
        }
508
0
        msg = "checker started";
509
0
        LOG(INFO) << msg;
510
0
        std::cout << msg << std::endl;
511
0
    }
512
513
4
    if (server) {
514
        // Add service
515
1
        auto recycler_service =
516
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
517
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
518
1
    }
519
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
521
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
522
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
522
8
        workers_.emplace_back([this] { recycle_callback(); });
523
8
    }
524
525
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
526
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
527
528
4
    if (config::enable_snapshot_data_migrator) {
529
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
530
0
        int ret = snapshot_data_migrator_->start();
531
0
        if (ret != 0) {
532
0
            LOG(ERROR) << "failed to start snapshot data migrator";
533
0
            return ret;
534
0
        }
535
0
        LOG(INFO) << "snapshot data migrator started";
536
0
    }
537
538
4
    if (config::enable_snapshot_chain_compactor) {
539
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
540
0
        int ret = snapshot_chain_compactor_->start();
541
0
        if (ret != 0) {
542
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
543
0
            return ret;
544
0
        }
545
0
        LOG(INFO) << "snapshot chain compactor started";
546
0
    }
547
548
4
    return 0;
549
4
}
550
551
4
void Recycler::stop() {
552
4
    stopped_ = true;
553
4
    notifier_.notify_all();
554
4
    pending_instance_cond_.notify_all();
555
4
    {
556
4
        std::lock_guard lock(mtx_);
557
4
        for (auto& [_, recycler] : recycling_instance_map_) {
558
0
            recycler->stop();
559
0
        }
560
4
    }
561
20
    for (auto& w : workers_) {
562
20
        if (w.joinable()) w.join();
563
20
    }
564
4
    if (checker_) {
565
0
        checker_->stop();
566
0
    }
567
4
    if (snapshot_data_migrator_) {
568
0
        snapshot_data_migrator_->stop();
569
0
    }
570
4
    if (snapshot_chain_compactor_) {
571
0
        snapshot_chain_compactor_->stop();
572
0
    }
573
4
}
574
575
class InstanceRecycler::InvertedIndexIdCache {
576
public:
577
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
578
164
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
579
580
    // Return 0 if success, 1 if schema kv not found, negative for error
581
    // For the same index_id, schema_version, res, since `get` is not completely atomic
582
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
583
    // resulting in repeated addition and inaccuracy.
584
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
585
    // repeated addition does not affect correctness.
586
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
587
28.4k
        {
588
28.4k
            std::lock_guard lock(mtx_);
589
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
590
4.67k
                return 0;
591
4.67k
            }
592
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
593
23.7k
                it != inverted_index_id_map_.end()) {
594
18.1k
                res = it->second;
595
18.1k
                return 0;
596
18.1k
            }
597
23.7k
        }
598
        // Get schema from kv
599
        // TODO(plat1ko): Single flight
600
5.54k
        std::unique_ptr<Transaction> txn;
601
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
602
5.54k
        if (err != TxnErrorCode::TXN_OK) {
603
0
            LOG(WARNING) << "failed to create txn, err=" << err;
604
0
            return -1;
605
0
        }
606
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
607
5.54k
        ValueBuf val_buf;
608
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
609
5.54k
        if (err != TxnErrorCode::TXN_OK) {
610
500
            LOG(WARNING) << "failed to get schema, err=" << err;
611
500
            return static_cast<int>(err);
612
500
        }
613
5.04k
        doris::TabletSchemaCloudPB schema;
614
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
615
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
616
0
            return -1;
617
0
        }
618
5.04k
        if (schema.index_size() > 0) {
619
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
620
4.01k
            if (schema.has_inverted_index_storage_format()) {
621
4.00k
                index_format = schema.inverted_index_storage_format();
622
4.00k
            }
623
4.01k
            res.first = index_format;
624
4.01k
            res.second.reserve(schema.index_size());
625
10.0k
            for (auto& i : schema.index()) {
626
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
627
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
628
10.0k
                }
629
10.0k
            }
630
4.01k
        }
631
5.04k
        insert(index_id, schema_version, res);
632
5.04k
        return 0;
633
5.04k
    }
634
635
    // Empty `ids` means this schema has no inverted index
636
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
637
5.04k
        if (index_info.second.empty()) {
638
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
639
1.02k
            std::lock_guard lock(mtx_);
640
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
641
4.01k
        } else {
642
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
643
4.01k
            std::lock_guard lock(mtx_);
644
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
645
4.01k
        }
646
5.04k
    }
647
648
private:
649
    std::string instance_id_;
650
    std::shared_ptr<TxnKv> txn_kv_;
651
652
    std::mutex mtx_;
653
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
654
    struct HashOfKey {
655
57.1k
        size_t operator()(const Key& key) const {
656
57.1k
            size_t seed = 0;
657
57.1k
            seed = std::hash<int64_t> {}(key.first);
658
57.1k
            seed = std::hash<int32_t> {}(key.second);
659
57.1k
            return seed;
660
57.1k
        }
661
    };
662
    // <index_id, schema_version> -> inverted_index_ids
663
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
664
    // Store <index_id, schema_version> of schema which doesn't have inverted index
665
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
666
};
667
668
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
669
                                   RecyclerThreadPoolGroup thread_pool_group,
670
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
671
164
        : txn_kv_(std::move(txn_kv)),
672
164
          instance_id_(instance.instance_id()),
673
164
          instance_info_(instance),
674
164
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
675
164
          _thread_pool_group(std::move(thread_pool_group)),
676
164
          txn_lazy_committer_(std::move(txn_lazy_committer)),
677
164
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
678
164
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
679
164
    delete_bitmap_lock_white_list_->init();
680
164
    resource_mgr_->init();
681
682
164
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
683
684
    // Since the recycler's resource manager could not be notified when instance info changes,
685
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
686
164
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
687
164
};
688
689
164
InstanceRecycler::~InstanceRecycler() = default;
690
691
142
int InstanceRecycler::init_obj_store_accessors() {
692
142
    for (const auto& obj_info : instance_info_.obj_info()) {
693
101
#ifdef UNIT_TEST
694
101
        auto accessor = std::make_shared<MockAccessor>();
695
#else
696
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
697
        if (!s3_conf) {
698
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
699
            return -1;
700
        }
701
702
        std::shared_ptr<S3Accessor> accessor;
703
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
704
        if (ret != 0) {
705
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
706
                         << " resource_id=" << obj_info.id();
707
            return ret;
708
        }
709
#endif
710
101
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
711
101
    }
712
713
142
    return 0;
714
142
}
715
716
142
int InstanceRecycler::init_storage_vault_accessors() {
717
142
    if (instance_info_.resource_ids().empty()) {
718
135
        return 0;
719
135
    }
720
721
7
    FullRangeGetOptions opts(txn_kv_);
722
7
    opts.prefetch = true;
723
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
724
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
725
726
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
727
18
        auto [k, v] = *kv;
728
18
        StorageVaultPB vault;
729
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
730
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
731
0
            return -1;
732
0
        }
733
18
        std::string recycler_storage_vault_white_list = accumulate(
734
18
                config::recycler_storage_vault_white_list.begin(),
735
18
                config::recycler_storage_vault_white_list.end(), std::string(),
736
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
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
737
18
        LOG_INFO("config::recycler_storage_vault_white_list")
738
18
                .tag("", recycler_storage_vault_white_list);
739
18
        if (!config::recycler_storage_vault_white_list.empty()) {
740
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
741
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
742
8
                it == config::recycler_storage_vault_white_list.end()) {
743
2
                LOG_WARNING(
744
2
                        "failed to init accessor for vault because this vault is not in "
745
2
                        "config::recycler_storage_vault_white_list. ")
746
2
                        .tag(" vault name:", vault.name())
747
2
                        .tag(" config::recycler_storage_vault_white_list:",
748
2
                             recycler_storage_vault_white_list);
749
2
                continue;
750
2
            }
751
8
        }
752
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
753
16
                                 &accessor_map_, &vault);
754
16
        if (vault.has_hdfs_info()) {
755
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
756
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
757
9
            int ret = accessor->init();
758
9
            if (ret != 0) {
759
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
760
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
761
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
762
4
                continue;
763
4
            }
764
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
765
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
766
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
767
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
768
#else
769
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
770
                       << "but HDFS storage vaults were detected";
771
#endif
772
7
        } else if (vault.has_obj_info()) {
773
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
774
7
            if (!s3_conf) {
775
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
776
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
777
1
                continue;
778
1
            }
779
780
6
            std::shared_ptr<S3Accessor> accessor;
781
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
782
6
            if (ret != 0) {
783
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
784
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
785
0
                             << " ret=" << ret
786
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
787
0
                continue;
788
0
            }
789
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
790
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
791
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
792
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
793
6
        }
794
16
    }
795
796
7
    if (!it->is_valid()) {
797
0
        LOG_WARNING("failed to get storage vault kv");
798
0
        return -1;
799
0
    }
800
801
7
    if (accessor_map_.empty()) {
802
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
803
1
        return -2;
804
1
    }
805
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
806
6
             instance_id_);
807
808
6
    return 0;
809
7
}
810
811
143
int InstanceRecycler::init() {
812
143
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
813
143
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
814
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
815
1
        return 0;
816
1
    }
817
818
142
    int ret = init_obj_store_accessors();
819
142
    if (ret != 0) {
820
0
        return ret;
821
0
    }
822
823
142
    return init_storage_vault_accessors();
824
142
}
825
826
template <typename... Func>
827
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
120
    return [funcs...]() {
829
120
        return [](std::initializer_list<int> ret_vals) {
830
120
            int i = 0;
831
140
            for (int ret : ret_vals) {
832
140
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
140
            }
836
120
            return i;
837
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
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
20
            for (int ret : ret_vals) {
832
20
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
20
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
20
            for (int ret : ret_vals) {
832
20
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
20
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
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
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
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
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
840
841
11
int InstanceRecycler::do_recycle() {
842
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
843
11
    tablet_metrics_context_.reset();
844
11
    segment_metrics_context_.reset();
845
11
    DORIS_CLOUD_DEFER {
846
11
        tablet_metrics_context_.finish_report();
847
11
        segment_metrics_context_.finish_report();
848
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
845
11
    DORIS_CLOUD_DEFER {
846
11
        tablet_metrics_context_.finish_report();
847
11
        segment_metrics_context_.finish_report();
848
11
    };
849
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
850
1
        int res = recycle_cluster_snapshots();
851
1
        if (res != 0) {
852
0
            return -1;
853
0
        }
854
1
        return recycle_deleted_instance();
855
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
856
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
857
10
                                        fmt::format("instance id {}", instance_id_),
858
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
858
120
                                        [](int r) { return r != 0; });
859
10
        sync_executor
860
10
                .add(task_wrapper(
861
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
861
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
862
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
862
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
863
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
864
                                   // becase they may both recycle the same set of tablets
865
                        // recycle dropped table or idexes(mv, rollup)
866
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
866
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
867
                        // recycle dropped partitions
868
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
868
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
869
10
                .add(task_wrapper(
870
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
870
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
871
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
871
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
872
10
                .add(task_wrapper(
873
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
873
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
874
10
                .add(task_wrapper(
875
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
875
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
876
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
876
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
877
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
877
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
878
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
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
879
10
                .add(task_wrapper(
880
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
880
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
881
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
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
882
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
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
883
10
        bool finished = true;
884
10
        std::vector<int> rets = sync_executor.when_all(&finished);
885
120
        for (int ret : rets) {
886
120
            if (ret != 0) {
887
0
                return ret;
888
0
            }
889
120
        }
890
10
        return finished ? 0 : -1;
891
10
    } else {
892
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
893
0
                     << " instance_id=" << instance_id_;
894
0
        return -1;
895
0
    }
896
11
}
897
898
/**
899
* 1. delete all remote data
900
* 2. delete all kv
901
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
902
*/
903
13
int InstanceRecycler::recycle_deleted_instance() {
904
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
905
906
13
    int ret = 0;
907
13
    auto start_time = steady_clock::now();
908
13
    const auto recycle_state = instance_info_.recycle_state();
909
910
13
    if (config::retain_deleted_instance_tombstone &&
911
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
912
4
        return 0;
913
4
    }
914
915
9
    DORIS_CLOUD_DEFER {
916
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
917
9
        if (ret != 0) {
918
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
919
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
920
0
                         << "s, instance_id=" << instance_id_;
921
9
        } else if (recycle_state ==
922
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
923
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
924
0
                      << "s, instance_id=" << instance_id_;
925
9
        } else {
926
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
927
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
928
9
                      << "s, instance_id=" << instance_id_;
929
9
        }
930
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
915
9
    DORIS_CLOUD_DEFER {
916
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
917
9
        if (ret != 0) {
918
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
919
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
920
0
                         << "s, instance_id=" << instance_id_;
921
9
        } else if (recycle_state ==
922
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
923
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
924
0
                      << "s, instance_id=" << instance_id_;
925
9
        } else {
926
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
927
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
928
9
                      << "s, instance_id=" << instance_id_;
929
9
        }
930
9
    };
931
932
9
    switch (recycle_state) {
933
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
934
6
        ret = recycle_deleted_instance_data();
935
6
        break;
936
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
937
3
        ret = recycle_deleted_instance_metadata();
938
3
        break;
939
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
940
0
        ret = remove_instance_key();
941
0
        break;
942
0
    default:
943
0
        LOG_WARNING("invalid instance recycle state")
944
0
                .tag("instance_id", instance_id_)
945
0
                .tag("recycle_state", instance_info_.recycle_state());
946
0
        ret = -1;
947
0
        break;
948
9
    }
949
950
9
    return ret;
951
9
}
952
953
6
int InstanceRecycler::recycle_deleted_instance_data() {
954
6
    int ret = 0;
955
956
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
957
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
958
6
        int res = recycle_tmp_rowsets();
959
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
960
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
961
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
962
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
963
            // and cannot be recycled.
964
0
            res = recycle_tmp_rowsets();
965
0
        }
966
6
        return res;
967
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
957
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
958
6
        int res = recycle_tmp_rowsets();
959
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
960
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
961
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
962
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
963
            // and cannot be recycled.
964
0
            res = recycle_tmp_rowsets();
965
0
        }
966
6
        return res;
967
6
    };
968
969
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
970
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
971
0
        return -1;
972
0
    }
973
974
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
975
6
    if (recycle_versioned_rowsets() != 0) {
976
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
977
0
        return -1;
978
0
    }
979
980
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
981
6
    if (recycle_operation_logs() != 0) {
982
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
983
0
        return -1;
984
0
    }
985
986
    // Step 4: Check if there are still cluster snapshots
987
6
    bool has_snapshots = false;
988
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
989
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
990
0
        return -1;
991
6
    } else if (has_snapshots) {
992
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
993
1
        return 0;
994
1
    }
995
996
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
997
5
                            instance_info().snapshot_switch_status() !=
998
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
999
5
    if (snapshot_enabled) {
1000
1
        bool has_unrecycled_rowsets = false;
1001
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1002
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1003
0
            return -1;
1004
1
        } else if (has_unrecycled_rowsets) {
1005
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1006
0
                    .tag("instance_id", instance_id_);
1007
0
            return ret;
1008
0
        }
1009
4
    } else { // delete all remote data if snapshot is disabled
1010
4
        for (auto& [_, accessor] : accessor_map_) {
1011
4
            if (stopped()) {
1012
0
                return ret;
1013
0
            }
1014
1015
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1016
4
            int del_ret = accessor->delete_all();
1017
4
            if (del_ret == 0) {
1018
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1019
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1020
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1021
                // so the recycling has been successful.
1022
0
                ret = -1;
1023
0
            }
1024
4
        }
1025
1026
4
        if (ret != 0) {
1027
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1028
0
            return ret;
1029
0
        }
1030
4
    }
1031
1032
5
    if (update_instance_recycle_state(
1033
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1034
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1035
0
        return -1;
1036
0
    }
1037
1038
5
    return 0;
1039
5
}
1040
1041
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1042
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1043
7
    if (instance_info_.has_successor_instance_id() &&
1044
7
        !instance_info_.successor_instance_id().empty()) {
1045
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1046
4
        std::unique_ptr<Transaction> txn;
1047
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1048
4
        if (err != TxnErrorCode::TXN_OK) {
1049
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1050
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1051
0
                         << " err=" << err;
1052
0
            return -1;
1053
0
        }
1054
1055
4
        InstanceInfoPB successor_instance;
1056
4
        std::string value;
1057
4
        err = txn->get(key, &value);
1058
4
        if (err == TxnErrorCode::TXN_OK) {
1059
3
            InstanceInfoPB successor_instance;
1060
3
            if (!successor_instance.ParseFromString(value)) {
1061
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1062
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1063
0
                return -1;
1064
0
            }
1065
3
            if (!successor_instance.has_recycle_state() ||
1066
3
                successor_instance.recycle_state() !=
1067
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1068
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1069
2
                          << " instance_id=" << instance_id_
1070
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1071
2
                          << " successor_status=" << successor_instance.status()
1072
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1073
2
                return 0;
1074
2
            }
1075
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1076
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1077
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1078
0
                         << " err=" << err;
1079
0
            return -1;
1080
0
        }
1081
4
    }
1082
1083
    // delete all kv
1084
5
    std::unique_ptr<Transaction> txn;
1085
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1086
5
    if (err != TxnErrorCode::TXN_OK) {
1087
0
        LOG(WARNING) << "failed to create txn";
1088
0
        return -1;
1089
0
    }
1090
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1091
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1092
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1093
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1094
5
    txn->remove(start_txn_key, end_txn_key);
1095
5
    std::string start_version_key = version_key_prefix(instance_id_);
1096
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1097
5
    txn->remove(start_version_key, end_version_key);
1098
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1099
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_meta_key, end_meta_key);
1101
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1102
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_recycle_key, end_recycle_key);
1104
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1105
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1106
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1107
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1108
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1109
5
    txn->remove(start_copy_key, end_copy_key);
1110
    // should not remove job key range, because we need to reserve job recycle kv
1111
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1112
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1113
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1114
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1115
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1116
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1117
5
    std::string start_vault_key = storage_vault_key(key_info0);
1118
5
    std::string end_vault_key = storage_vault_key(key_info1);
1119
5
    txn->remove(start_vault_key, end_vault_key);
1120
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1121
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1122
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1123
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1124
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1125
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1126
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1127
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1129
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1130
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1132
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1133
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1135
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1136
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1138
1139
    // Updating the recycle state also commits this transaction, making the metadata deletions
1140
    // and state transition atomic.
1141
5
    if (update_instance_recycle_state(
1142
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1143
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1144
0
        return -1;
1145
0
    }
1146
1147
5
    return 0;
1148
5
}
1149
1150
0
int InstanceRecycler::remove_instance_key() {
1151
0
    std::unique_ptr<Transaction> txn;
1152
0
    std::string key = instance_key(instance_info_.instance_id());
1153
0
    std::string value;
1154
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1155
0
    if (err != TxnErrorCode::TXN_OK) {
1156
0
        LOG(WARNING) << "failed to create txn";
1157
0
        return -1;
1158
0
    }
1159
1160
0
    err = txn->get(key, &value);
1161
0
    if (err != TxnErrorCode::TXN_OK) {
1162
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1163
0
                     << ", err=" << err;
1164
0
        return -1;
1165
0
    }
1166
1167
0
    InstanceInfoPB instance;
1168
0
    if (!instance.ParseFromString(value)) {
1169
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1170
0
        return -1;
1171
0
    }
1172
1173
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1174
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1175
0
                     << instance_id_ << ", status=" << instance.status();
1176
0
        return -1;
1177
0
    }
1178
1179
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1180
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1181
0
                     << instance_id_
1182
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1183
0
                     << ", expected_state="
1184
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1185
0
        return -1;
1186
0
    }
1187
1188
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1189
0
    txn->remove(key);
1190
0
    err = txn->commit();
1191
0
    if (err != TxnErrorCode::TXN_OK) {
1192
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1193
0
                     << " err=" << err;
1194
0
        return -1;
1195
0
    }
1196
0
    return 0;
1197
0
}
1198
1199
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1200
7
                                                    InstanceRecycleState target_state) {
1201
7
    std::unique_ptr<Transaction> txn;
1202
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1203
7
    if (err != TxnErrorCode::TXN_OK) {
1204
0
        LOG(WARNING) << "failed to create txn";
1205
0
        return -1;
1206
0
    }
1207
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1208
7
}
1209
1210
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1211
                                                    InstanceRecycleState target_state,
1212
12
                                                    Transaction* txn) {
1213
12
    const bool valid_transition =
1214
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1215
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1216
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1217
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1218
1219
12
    if (!valid_transition) {
1220
1
        LOG_WARNING("invalid instance recycled state transition")
1221
1
                .tag("instance_id", instance_id_)
1222
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1223
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1224
1
        return -1;
1225
1
    }
1226
1227
11
    std::string key = instance_key({instance_id_});
1228
11
    std::string value;
1229
11
    TxnErrorCode err = txn->get(key, &value);
1230
11
    if (err != TxnErrorCode::TXN_OK) {
1231
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1232
0
                .tag("instance_id", instance_id_)
1233
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1234
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1235
0
                .tag("err", err);
1236
0
        return -1;
1237
0
    }
1238
1239
11
    InstanceInfoPB instance;
1240
11
    if (!instance.ParseFromString(value)) {
1241
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1242
0
                .tag("instance_id", instance_id_)
1243
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1244
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1245
0
        return -1;
1246
0
    }
1247
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1248
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1249
0
                .tag("instance_id", instance_id_)
1250
0
                .tag("status", instance.status())
1251
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1252
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1253
0
        return -1;
1254
0
    }
1255
11
    if (instance.recycle_state() != current_state) {
1256
1
        LOG_WARNING("instance recycled state changed before update")
1257
1
                .tag("instance_id", instance_id_)
1258
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1259
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1260
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1261
1
        return -1;
1262
1
    }
1263
1264
10
    instance.set_recycle_state(target_state);
1265
10
    instance.set_recycle_state_update_time_ms(
1266
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1267
10
    if (!instance.SerializeToString(&value)) {
1268
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1269
0
                .tag("instance_id", instance_id_)
1270
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1271
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1272
0
        return -1;
1273
0
    }
1274
1275
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1276
10
    txn->put(key, value);
1277
10
    err = txn->commit();
1278
10
    if (err != TxnErrorCode::TXN_OK) {
1279
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1280
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1281
0
        return -1;
1282
0
    }
1283
1284
10
    instance_info_.Swap(&instance);
1285
10
    LOG_INFO("updated instance recycled state")
1286
10
            .tag("instance_id", instance_id_)
1287
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1288
10
    return 0;
1289
10
}
1290
1291
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1292
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1293
9
    if (exists == nullptr) {
1294
0
        return -1;
1295
0
    }
1296
9
    *exists = false;
1297
1298
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1299
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1300
9
    std::string scan_begin = begin;
1301
1302
9
    while (true) {
1303
9
        std::unique_ptr<RangeGetIterator> it_range;
1304
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1305
9
        if (get_ret < 0) {
1306
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1307
0
                    .tag("instance_id", instance_id_)
1308
0
                    .tag("tablet_id", tablet_id)
1309
0
                    .tag("ret", get_ret);
1310
0
            return -1;
1311
0
        }
1312
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1313
6
            return 0;
1314
6
        }
1315
1316
3
        std::string last_key;
1317
3
        while (it_range->has_next()) {
1318
3
            auto [k, v] = it_range->next();
1319
3
            last_key.assign(k.data(), k.size());
1320
3
            doris::RowsetMetaCloudPB rowset_meta;
1321
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1322
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1323
0
                        .tag("instance_id", instance_id_)
1324
0
                        .tag("tablet_id", tablet_id)
1325
0
                        .tag("key", hex(k));
1326
0
                continue;
1327
0
            }
1328
3
            if (stats) {
1329
3
                ++stats->rowset_scan_count;
1330
3
            }
1331
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1332
3
                *exists = true;
1333
3
                return 0;
1334
3
            }
1335
3
        }
1336
1337
0
        if (!it_range->more()) {
1338
0
            return 0;
1339
0
        }
1340
1341
        // Continue scanning from the next key to keep each transaction short.
1342
0
        scan_begin = std::move(last_key);
1343
0
        scan_begin.push_back('\x00');
1344
0
    }
1345
9
}
1346
1347
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1348
                                                          const std::string& rowset_id,
1349
                                                          int64_t txn_id, bool* recycle_exists,
1350
11
                                                          bool* tmp_exists) {
1351
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1352
0
        return -1;
1353
0
    }
1354
11
    *recycle_exists = false;
1355
11
    *tmp_exists = false;
1356
1357
11
    if (txn_id <= 0) {
1358
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1359
0
                .tag("instance_id", instance_id_)
1360
0
                .tag("tablet_id", tablet_id)
1361
0
                .tag("rowset_id", rowset_id)
1362
0
                .tag("txn_id", txn_id);
1363
0
        return -1;
1364
0
    }
1365
1366
11
    std::unique_ptr<Transaction> txn;
1367
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1368
11
    if (err != TxnErrorCode::TXN_OK) {
1369
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1370
0
                .tag("instance_id", instance_id_)
1371
0
                .tag("tablet_id", tablet_id)
1372
0
                .tag("rowset_id", rowset_id)
1373
0
                .tag("txn_id", txn_id)
1374
0
                .tag("err", err);
1375
0
        return -1;
1376
0
    }
1377
1378
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1379
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1380
11
    if (ret == TxnErrorCode::TXN_OK) {
1381
1
        *recycle_exists = true;
1382
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1383
0
        LOG_WARNING("failed to check recycle rowset existence")
1384
0
                .tag("instance_id", instance_id_)
1385
0
                .tag("tablet_id", tablet_id)
1386
0
                .tag("rowset_id", rowset_id)
1387
0
                .tag("key", hex(recycle_key))
1388
0
                .tag("err", ret);
1389
0
        return -1;
1390
0
    }
1391
1392
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1393
11
    ret = key_exists(txn.get(), tmp_key, true);
1394
11
    if (ret == TxnErrorCode::TXN_OK) {
1395
1
        *tmp_exists = true;
1396
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1397
0
        LOG_WARNING("failed to check tmp rowset existence")
1398
0
                .tag("instance_id", instance_id_)
1399
0
                .tag("tablet_id", tablet_id)
1400
0
                .tag("txn_id", txn_id)
1401
0
                .tag("key", hex(tmp_key))
1402
0
                .tag("err", ret);
1403
0
        return -1;
1404
0
    }
1405
1406
11
    return 0;
1407
11
}
1408
1409
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1410
9
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1411
9
    if (!hint.empty()) {
1412
9
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1413
9
            return {hint, it->second};
1414
9
        }
1415
9
    }
1416
1417
0
    return {"", nullptr};
1418
9
}
1419
1420
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1421
                                               const std::string& packed_file_path,
1422
3
                                               PackedFileRecycleStats* stats) {
1423
3
    bool local_changed = false;
1424
3
    int64_t left_num = 0;
1425
3
    int64_t left_bytes = 0;
1426
3
    bool all_small_files_confirmed = true;
1427
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1428
1429
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1430
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1431
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1432
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1433
14
        LOG_INFO("packed slice correction status")
1434
14
                .tag("instance_id", instance_id_)
1435
14
                .tag("packed_file_path", packed_file_path)
1436
14
                .tag("small_file_path", file.path())
1437
14
                .tag("tablet_id", tablet_id)
1438
14
                .tag("rowset_id", rowset_id)
1439
14
                .tag("txn_id", txn_id)
1440
14
                .tag("size", file.size())
1441
14
                .tag("deleted", file.deleted())
1442
14
                .tag("corrected", file.corrected())
1443
14
                .tag("confirmed_this_round", confirmed_this_round);
1444
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
1429
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1430
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1431
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1432
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1433
        LOG_INFO("packed slice correction status")
1434
14
                .tag("instance_id", instance_id_)
1435
14
                .tag("packed_file_path", packed_file_path)
1436
14
                .tag("small_file_path", file.path())
1437
14
                .tag("tablet_id", tablet_id)
1438
14
                .tag("rowset_id", rowset_id)
1439
14
                .tag("txn_id", txn_id)
1440
14
                .tag("size", file.size())
1441
14
                .tag("deleted", file.deleted())
1442
14
                .tag("corrected", file.corrected())
1443
14
                .tag("confirmed_this_round", confirmed_this_round);
1444
14
    };
1445
1446
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1447
14
        auto* small_file = packed_info->mutable_slices(i);
1448
14
        if (small_file->deleted()) {
1449
3
            log_small_file_status(*small_file, small_file->corrected());
1450
3
            continue;
1451
3
        }
1452
1453
11
        if (small_file->corrected()) {
1454
0
            left_num++;
1455
0
            left_bytes += small_file->size();
1456
0
            log_small_file_status(*small_file, true);
1457
0
            continue;
1458
0
        }
1459
1460
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1461
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1462
0
                    .tag("instance_id", instance_id_)
1463
0
                    .tag("small_file_path", small_file->path())
1464
0
                    .tag("index", i);
1465
0
            return -1;
1466
0
        }
1467
1468
11
        int64_t tablet_id = small_file->tablet_id();
1469
11
        const std::string& rowset_id = small_file->rowset_id();
1470
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1471
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1472
0
                    .tag("instance_id", instance_id_)
1473
0
                    .tag("small_file_path", small_file->path())
1474
0
                    .tag("index", i)
1475
0
                    .tag("tablet_id", tablet_id)
1476
0
                    .tag("rowset_id", rowset_id)
1477
0
                    .tag("has_txn_id", small_file->has_txn_id())
1478
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1479
0
            return -1;
1480
0
        }
1481
11
        int64_t txn_id = small_file->txn_id();
1482
11
        bool recycle_exists = false;
1483
11
        bool tmp_exists = false;
1484
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1485
11
                                                &tmp_exists) != 0) {
1486
0
            return -1;
1487
0
        }
1488
1489
11
        bool small_file_confirmed = false;
1490
11
        if (tmp_exists) {
1491
1
            left_num++;
1492
1
            left_bytes += small_file->size();
1493
1
            small_file_confirmed = true;
1494
10
        } else if (recycle_exists) {
1495
1
            left_num++;
1496
1
            left_bytes += small_file->size();
1497
            // keep small_file_confirmed=false so the packed file remains uncorrected
1498
9
        } else {
1499
9
            bool rowset_exists = false;
1500
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1501
0
                return -1;
1502
0
            }
1503
1504
9
            if (!rowset_exists) {
1505
6
                if (!small_file->deleted()) {
1506
6
                    small_file->set_deleted(true);
1507
6
                    local_changed = true;
1508
6
                }
1509
6
                if (!small_file->corrected()) {
1510
6
                    small_file->set_corrected(true);
1511
6
                    local_changed = true;
1512
6
                }
1513
6
                small_file_confirmed = true;
1514
6
            } else {
1515
3
                left_num++;
1516
3
                left_bytes += small_file->size();
1517
3
                small_file_confirmed = true;
1518
3
            }
1519
9
        }
1520
1521
11
        if (!small_file_confirmed) {
1522
1
            all_small_files_confirmed = false;
1523
1
        }
1524
1525
11
        if (small_file->corrected() != small_file_confirmed) {
1526
4
            small_file->set_corrected(small_file_confirmed);
1527
4
            local_changed = true;
1528
4
        }
1529
1530
11
        log_small_file_status(*small_file, small_file_confirmed);
1531
11
    }
1532
1533
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1534
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1535
3
        local_changed = true;
1536
3
    }
1537
3
    if (packed_info->ref_cnt() != left_num) {
1538
3
        auto old_ref_cnt = packed_info->ref_cnt();
1539
3
        packed_info->set_ref_cnt(left_num);
1540
3
        LOG_INFO("corrected packed file ref count")
1541
3
                .tag("instance_id", instance_id_)
1542
3
                .tag("resource_id", packed_info->resource_id())
1543
3
                .tag("packed_file_path", packed_file_path)
1544
3
                .tag("old_ref_cnt", old_ref_cnt)
1545
3
                .tag("new_ref_cnt", left_num);
1546
3
        local_changed = true;
1547
3
    }
1548
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1549
2
        packed_info->set_corrected(all_small_files_confirmed);
1550
2
        local_changed = true;
1551
2
    }
1552
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1553
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1554
1
        local_changed = true;
1555
1
    }
1556
1557
3
    if (changed != nullptr) {
1558
3
        *changed = local_changed;
1559
3
    }
1560
3
    return 0;
1561
3
}
1562
1563
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1564
                                                 const std::string& packed_file_path,
1565
4
                                                 PackedFileRecycleStats* stats) {
1566
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1567
4
    bool correction_ok = false;
1568
4
    cloud::PackedFileInfoPB packed_info;
1569
1570
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1571
4
        if (stopped()) {
1572
0
            LOG_WARNING("recycler stopped before processing packed file")
1573
0
                    .tag("instance_id", instance_id_)
1574
0
                    .tag("packed_file_path", packed_file_path)
1575
0
                    .tag("attempt", attempt);
1576
0
            return -1;
1577
0
        }
1578
1579
4
        std::unique_ptr<Transaction> txn;
1580
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1581
4
        if (err != TxnErrorCode::TXN_OK) {
1582
0
            LOG_WARNING("failed to create txn when processing packed file")
1583
0
                    .tag("instance_id", instance_id_)
1584
0
                    .tag("packed_file_path", packed_file_path)
1585
0
                    .tag("attempt", attempt)
1586
0
                    .tag("err", err);
1587
0
            return -1;
1588
0
        }
1589
1590
4
        std::string packed_val;
1591
4
        err = txn->get(packed_key, &packed_val);
1592
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1593
0
            return 0;
1594
0
        }
1595
4
        if (err != TxnErrorCode::TXN_OK) {
1596
0
            LOG_WARNING("failed to get packed file kv")
1597
0
                    .tag("instance_id", instance_id_)
1598
0
                    .tag("packed_file_path", packed_file_path)
1599
0
                    .tag("attempt", attempt)
1600
0
                    .tag("err", err);
1601
0
            return -1;
1602
0
        }
1603
1604
4
        if (!packed_info.ParseFromString(packed_val)) {
1605
0
            LOG_WARNING("failed to parse packed file info")
1606
0
                    .tag("instance_id", instance_id_)
1607
0
                    .tag("packed_file_path", packed_file_path)
1608
0
                    .tag("attempt", attempt);
1609
0
            return -1;
1610
0
        }
1611
1612
4
        int64_t now_sec = ::time(nullptr);
1613
4
        bool corrected = packed_info.corrected();
1614
4
        bool due = config::force_immediate_recycle ||
1615
4
                   now_sec - packed_info.created_at_sec() >=
1616
4
                           config::packed_file_correction_delay_seconds;
1617
1618
4
        if (!corrected && due) {
1619
3
            bool changed = false;
1620
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1621
0
                LOG_WARNING("correct_packed_file_info failed")
1622
0
                        .tag("instance_id", instance_id_)
1623
0
                        .tag("packed_file_path", packed_file_path)
1624
0
                        .tag("attempt", attempt);
1625
0
                return -1;
1626
0
            }
1627
3
            if (changed) {
1628
3
                std::string updated;
1629
3
                if (!packed_info.SerializeToString(&updated)) {
1630
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1631
0
                            .tag("instance_id", instance_id_)
1632
0
                            .tag("packed_file_path", packed_file_path)
1633
0
                            .tag("attempt", attempt);
1634
0
                    return -1;
1635
0
                }
1636
3
                txn->put(packed_key, updated);
1637
3
                err = txn->commit();
1638
3
                if (err == TxnErrorCode::TXN_OK) {
1639
3
                    if (stats) {
1640
3
                        ++stats->num_corrected;
1641
3
                    }
1642
3
                } else {
1643
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1644
0
                        LOG_WARNING(
1645
0
                                "failed to commit correction for packed file due to conflict, "
1646
0
                                "retrying")
1647
0
                                .tag("instance_id", instance_id_)
1648
0
                                .tag("packed_file_path", packed_file_path)
1649
0
                                .tag("attempt", attempt);
1650
0
                        sleep_for_packed_file_retry();
1651
0
                        packed_info.Clear();
1652
0
                        continue;
1653
0
                    }
1654
0
                    LOG_WARNING("failed to commit correction for packed file")
1655
0
                            .tag("instance_id", instance_id_)
1656
0
                            .tag("packed_file_path", packed_file_path)
1657
0
                            .tag("attempt", attempt)
1658
0
                            .tag("err", err);
1659
0
                    return -1;
1660
0
                }
1661
3
            }
1662
3
        }
1663
1664
4
        correction_ok = true;
1665
4
        break;
1666
4
    }
1667
1668
4
    if (!correction_ok) {
1669
0
        return -1;
1670
0
    }
1671
1672
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1673
4
          packed_info.ref_cnt() == 0)) {
1674
3
        return 0;
1675
3
    }
1676
1677
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1678
0
        LOG_WARNING("packed file missing resource id when recycling")
1679
0
                .tag("instance_id", instance_id_)
1680
0
                .tag("packed_file_path", packed_file_path);
1681
0
        return -1;
1682
0
    }
1683
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1684
1
    if (!accessor) {
1685
0
        LOG_WARNING("no accessor available to delete packed file")
1686
0
                .tag("instance_id", instance_id_)
1687
0
                .tag("packed_file_path", packed_file_path)
1688
0
                .tag("resource_id", packed_info.resource_id());
1689
0
        return -1;
1690
0
    }
1691
1
    int del_ret = accessor->delete_file(packed_file_path);
1692
1
    if (del_ret != 0 && del_ret != 1) {
1693
0
        LOG_WARNING("failed to delete packed file")
1694
0
                .tag("instance_id", instance_id_)
1695
0
                .tag("packed_file_path", packed_file_path)
1696
0
                .tag("resource_id", resource_id)
1697
0
                .tag("ret", del_ret);
1698
0
        return -1;
1699
0
    }
1700
1
    if (del_ret == 1) {
1701
0
        LOG_INFO("packed file already removed")
1702
0
                .tag("instance_id", instance_id_)
1703
0
                .tag("packed_file_path", packed_file_path)
1704
0
                .tag("resource_id", resource_id);
1705
1
    } else {
1706
1
        LOG_INFO("deleted packed file")
1707
1
                .tag("instance_id", instance_id_)
1708
1
                .tag("packed_file_path", packed_file_path)
1709
1
                .tag("resource_id", resource_id);
1710
1
    }
1711
1712
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1713
1
        std::unique_ptr<Transaction> del_txn;
1714
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1715
1
        if (err != TxnErrorCode::TXN_OK) {
1716
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1717
0
                    .tag("instance_id", instance_id_)
1718
0
                    .tag("packed_file_path", packed_file_path)
1719
0
                    .tag("del_attempt", del_attempt)
1720
0
                    .tag("err", err);
1721
0
            return -1;
1722
0
        }
1723
1724
1
        std::string latest_val;
1725
1
        err = del_txn->get(packed_key, &latest_val);
1726
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1727
0
            return 0;
1728
0
        }
1729
1
        if (err != TxnErrorCode::TXN_OK) {
1730
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1731
0
                    .tag("instance_id", instance_id_)
1732
0
                    .tag("packed_file_path", packed_file_path)
1733
0
                    .tag("del_attempt", del_attempt)
1734
0
                    .tag("err", err);
1735
0
            return -1;
1736
0
        }
1737
1738
1
        cloud::PackedFileInfoPB latest_info;
1739
1
        if (!latest_info.ParseFromString(latest_val)) {
1740
0
            LOG_WARNING("failed to parse packed file info before removal")
1741
0
                    .tag("instance_id", instance_id_)
1742
0
                    .tag("packed_file_path", packed_file_path)
1743
0
                    .tag("del_attempt", del_attempt);
1744
0
            return -1;
1745
0
        }
1746
1747
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1748
1
              latest_info.ref_cnt() == 0)) {
1749
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1750
0
                    .tag("instance_id", instance_id_)
1751
0
                    .tag("packed_file_path", packed_file_path)
1752
0
                    .tag("del_attempt", del_attempt);
1753
0
            return 0;
1754
0
        }
1755
1756
1
        del_txn->remove(packed_key);
1757
1
        err = del_txn->commit();
1758
1
        if (err == TxnErrorCode::TXN_OK) {
1759
1
            if (stats) {
1760
1
                ++stats->num_deleted;
1761
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1762
1
                                        static_cast<int64_t>(latest_val.size());
1763
1
                if (del_ret == 0 || del_ret == 1) {
1764
1
                    ++stats->num_object_deleted;
1765
1
                    int64_t object_size = latest_info.total_slice_bytes();
1766
1
                    if (object_size <= 0) {
1767
0
                        object_size = packed_info.total_slice_bytes();
1768
0
                    }
1769
1
                    stats->bytes_object_deleted += object_size;
1770
1
                }
1771
1
            }
1772
1
            LOG_INFO("removed packed file metadata")
1773
1
                    .tag("instance_id", instance_id_)
1774
1
                    .tag("packed_file_path", packed_file_path);
1775
1
            return 0;
1776
1
        }
1777
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1778
0
            if (del_attempt >= max_retry_times) {
1779
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1780
0
                        .tag("instance_id", instance_id_)
1781
0
                        .tag("packed_file_path", packed_file_path)
1782
0
                        .tag("del_attempt", del_attempt);
1783
0
                return -1;
1784
0
            }
1785
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1786
0
                    .tag("instance_id", instance_id_)
1787
0
                    .tag("packed_file_path", packed_file_path)
1788
0
                    .tag("del_attempt", del_attempt);
1789
0
            sleep_for_packed_file_retry();
1790
0
            continue;
1791
0
        }
1792
0
        LOG_WARNING("failed to remove packed file kv")
1793
0
                .tag("instance_id", instance_id_)
1794
0
                .tag("packed_file_path", packed_file_path)
1795
0
                .tag("del_attempt", del_attempt)
1796
0
                .tag("err", err);
1797
0
        return -1;
1798
0
    }
1799
1800
0
    return -1;
1801
1
}
1802
1803
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1804
4
                                            PackedFileRecycleStats* stats, int* ret) {
1805
4
    if (stats) {
1806
4
        ++stats->num_scanned;
1807
4
    }
1808
4
    std::string packed_file_path;
1809
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1810
0
        LOG_WARNING("failed to decode packed file key")
1811
0
                .tag("instance_id", instance_id_)
1812
0
                .tag("key", hex(key));
1813
0
        if (stats) {
1814
0
            ++stats->num_failed;
1815
0
        }
1816
0
        if (ret) {
1817
0
            *ret = -1;
1818
0
        }
1819
0
        return 0;
1820
0
    }
1821
1822
4
    std::string packed_key(key);
1823
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1824
4
    if (process_ret != 0) {
1825
0
        if (stats) {
1826
0
            ++stats->num_failed;
1827
0
        }
1828
0
        if (ret) {
1829
0
            *ret = -1;
1830
0
        }
1831
0
    }
1832
4
    return 0;
1833
4
}
1834
1835
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1836
6.30k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1837
6.30k
    if (config::force_immediate_recycle) {
1838
295
        return 0L;
1839
295
    }
1840
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1841
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1842
6.00k
    int64_t retention_seconds = config::retention_seconds;
1843
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1844
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1845
4.70k
    }
1846
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1847
6.00k
    if (*earlest_ts > final_expiration) {
1848
6
        *earlest_ts = final_expiration;
1849
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1850
6
    }
1851
6.00k
    return final_expiration;
1852
6.30k
}
1853
1854
int64_t calculate_partition_expired_time(
1855
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1856
7
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1857
7
    if (config::force_immediate_recycle) {
1858
1
        return 0L;
1859
1
    }
1860
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1861
6
                                                            : partition_meta_pb.creation_time();
1862
6
    int64_t retention_seconds = config::retention_seconds;
1863
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1864
6
        retention_seconds =
1865
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1866
6
    }
1867
6
    int64_t final_expiration = expiration + retention_seconds;
1868
6
    if (*earlest_ts > final_expiration) {
1869
2
        *earlest_ts = final_expiration;
1870
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1871
2
    }
1872
6
    return final_expiration;
1873
7
}
1874
1875
int64_t calculate_index_expired_time(const std::string& instance_id_,
1876
                                     const RecycleIndexPB& index_meta_pb,
1877
8
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1878
8
    if (config::force_immediate_recycle) {
1879
2
        return 0L;
1880
2
    }
1881
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1882
6
                                                        : index_meta_pb.creation_time();
1883
6
    int64_t retention_seconds = config::retention_seconds;
1884
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1885
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1886
6
    }
1887
6
    int64_t final_expiration = expiration + retention_seconds;
1888
6
    if (*earlest_ts > final_expiration) {
1889
2
        *earlest_ts = final_expiration;
1890
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1891
2
    }
1892
6
    return final_expiration;
1893
8
}
1894
1895
int64_t calculate_tmp_rowset_expired_time(
1896
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1897
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1898
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1899
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1900
    //  duration or timeout always < `retention_time` in practice.
1901
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1902
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1903
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1904
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1905
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1906
53.2k
    if (*earlest_ts > final_expiration) {
1907
20
        *earlest_ts = final_expiration;
1908
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1909
20
    }
1910
53.2k
    return final_expiration;
1911
53.2k
}
1912
1913
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1914
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1915
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1916
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1917
11
        *earlest_ts = final_expiration / 1000;
1918
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1919
11
    }
1920
50.0k
    return final_expiration;
1921
50.0k
}
1922
1923
int64_t calculate_restore_job_expired_time(
1924
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1925
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1926
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1927
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1928
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1929
        // final state, recycle immediately
1930
41
        return 0L;
1931
41
    }
1932
    // not final state, wait much longer than the FE's timeout(1 day)
1933
0
    int64_t last_modified_s =
1934
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1935
0
    int64_t expiration = restore_job.expired_at_s() > 0
1936
0
                                 ? last_modified_s + restore_job.expired_at_s()
1937
0
                                 : last_modified_s;
1938
0
    int64_t final_expiration = expiration + config::retention_seconds;
1939
0
    if (*earlest_ts > final_expiration) {
1940
0
        *earlest_ts = final_expiration;
1941
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1942
0
    }
1943
0
    return final_expiration;
1944
41
}
1945
1946
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1947
537
    AbortTxnRequest req;
1948
537
    TxnInfoPB txn_info;
1949
537
    MetaServiceCode code = MetaServiceCode::OK;
1950
537
    std::string msg;
1951
537
    std::stringstream ss;
1952
537
    std::unique_ptr<Transaction> txn;
1953
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1954
537
    if (err != TxnErrorCode::TXN_OK) {
1955
0
        LOG_WARNING("failed to create txn").tag("err", err);
1956
0
        return -1;
1957
0
    }
1958
1959
    // get txn index
1960
537
    TxnIndexPB txn_idx_pb;
1961
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1962
537
    std::string index_val;
1963
537
    err = txn->get(index_key, &index_val);
1964
537
    if (err != TxnErrorCode::TXN_OK) {
1965
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1966
            // maybe recycled
1967
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1968
2
                    .tag("key", hex(index_key))
1969
2
                    .tag("txn_id", txn_id);
1970
2
            return 0;
1971
2
        }
1972
0
        LOG_WARNING("failed to get txn index")
1973
0
                .tag("err", err)
1974
0
                .tag("key", hex(index_key))
1975
0
                .tag("txn_id", txn_id);
1976
0
        return -1;
1977
2
    }
1978
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
1979
1
        LOG_WARNING("failed to parse txn index")
1980
1
                .tag("err", err)
1981
1
                .tag("key", hex(index_key))
1982
1
                .tag("txn_id", txn_id);
1983
1
        return -1;
1984
1
    }
1985
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1986
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
1987
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1988
3
                .tag("key", hex(index_key))
1989
3
                .tag("txn_id", txn_id)
1990
3
                .tag("db_id",
1991
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1992
3
        return -1;
1993
3
    }
1994
1995
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1996
531
    const int64_t owner_txn_id =
1997
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1998
531
    if (owner_txn_id <= 0) {
1999
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2000
1
                .tag("key", hex(index_key))
2001
1
                .tag("txn_id", txn_id)
2002
1
                .tag("owner_txn_id", owner_txn_id);
2003
1
        return -1;
2004
1
    }
2005
2006
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2007
530
    std::string info_val;
2008
530
    err = txn->get(info_key, &info_val);
2009
530
    if (err != TxnErrorCode::TXN_OK) {
2010
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2011
            // maybe recycled
2012
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2013
1
                        owner_txn_id, instance_id_)
2014
1
                    .tag("key", hex(info_key))
2015
1
                    .tag("txn_id", txn_id)
2016
1
                    .tag("owner_txn_id", owner_txn_id);
2017
1
            return 0;
2018
1
        }
2019
0
        LOG_WARNING("failed to get txn info")
2020
0
                .tag("err", err)
2021
0
                .tag("key", hex(info_key))
2022
0
                .tag("txn_id", txn_id)
2023
0
                .tag("owner_txn_id", owner_txn_id);
2024
0
        return -1;
2025
1
    }
2026
529
    if (!txn_info.ParseFromString(info_val)) {
2027
1
        LOG_WARNING("failed to parse txn info")
2028
1
                .tag("err", err)
2029
1
                .tag("key", hex(info_key))
2030
1
                .tag("txn_id", txn_id)
2031
1
                .tag("owner_txn_id", owner_txn_id);
2032
1
        return -1;
2033
1
    }
2034
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2035
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2036
1
                .tag("key", hex(info_key))
2037
1
                .tag("txn_id", txn_id)
2038
1
                .tag("owner_txn_id", owner_txn_id)
2039
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2040
1
        return -1;
2041
1
    }
2042
2043
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2044
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2045
514
                .tag("key", hex(info_key))
2046
514
                .tag("txn_id", txn_id)
2047
514
                .tag("owner_txn_id", owner_txn_id);
2048
514
        return 0;
2049
514
    }
2050
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2051
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2052
4
                    owner_txn_id, txn_info.status())
2053
4
                .tag("key", hex(info_key))
2054
4
                .tag("txn_id", txn_id)
2055
4
                .tag("owner_txn_id", owner_txn_id);
2056
4
        return -1;
2057
4
    }
2058
2059
9
    req.set_txn_id(owner_txn_id);
2060
9
    req.set_db_id(db_id);
2061
2062
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2063
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2064
9
                 << " txn_info=" << txn_info.ShortDebugString();
2065
2066
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2067
9
    if (code != MetaServiceCode::OK) {
2068
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2069
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2070
0
                     << " code=" << code << " msg=" << msg;
2071
0
        return -1;
2072
0
    }
2073
2074
9
    err = txn->commit();
2075
9
    if (err != TxnErrorCode::TXN_OK) {
2076
0
        code = cast_as<ErrCategory::COMMIT>(err);
2077
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2078
0
        msg = ss.str();
2079
0
        return -1;
2080
0
    }
2081
2082
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2083
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2084
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2085
9
                 << " msg=" << msg;
2086
2087
9
    return 0;
2088
9
}
2089
2090
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2091
11
                                                   const std::string& job_id) {
2092
11
    FinishTabletJobRequest req;
2093
11
    FinishTabletJobResponse res;
2094
11
    req.set_action(FinishTabletJobRequest::ABORT);
2095
11
    MetaServiceCode code = MetaServiceCode::OK;
2096
11
    std::string msg;
2097
11
    std::stringstream ss;
2098
2099
11
    TabletIndexPB tablet_idx;
2100
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2101
11
    if (ret == 1) {
2102
        // tablet maybe recycled, directly return 0
2103
1
        return 0;
2104
10
    } else if (ret != 0) {
2105
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2106
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2107
0
        return ret;
2108
0
    }
2109
2110
10
    std::unique_ptr<Transaction> txn;
2111
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2112
10
    if (err != TxnErrorCode::TXN_OK) {
2113
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2114
0
        return -1;
2115
0
    }
2116
2117
10
    std::string job_key =
2118
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2119
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2120
10
    std::string job_val;
2121
10
    err = txn->get(job_key, &job_val);
2122
10
    if (err != TxnErrorCode::TXN_OK) {
2123
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2124
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2125
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2126
            // A previous recycler round may have aborted the job. The caller must recheck the
2127
            // recycle key before deleting object data.
2128
1
            return 0;
2129
1
        }
2130
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2131
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2132
0
                     << " key=" << hex(job_key);
2133
0
        return -1;
2134
1
    }
2135
2136
9
    TabletJobInfoPB job_pb;
2137
9
    if (!job_pb.ParseFromString(job_val)) {
2138
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2139
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2140
0
        return -1;
2141
0
    }
2142
2143
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2144
9
    for (const auto& compaction : job_pb.compaction()) {
2145
9
        if (compaction.id() == job_id) {
2146
5
            matched_compaction = &compaction;
2147
5
            break;
2148
5
        }
2149
9
    }
2150
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2151
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2152
9
        job_pb.schema_change().id() == job_id) {
2153
3
        matched_schema_change = &job_pb.schema_change();
2154
3
    }
2155
2156
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2157
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2158
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2159
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2160
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2161
        // both the base and mirrored schema-change records.
2162
8
        if (matched_compaction != nullptr) {
2163
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2164
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2165
5
        } else {
2166
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2167
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2168
3
        }
2169
8
        req.set_action(FinishTabletJobRequest::ABORT);
2170
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2171
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2172
8
                           ss);
2173
8
        if (code != MetaServiceCode::OK) {
2174
            // These two codes mean that the job cannot be aborted anymore.
2175
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2176
            // There is no running job that still owns the PREPARE rowset, so the caller may
2177
            // recheck the recycle key.
2178
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2179
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2180
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2181
            // job again and continue recycling only when the target job id no longer exists.
2182
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2183
0
                std::unique_ptr<Transaction> check_txn;
2184
0
                err = txn_kv_->create_txn(&check_txn);
2185
0
                if (err != TxnErrorCode::TXN_OK) {
2186
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2187
0
                                 << instance_id_ << " err=" << err;
2188
0
                    return -1;
2189
0
                }
2190
2191
0
                const auto& idx = req.job().idx();
2192
0
                std::string current_job_key =
2193
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2194
0
                                        idx.partition_id(), idx.tablet_id()});
2195
0
                std::string current_job_val;
2196
0
                err = check_txn->get(current_job_key, &current_job_val);
2197
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2198
0
                    no_job_to_abort = true;
2199
0
                } else if (err != TxnErrorCode::TXN_OK) {
2200
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2201
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2202
0
                                 << " key=" << hex(current_job_key);
2203
0
                    return -1;
2204
0
                } else {
2205
0
                    TabletJobInfoPB current_job;
2206
0
                    if (!current_job.ParseFromString(current_job_val)) {
2207
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2208
0
                                     << " tablet_id=" << idx.tablet_id()
2209
0
                                     << " key=" << hex(current_job_key);
2210
0
                        return -1;
2211
0
                    }
2212
0
                    if (matched_compaction != nullptr) {
2213
0
                        no_job_to_abort = true;
2214
0
                        for (const auto& compaction : current_job.compaction()) {
2215
0
                            if (compaction.id() == job_id) {
2216
0
                                no_job_to_abort = false;
2217
0
                                break;
2218
0
                            }
2219
0
                        }
2220
0
                    } else {
2221
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2222
0
                                          current_job.schema_change().id() != job_id;
2223
0
                    }
2224
0
                }
2225
0
            }
2226
0
            if (no_job_to_abort) {
2227
0
                return 0;
2228
0
            }
2229
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2230
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2231
0
                         << " msg=" << msg;
2232
0
            return -1;
2233
0
        }
2234
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2235
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2236
8
                     << " code=" << code << " msg=" << msg;
2237
8
    } else {
2238
        // clang-format off
2239
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2240
1
                  << ", instance_id=" << instance_id_ 
2241
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2242
1
                  << ", job_id=" << job_id
2243
1
                  << ", rowset_id=" << rowset_id;
2244
        // clang-format on
2245
1
    }
2246
2247
9
    return 0;
2248
9
}
2249
2250
template <typename T>
2251
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
13
        return rowset_meta_pb.mutable_rowset_meta();
2254
13
    } else {
2255
9
        return &rowset_meta_pb;
2256
9
    }
2257
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2251
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
13
        return rowset_meta_pb.mutable_rowset_meta();
2254
    } else {
2255
        return &rowset_meta_pb;
2256
    }
2257
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2251
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
        return rowset_meta_pb.mutable_rowset_meta();
2254
9
    } else {
2255
9
        return &rowset_meta_pb;
2256
9
    }
2257
9
}
2258
2259
template <typename T>
2260
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
833
        return rowset_meta_pb.rowset_meta();
2263
833
    } else {
2264
799
        return rowset_meta_pb;
2265
799
    }
2266
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2260
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
833
        return rowset_meta_pb.rowset_meta();
2263
    } else {
2264
        return rowset_meta_pb;
2265
    }
2266
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2260
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
        return rowset_meta_pb.rowset_meta();
2263
799
    } else {
2264
799
        return rowset_meta_pb;
2265
799
    }
2266
799
}
2267
2268
template <typename T>
2269
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2270
1.07k
        const T& rowset_meta_pb) {
2271
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
0
            return std::nullopt;
2274
0
        }
2275
545
    }
2276
2277
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
1.07k
    RelatedTxnOrJobAbortTask task;
2279
1.07k
    task.tablet_id = rs_meta.tablet_id();
2280
1.07k
    task.start_version = rs_meta.start_version();
2281
1.07k
    task.end_version = rs_meta.end_version();
2282
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2283
1.07k
    if (rs_meta.has_load_id()) {
2284
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
1.05k
        task.txn_id = rs_meta.txn_id();
2286
1.05k
        return task;
2287
1.05k
    }
2288
19
    if (rs_meta.has_job_id()) {
2289
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
14
        task.job_id = rs_meta.job_id();
2291
14
        return task;
2292
14
    }
2293
5
    return std::nullopt;
2294
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2270
545
        const T& rowset_meta_pb) {
2271
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
0
            return std::nullopt;
2274
0
        }
2275
545
    }
2276
2277
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
545
    RelatedTxnOrJobAbortTask task;
2279
545
    task.tablet_id = rs_meta.tablet_id();
2280
545
    task.start_version = rs_meta.start_version();
2281
545
    task.end_version = rs_meta.end_version();
2282
545
    task.rowset_id = rs_meta.rowset_id_v2();
2283
545
    if (rs_meta.has_load_id()) {
2284
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
534
        task.txn_id = rs_meta.txn_id();
2286
534
        return task;
2287
534
    }
2288
11
    if (rs_meta.has_job_id()) {
2289
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
10
        task.job_id = rs_meta.job_id();
2291
10
        return task;
2292
10
    }
2293
1
    return std::nullopt;
2294
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2270
526
        const T& rowset_meta_pb) {
2271
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
            return std::nullopt;
2274
        }
2275
    }
2276
2277
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
526
    RelatedTxnOrJobAbortTask task;
2279
526
    task.tablet_id = rs_meta.tablet_id();
2280
526
    task.start_version = rs_meta.start_version();
2281
526
    task.end_version = rs_meta.end_version();
2282
526
    task.rowset_id = rs_meta.rowset_id_v2();
2283
526
    if (rs_meta.has_load_id()) {
2284
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
518
        task.txn_id = rs_meta.txn_id();
2286
518
        return task;
2287
518
    }
2288
8
    if (rs_meta.has_job_id()) {
2289
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
4
        task.job_id = rs_meta.job_id();
2291
4
        return task;
2292
4
    }
2293
4
    return std::nullopt;
2294
8
}
2295
2296
template <typename T>
2297
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2298
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return false;
2302
0
        }
2303
268
    }
2304
2305
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
523
    }
2313
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2298
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return false;
2302
0
        }
2303
268
    }
2304
2305
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
264
    }
2313
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2298
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
            return false;
2302
        }
2303
    }
2304
2305
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
259
    }
2313
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
261
}
2315
2316
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2317
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2318
71
}
2319
2320
template <typename T>
2321
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2322
18
                                   const std::vector<std::string>& keys) {
2323
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
18
        std::unique_ptr<Transaction> txn;
2327
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
18
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
18
        std::vector<std::optional<std::string>> values;
2333
18
        err = txn->batch_get(&values, batch_keys);
2334
18
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
18
        DCHECK_EQ(values.size(), batch_keys.size());
2340
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
22
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
22
            const auto& key = batch_keys[i];
2346
22
            auto val = values[i].value();
2347
22
            T rowset_meta_pb;
2348
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
13
            }
2361
22
            val.clear();
2362
22
            rowset_meta_pb.SerializeToString(&val);
2363
22
            txn->put(key, val);
2364
22
        }
2365
18
        err = txn->commit();
2366
18
        if (err != TxnErrorCode::TXN_OK) {
2367
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
1
            return -1;
2369
1
        }
2370
18
    }
2371
2372
17
    return 0;
2373
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2322
11
                                   const std::vector<std::string>& keys) {
2323
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
11
        std::unique_ptr<Transaction> txn;
2327
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
11
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
11
        std::vector<std::optional<std::string>> values;
2333
11
        err = txn->batch_get(&values, batch_keys);
2334
11
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
11
        DCHECK_EQ(values.size(), batch_keys.size());
2340
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
13
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
13
            const auto& key = batch_keys[i];
2346
13
            auto val = values[i].value();
2347
13
            T rowset_meta_pb;
2348
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
13
            }
2361
13
            val.clear();
2362
13
            rowset_meta_pb.SerializeToString(&val);
2363
13
            txn->put(key, val);
2364
13
        }
2365
11
        err = txn->commit();
2366
11
        if (err != TxnErrorCode::TXN_OK) {
2367
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
1
            return -1;
2369
1
        }
2370
11
    }
2371
2372
10
    return 0;
2373
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2322
7
                                   const std::vector<std::string>& keys) {
2323
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
7
        std::unique_ptr<Transaction> txn;
2327
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
7
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
7
        std::vector<std::optional<std::string>> values;
2333
7
        err = txn->batch_get(&values, batch_keys);
2334
7
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
7
        DCHECK_EQ(values.size(), batch_keys.size());
2340
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
9
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
9
            const auto& key = batch_keys[i];
2346
9
            auto val = values[i].value();
2347
9
            T rowset_meta_pb;
2348
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
            }
2361
9
            val.clear();
2362
9
            rowset_meta_pb.SerializeToString(&val);
2363
9
            txn->put(key, val);
2364
9
        }
2365
7
        err = txn->commit();
2366
7
        if (err != TxnErrorCode::TXN_OK) {
2367
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
0
            return -1;
2369
0
        }
2370
7
    }
2371
2372
7
    return 0;
2373
7
}
2374
2375
template <typename T>
2376
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2377
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
1
        }
2383
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2378
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
1
        }
2383
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2378
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
0
        }
2383
7
    });
2384
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2377
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
11
        }
2383
11
    });
2384
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2377
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
7
        }
2383
7
    });
2384
7
}
2385
2386
template <typename T>
2387
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2388
                                 const std::vector<std::string>& keys,
2389
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
22
        std::unique_ptr<Transaction> txn;
2394
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
22
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
22
        std::vector<std::optional<std::string>> values;
2400
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
22
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
22
        DCHECK_EQ(values.size(), batch_keys.size());
2407
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
533
            const std::string& key = batch_keys[idx];
2409
533
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
533
            T rowset_meta_pb;
2414
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
533
                abort_task.has_value()) {
2421
533
                abort_task->key = key;
2422
533
                abort_tasks->emplace_back(std::move(*abort_task));
2423
533
            }
2424
533
        }
2425
22
    }
2426
20
    return 0;
2427
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2389
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
16
        std::unique_ptr<Transaction> txn;
2394
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
16
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
16
        std::vector<std::optional<std::string>> values;
2400
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
16
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
16
        DCHECK_EQ(values.size(), batch_keys.size());
2407
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
272
            const std::string& key = batch_keys[idx];
2409
272
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
272
            T rowset_meta_pb;
2414
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
272
                abort_task.has_value()) {
2421
272
                abort_task->key = key;
2422
272
                abort_tasks->emplace_back(std::move(*abort_task));
2423
272
            }
2424
272
        }
2425
16
    }
2426
15
    return 0;
2427
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2389
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
6
        std::unique_ptr<Transaction> txn;
2394
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
6
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
6
        std::vector<std::optional<std::string>> values;
2400
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
6
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
6
        DCHECK_EQ(values.size(), batch_keys.size());
2407
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
261
            const std::string& key = batch_keys[idx];
2409
261
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
261
            T rowset_meta_pb;
2414
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
261
                abort_task.has_value()) {
2421
261
                abort_task->key = key;
2422
261
                abort_tasks->emplace_back(std::move(*abort_task));
2423
261
            }
2424
261
        }
2425
6
    }
2426
5
    return 0;
2427
5
}
2428
2429
template <typename T>
2430
int batch_recheck_rowsets_after_abort(
2431
        TxnKv* txn_kv, const std::string& instance_id,
2432
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2433
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
18
    int ret = 0;
2435
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
20
        std::vector<std::string> batch_keys;
2438
20
        batch_keys.reserve(limit - offset);
2439
550
        for (size_t idx = offset; idx < limit; ++idx) {
2440
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
530
        }
2442
2443
20
        std::unique_ptr<Transaction> txn;
2444
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
20
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
20
        std::vector<std::optional<std::string>> values;
2453
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
20
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
20
        DCHECK_EQ(values.size(), batch_keys.size());
2461
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
20
                                 &batch_size);
2464
2465
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
530
            if (!values[idx].has_value()) {
2468
1
                continue;
2469
1
            }
2470
2471
529
            T rowset_meta_pb;
2472
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
1
                             << instance_id << " key=" << hex(key);
2487
1
                continue;
2488
1
            }
2489
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
528
        }
2491
20
    }
2492
18
    return ret;
2493
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2433
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
13
    int ret = 0;
2435
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
14
        std::vector<std::string> batch_keys;
2438
14
        batch_keys.reserve(limit - offset);
2439
283
        for (size_t idx = offset; idx < limit; ++idx) {
2440
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
269
        }
2442
2443
14
        std::unique_ptr<Transaction> txn;
2444
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
14
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
14
        std::vector<std::optional<std::string>> values;
2453
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
14
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
14
        DCHECK_EQ(values.size(), batch_keys.size());
2461
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
14
                                 &batch_size);
2464
2465
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
269
            if (!values[idx].has_value()) {
2468
1
                continue;
2469
1
            }
2470
2471
268
            T rowset_meta_pb;
2472
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
1
                             << instance_id << " key=" << hex(key);
2487
1
                continue;
2488
1
            }
2489
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
267
        }
2491
14
    }
2492
13
    return ret;
2493
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2433
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
5
    int ret = 0;
2435
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
6
        std::vector<std::string> batch_keys;
2438
6
        batch_keys.reserve(limit - offset);
2439
267
        for (size_t idx = offset; idx < limit; ++idx) {
2440
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
261
        }
2442
2443
6
        std::unique_ptr<Transaction> txn;
2444
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
6
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
6
        std::vector<std::optional<std::string>> values;
2453
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
6
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
6
        DCHECK_EQ(values.size(), batch_keys.size());
2461
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
6
                                 &batch_size);
2464
2465
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
261
            if (!values[idx].has_value()) {
2468
0
                continue;
2469
0
            }
2470
2471
261
            T rowset_meta_pb;
2472
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
0
                             << instance_id << " key=" << hex(key);
2487
0
                continue;
2488
0
            }
2489
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
261
        }
2491
6
    }
2492
5
    return ret;
2493
5
}
2494
2495
template <typename T>
2496
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2497
        const std::vector<std::string>& keys,
2498
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
20
    int ret = 0;
2506
533
    for (const auto& abort_task : abort_tasks) {
2507
533
        int abort_ret = 0;
2508
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
526
        } else {
2511
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
7
                                                     abort_task.job_id);
2513
7
        }
2514
533
        if (abort_ret != 0) {
2515
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
3
            ret = abort_ret;
2519
3
            continue;
2520
3
        }
2521
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
530
    }
2523
20
    return ret;
2524
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2498
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
15
    int ret = 0;
2506
272
    for (const auto& abort_task : abort_tasks) {
2507
272
        int abort_ret = 0;
2508
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
267
        } else {
2511
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
5
                                                     abort_task.job_id);
2513
5
        }
2514
272
        if (abort_ret != 0) {
2515
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
3
            ret = abort_ret;
2519
3
            continue;
2520
3
        }
2521
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
269
    }
2523
15
    return ret;
2524
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2498
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
5
    int ret = 0;
2506
261
    for (const auto& abort_task : abort_tasks) {
2507
261
        int abort_ret = 0;
2508
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
259
        } else {
2511
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
2
                                                     abort_task.job_id);
2513
2
        }
2514
261
        if (abort_ret != 0) {
2515
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
0
            ret = abort_ret;
2519
0
            continue;
2520
0
        }
2521
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
261
    }
2523
5
    return ret;
2524
5
}
2525
2526
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2527
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2528
15
        std::atomic_long* num_recycled) {
2529
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2530
15
                                  num_recycled]() mutable {
2531
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
15
                                                                            keys_to_recheck);
2534
15
        if (abort_ret != 0) {
2535
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
2
                            "instance_id="
2537
2
                         << instance_id_;
2538
2
        }
2539
15
        if (keys_to_recheck.empty()) {
2540
2
            return;
2541
2
        }
2542
2543
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
13
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
267
            const auto& current_meta = current_rowset.rowset_meta();
2552
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
267
                                   current_meta.rowset_id_v2()) != 0) {
2554
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
1
                continue;
2556
1
            }
2557
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
266
                                                   current_meta.tablet_id(),
2559
266
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
266
            std::vector<std::string> keys {key};
2563
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
266
        }
2569
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2530
2
                                  num_recycled]() mutable {
2531
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
2
                                                                            keys_to_recheck);
2534
2
        if (abort_ret != 0) {
2535
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
0
                            "instance_id="
2537
0
                         << instance_id_;
2538
0
        }
2539
2
        if (keys_to_recheck.empty()) {
2540
0
            return;
2541
0
        }
2542
2543
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
2
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
2
            const auto& current_meta = current_rowset.rowset_meta();
2552
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
2
                                   current_meta.rowset_id_v2()) != 0) {
2554
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
0
                continue;
2556
0
            }
2557
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
2
                                                   current_meta.tablet_id(),
2559
2
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
2
            std::vector<std::string> keys {key};
2563
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
2
        }
2569
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2530
13
                                  num_recycled]() mutable {
2531
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
13
                                                                            keys_to_recheck);
2534
13
        if (abort_ret != 0) {
2535
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
2
                            "instance_id="
2537
2
                         << instance_id_;
2538
2
        }
2539
13
        if (keys_to_recheck.empty()) {
2540
2
            return;
2541
2
        }
2542
2543
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
11
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
265
            const auto& current_meta = current_rowset.rowset_meta();
2552
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
265
                                   current_meta.rowset_id_v2()) != 0) {
2554
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
1
                continue;
2556
1
            }
2557
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
264
                                                   current_meta.tablet_id(),
2559
264
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
264
            std::vector<std::string> keys {key};
2563
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
264
        }
2569
11
    });
2570
15
    if (ret != 0) {
2571
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2572
0
    }
2573
15
}
2574
2575
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2576
                                                      std::vector<std::string> rowset_keys_to_abort,
2577
                                                      std::atomic_long* num_recycled,
2578
5
                                                      RecyclerMetricsContext* metrics_context) {
2579
5
    if (rowset_keys_to_abort.empty()) {
2580
0
        return;
2581
0
    }
2582
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2583
5
                        metrics_context]() mutable {
2584
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
5
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
5
        std::vector<std::string> keys_to_delete;
2595
5
        std::vector<std::string> ref_count_keys_to_delete;
2596
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
5
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
261
            keys_to_delete.push_back(key);
2605
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
261
        }
2609
2610
5
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
5
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
261
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
261
        }
2627
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2583
3
                        metrics_context]() mutable {
2584
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
3
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
3
        std::vector<std::string> keys_to_delete;
2595
3
        std::vector<std::string> ref_count_keys_to_delete;
2596
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
3
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
3
            keys_to_delete.push_back(key);
2605
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
3
        }
2609
2610
3
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
3
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
3
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
3
        }
2627
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2583
2
                        metrics_context]() mutable {
2584
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
2
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
2
        std::vector<std::string> keys_to_delete;
2595
2
        std::vector<std::string> ref_count_keys_to_delete;
2596
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
2
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
258
            keys_to_delete.push_back(key);
2605
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
258
        }
2609
2610
2
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
2
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
258
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
258
        }
2627
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
2
    });
2638
5
}
2639
2640
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2641
1
    const std::string task_name = "recycle_ref_rowsets";
2642
1
    *has_unrecycled_rowsets = false;
2643
2644
1
    std::string data_rowset_ref_count_key_start =
2645
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2646
1
    std::string data_rowset_ref_count_key_end =
2647
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2648
2649
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2650
2651
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2652
1
    register_recycle_task(task_name, start_time);
2653
2654
1
    DORIS_CLOUD_DEFER {
2655
1
        unregister_recycle_task(task_name);
2656
1
        int64_t cost =
2657
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2658
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2659
1
                .tag("instance_id", instance_id_);
2660
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2654
1
    DORIS_CLOUD_DEFER {
2655
1
        unregister_recycle_task(task_name);
2656
1
        int64_t cost =
2657
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2658
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2659
1
                .tag("instance_id", instance_id_);
2660
1
    };
2661
2662
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2663
1
    std::set<int64_t> tablets_with_refs;
2664
1
    int64_t num_scanned = 0;
2665
2666
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2667
0
        ++num_scanned;
2668
0
        int64_t tablet_id;
2669
0
        std::string rowset_id;
2670
0
        std::string_view key(k);
2671
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2672
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2673
0
            return 0; // Continue scanning
2674
0
        }
2675
2676
0
        tablets_with_refs.insert(tablet_id);
2677
0
        return 0;
2678
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2679
2680
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2681
1
                         std::move(scan_func)) != 0) {
2682
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2683
0
        return -1;
2684
0
    }
2685
2686
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2687
1
             tablets_with_refs.size(), num_scanned)
2688
1
            .tag("instance_id", instance_id_);
2689
2690
    // Phase 2: Recycle each tablet
2691
1
    int64_t num_recycled_tablets = 0;
2692
1
    for (int64_t tablet_id : tablets_with_refs) {
2693
0
        if (stopped()) {
2694
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2695
0
                    .tag("instance_id", instance_id_)
2696
0
                    .tag("tablets_processed", num_recycled_tablets)
2697
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2698
0
            break;
2699
0
        }
2700
2701
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2702
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2703
0
            LOG_WARNING("failed to recycle tablet")
2704
0
                    .tag("instance_id", instance_id_)
2705
0
                    .tag("tablet_id", tablet_id);
2706
0
            return -1;
2707
0
        }
2708
0
        ++num_recycled_tablets;
2709
0
    }
2710
2711
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2712
1
            .tag("instance_id", instance_id_)
2713
1
            .tag("total_tablets", tablets_with_refs.size());
2714
2715
    // Phase 3: Scan again to check if any ref count keys still exist
2716
1
    std::unique_ptr<Transaction> txn;
2717
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2718
1
    if (err != TxnErrorCode::TXN_OK) {
2719
0
        LOG_WARNING("failed to create txn for final check")
2720
0
                .tag("instance_id", instance_id_)
2721
0
                .tag("err", err);
2722
0
        return -1;
2723
0
    }
2724
2725
1
    std::unique_ptr<RangeGetIterator> iter;
2726
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2727
1
    if (err != TxnErrorCode::TXN_OK) {
2728
0
        LOG_WARNING("failed to create range iterator for final check")
2729
0
                .tag("instance_id", instance_id_)
2730
0
                .tag("err", err);
2731
0
        return -1;
2732
0
    }
2733
2734
1
    *has_unrecycled_rowsets = iter->has_next();
2735
1
    if (*has_unrecycled_rowsets) {
2736
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2737
0
                .tag("instance_id", instance_id_);
2738
0
    }
2739
2740
1
    return 0;
2741
1
}
2742
2743
15
int InstanceRecycler::recycle_indexes() {
2744
15
    const std::string task_name = "recycle_indexes";
2745
15
    int64_t num_scanned = 0;
2746
15
    int64_t num_expired = 0;
2747
15
    int64_t num_recycled = 0;
2748
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2749
2750
15
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2751
15
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2752
15
    std::string index_key0;
2753
15
    std::string index_key1;
2754
15
    recycle_index_key(index_key_info0, &index_key0);
2755
15
    recycle_index_key(index_key_info1, &index_key1);
2756
2757
15
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2758
2759
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2760
15
    register_recycle_task(task_name, start_time);
2761
2762
15
    DORIS_CLOUD_DEFER {
2763
15
        unregister_recycle_task(task_name);
2764
15
        int64_t cost =
2765
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2766
15
        metrics_context.finish_report();
2767
15
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2768
15
                .tag("instance_id", instance_id_)
2769
15
                .tag("num_scanned", num_scanned)
2770
15
                .tag("num_expired", num_expired)
2771
15
                .tag("num_recycled", num_recycled);
2772
15
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2762
15
    DORIS_CLOUD_DEFER {
2763
15
        unregister_recycle_task(task_name);
2764
15
        int64_t cost =
2765
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2766
15
        metrics_context.finish_report();
2767
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2768
15
                .tag("instance_id", instance_id_)
2769
15
                .tag("num_scanned", num_scanned)
2770
15
                .tag("num_expired", num_expired)
2771
15
                .tag("num_recycled", num_recycled);
2772
15
    };
2773
2774
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2775
2776
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2777
15
    std::vector<std::string_view> index_keys;
2778
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2779
8
        ++num_scanned;
2780
8
        RecycleIndexPB index_pb;
2781
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2782
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2783
0
            return -1;
2784
0
        }
2785
8
        int64_t current_time = ::time(nullptr);
2786
8
        if (current_time <
2787
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2788
0
            return 0;
2789
0
        }
2790
8
        ++num_expired;
2791
        // decode index_id
2792
8
        auto k1 = k;
2793
8
        k1.remove_prefix(1);
2794
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2795
8
        decode_key(&k1, &out);
2796
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2797
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2798
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2799
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2800
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2801
        // Change state to RECYCLING
2802
8
        std::unique_ptr<Transaction> txn;
2803
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2804
8
        if (err != TxnErrorCode::TXN_OK) {
2805
0
            LOG_WARNING("failed to create txn").tag("err", err);
2806
0
            return -1;
2807
0
        }
2808
8
        std::string val;
2809
8
        err = txn->get(k, &val);
2810
8
        if (err ==
2811
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2812
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2813
0
            return 0;
2814
0
        }
2815
8
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2817
0
            return -1;
2818
0
        }
2819
8
        index_pb.Clear();
2820
8
        if (!index_pb.ParseFromString(val)) {
2821
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2822
0
            return -1;
2823
0
        }
2824
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2825
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2826
8
            txn->put(k, index_pb.SerializeAsString());
2827
8
            err = txn->commit();
2828
8
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2830
0
                return -1;
2831
0
            }
2832
8
        }
2833
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2834
0
            LOG_WARNING("failed to recycle tablets under index")
2835
0
                    .tag("table_id", index_pb.table_id())
2836
0
                    .tag("instance_id", instance_id_)
2837
0
                    .tag("index_id", index_id);
2838
0
            return -1;
2839
0
        }
2840
2841
8
        if (index_pb.has_db_id()) {
2842
            // Recycle the versioned keys
2843
2
            std::unique_ptr<Transaction> txn;
2844
2
            err = txn_kv_->create_txn(&txn);
2845
2
            if (err != TxnErrorCode::TXN_OK) {
2846
0
                LOG_WARNING("failed to create txn").tag("err", err);
2847
0
                return -1;
2848
0
            }
2849
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2850
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2851
2
            std::string index_inverted_key = versioned::index_inverted_key(
2852
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2853
2
            versioned_remove_all(txn.get(), meta_key);
2854
2
            txn->remove(index_key);
2855
2
            txn->remove(index_inverted_key);
2856
2
            err = txn->commit();
2857
2
            if (err != TxnErrorCode::TXN_OK) {
2858
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2859
0
                return -1;
2860
0
            }
2861
2
        }
2862
2863
8
        metrics_context.total_recycled_num = ++num_recycled;
2864
8
        metrics_context.report();
2865
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2866
8
        index_keys.push_back(k);
2867
8
        return 0;
2868
8
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2778
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2779
8
        ++num_scanned;
2780
8
        RecycleIndexPB index_pb;
2781
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2782
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2783
0
            return -1;
2784
0
        }
2785
8
        int64_t current_time = ::time(nullptr);
2786
8
        if (current_time <
2787
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2788
0
            return 0;
2789
0
        }
2790
8
        ++num_expired;
2791
        // decode index_id
2792
8
        auto k1 = k;
2793
8
        k1.remove_prefix(1);
2794
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2795
8
        decode_key(&k1, &out);
2796
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2797
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2798
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2799
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2800
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2801
        // Change state to RECYCLING
2802
8
        std::unique_ptr<Transaction> txn;
2803
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2804
8
        if (err != TxnErrorCode::TXN_OK) {
2805
0
            LOG_WARNING("failed to create txn").tag("err", err);
2806
0
            return -1;
2807
0
        }
2808
8
        std::string val;
2809
8
        err = txn->get(k, &val);
2810
8
        if (err ==
2811
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2812
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2813
0
            return 0;
2814
0
        }
2815
8
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2817
0
            return -1;
2818
0
        }
2819
8
        index_pb.Clear();
2820
8
        if (!index_pb.ParseFromString(val)) {
2821
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2822
0
            return -1;
2823
0
        }
2824
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2825
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2826
8
            txn->put(k, index_pb.SerializeAsString());
2827
8
            err = txn->commit();
2828
8
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2830
0
                return -1;
2831
0
            }
2832
8
        }
2833
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2834
0
            LOG_WARNING("failed to recycle tablets under index")
2835
0
                    .tag("table_id", index_pb.table_id())
2836
0
                    .tag("instance_id", instance_id_)
2837
0
                    .tag("index_id", index_id);
2838
0
            return -1;
2839
0
        }
2840
2841
8
        if (index_pb.has_db_id()) {
2842
            // Recycle the versioned keys
2843
2
            std::unique_ptr<Transaction> txn;
2844
2
            err = txn_kv_->create_txn(&txn);
2845
2
            if (err != TxnErrorCode::TXN_OK) {
2846
0
                LOG_WARNING("failed to create txn").tag("err", err);
2847
0
                return -1;
2848
0
            }
2849
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2850
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2851
2
            std::string index_inverted_key = versioned::index_inverted_key(
2852
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2853
2
            versioned_remove_all(txn.get(), meta_key);
2854
2
            txn->remove(index_key);
2855
2
            txn->remove(index_inverted_key);
2856
2
            err = txn->commit();
2857
2
            if (err != TxnErrorCode::TXN_OK) {
2858
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2859
0
                return -1;
2860
0
            }
2861
2
        }
2862
2863
8
        metrics_context.total_recycled_num = ++num_recycled;
2864
8
        metrics_context.report();
2865
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2866
8
        index_keys.push_back(k);
2867
8
        return 0;
2868
8
    };
2869
2870
15
    auto loop_done = [&index_keys, this]() -> int {
2871
4
        if (index_keys.empty()) return 0;
2872
4
        DORIS_CLOUD_DEFER {
2873
4
            index_keys.clear();
2874
4
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2872
4
        DORIS_CLOUD_DEFER {
2873
4
            index_keys.clear();
2874
4
        };
2875
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2876
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2877
0
            return -1;
2878
0
        }
2879
4
        return 0;
2880
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2870
4
    auto loop_done = [&index_keys, this]() -> int {
2871
4
        if (index_keys.empty()) return 0;
2872
4
        DORIS_CLOUD_DEFER {
2873
4
            index_keys.clear();
2874
4
        };
2875
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2876
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2877
0
            return -1;
2878
0
        }
2879
4
        return 0;
2880
4
    };
2881
2882
15
    if (config::enable_recycler_stats_metrics) {
2883
0
        scan_and_statistics_indexes();
2884
0
    }
2885
    // recycle_func and loop_done for scan and recycle
2886
15
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2887
15
}
2888
2889
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2890
251
                             int64_t tablet_id) {
2891
251
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2892
2893
248
    std::unique_ptr<Transaction> txn;
2894
248
    TxnErrorCode err = txn_kv->create_txn(&txn);
2895
248
    if (err != TxnErrorCode::TXN_OK) {
2896
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2897
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2898
0
        return false;
2899
0
    }
2900
2901
248
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2902
248
    std::string tablet_idx_val;
2903
248
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2904
248
    if (TxnErrorCode::TXN_OK != err) {
2905
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2906
0
                     << " tablet_id=" << tablet_id << " err=" << err
2907
0
                     << " key=" << hex(tablet_idx_key);
2908
0
        return false;
2909
0
    }
2910
2911
248
    TabletIndexPB tablet_idx_pb;
2912
248
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2913
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2914
0
                     << " tablet_id=" << tablet_id;
2915
0
        return false;
2916
0
    }
2917
2918
248
    if (!tablet_idx_pb.has_db_id()) {
2919
        // In the previous version, the db_id was not set in the index_pb.
2920
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2921
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2922
0
                  << " instance_id=" << instance_id
2923
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2924
0
        return true;
2925
0
    }
2926
2927
248
    std::string ver_val;
2928
248
    std::string ver_key =
2929
248
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2930
248
                                   tablet_idx_pb.partition_id()});
2931
248
    err = txn->get(ver_key, &ver_val);
2932
2933
248
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2934
214
        LOG(INFO) << ""
2935
214
                     "partition version not found, instance_id="
2936
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2937
214
                  << " table_id=" << tablet_idx_pb.table_id()
2938
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2939
214
                  << " key=" << hex(ver_key);
2940
214
        return true;
2941
214
    }
2942
2943
34
    if (TxnErrorCode::TXN_OK != err) {
2944
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2945
0
                     << " db_id=" << tablet_idx_pb.db_id()
2946
0
                     << " table_id=" << tablet_idx_pb.table_id()
2947
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2948
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2949
0
        return false;
2950
0
    }
2951
2952
34
    VersionPB version_pb;
2953
34
    if (!version_pb.ParseFromString(ver_val)) {
2954
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2955
0
                     << " db_id=" << tablet_idx_pb.db_id()
2956
0
                     << " table_id=" << tablet_idx_pb.table_id()
2957
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2958
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2959
0
        return false;
2960
0
    }
2961
2962
34
    if (version_pb.pending_txn_ids_size() > 0) {
2963
1
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2964
1
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2965
1
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2966
1
                     << " db_id=" << tablet_idx_pb.db_id()
2967
1
                     << " table_id=" << tablet_idx_pb.table_id()
2968
1
                     << " partition_id=" << tablet_idx_pb.partition_id()
2969
1
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2970
1
                     << " key=" << hex(ver_key);
2971
1
        return false;
2972
1
    }
2973
33
    return true;
2974
34
}
2975
2976
13
int InstanceRecycler::recycle_partitions() {
2977
13
    const std::string task_name = "recycle_partitions";
2978
13
    int64_t num_scanned = 0;
2979
13
    int64_t num_expired = 0;
2980
13
    int64_t num_recycled = 0;
2981
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2982
2983
13
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2984
13
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2985
13
    std::string part_key0;
2986
13
    std::string part_key1;
2987
13
    recycle_partition_key(part_key_info0, &part_key0);
2988
13
    recycle_partition_key(part_key_info1, &part_key1);
2989
2990
13
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2991
2992
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2993
13
    register_recycle_task(task_name, start_time);
2994
2995
13
    DORIS_CLOUD_DEFER {
2996
13
        unregister_recycle_task(task_name);
2997
13
        int64_t cost =
2998
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2999
13
        metrics_context.finish_report();
3000
13
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3001
13
                .tag("instance_id", instance_id_)
3002
13
                .tag("num_scanned", num_scanned)
3003
13
                .tag("num_expired", num_expired)
3004
13
                .tag("num_recycled", num_recycled);
3005
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2995
13
    DORIS_CLOUD_DEFER {
2996
13
        unregister_recycle_task(task_name);
2997
13
        int64_t cost =
2998
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2999
13
        metrics_context.finish_report();
3000
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3001
13
                .tag("instance_id", instance_id_)
3002
13
                .tag("num_scanned", num_scanned)
3003
13
                .tag("num_expired", num_expired)
3004
13
                .tag("num_recycled", num_recycled);
3005
13
    };
3006
3007
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3008
3009
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3010
13
    std::vector<std::string_view> partition_keys;
3011
13
    std::vector<std::string> partition_version_keys;
3012
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3013
7
        ++num_scanned;
3014
7
        RecyclePartitionPB part_pb;
3015
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3016
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3017
0
            return -1;
3018
0
        }
3019
7
        int64_t current_time = ::time(nullptr);
3020
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3021
7
                                                            &earlest_ts)) { // not expired
3022
0
            return 0;
3023
0
        }
3024
7
        ++num_expired;
3025
        // decode partition_id
3026
7
        auto k1 = k;
3027
7
        k1.remove_prefix(1);
3028
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3029
7
        decode_key(&k1, &out);
3030
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3031
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3032
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3033
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3034
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3035
        // Change state to RECYCLING
3036
7
        std::unique_ptr<Transaction> txn;
3037
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3038
7
        if (err != TxnErrorCode::TXN_OK) {
3039
0
            LOG_WARNING("failed to create txn").tag("err", err);
3040
0
            return -1;
3041
0
        }
3042
7
        std::string val;
3043
7
        err = txn->get(k, &val);
3044
7
        if (err ==
3045
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3046
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3047
0
            return 0;
3048
0
        }
3049
7
        if (err != TxnErrorCode::TXN_OK) {
3050
0
            LOG_WARNING("failed to get kv");
3051
0
            return -1;
3052
0
        }
3053
7
        part_pb.Clear();
3054
7
        if (!part_pb.ParseFromString(val)) {
3055
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3056
0
            return -1;
3057
0
        }
3058
        // Partitions with PREPARED state MUST have no data
3059
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3060
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3061
7
            txn->put(k, part_pb.SerializeAsString());
3062
7
            err = txn->commit();
3063
7
            if (err != TxnErrorCode::TXN_OK) {
3064
0
                LOG_WARNING("failed to commit txn: {}", err);
3065
0
                return -1;
3066
0
            }
3067
7
        }
3068
3069
7
        int ret = 0;
3070
31
        for (int64_t index_id : part_pb.index_id()) {
3071
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3072
0
                LOG_WARNING("failed to recycle tablets under partition")
3073
0
                        .tag("table_id", part_pb.table_id())
3074
0
                        .tag("instance_id", instance_id_)
3075
0
                        .tag("index_id", index_id)
3076
0
                        .tag("partition_id", partition_id);
3077
0
                ret = -1;
3078
0
            }
3079
31
        }
3080
7
        if (ret == 0 && part_pb.has_db_id()) {
3081
            // Recycle the versioned keys
3082
7
            std::unique_ptr<Transaction> txn;
3083
7
            err = txn_kv_->create_txn(&txn);
3084
7
            if (err != TxnErrorCode::TXN_OK) {
3085
0
                LOG_WARNING("failed to create txn").tag("err", err);
3086
0
                return -1;
3087
0
            }
3088
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3089
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3090
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3091
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3092
7
            std::string partition_version_key =
3093
7
                    versioned::partition_version_key({instance_id_, partition_id});
3094
7
            versioned_remove_all(txn.get(), meta_key);
3095
7
            txn->remove(index_key);
3096
7
            txn->remove(inverted_index_key);
3097
7
            versioned_remove_all(txn.get(), partition_version_key);
3098
7
            err = txn->commit();
3099
7
            if (err != TxnErrorCode::TXN_OK) {
3100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3101
0
                return -1;
3102
0
            }
3103
7
        }
3104
3105
7
        if (ret == 0) {
3106
7
            ++num_recycled;
3107
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3108
7
            partition_keys.push_back(k);
3109
7
            if (part_pb.db_id() > 0) {
3110
7
                partition_version_keys.push_back(partition_version_key(
3111
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3112
7
            }
3113
7
            metrics_context.total_recycled_num = num_recycled;
3114
7
            metrics_context.report();
3115
7
        }
3116
7
        return ret;
3117
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3012
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3013
7
        ++num_scanned;
3014
7
        RecyclePartitionPB part_pb;
3015
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3016
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3017
0
            return -1;
3018
0
        }
3019
7
        int64_t current_time = ::time(nullptr);
3020
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3021
7
                                                            &earlest_ts)) { // not expired
3022
0
            return 0;
3023
0
        }
3024
7
        ++num_expired;
3025
        // decode partition_id
3026
7
        auto k1 = k;
3027
7
        k1.remove_prefix(1);
3028
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3029
7
        decode_key(&k1, &out);
3030
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3031
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3032
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3033
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3034
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3035
        // Change state to RECYCLING
3036
7
        std::unique_ptr<Transaction> txn;
3037
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3038
7
        if (err != TxnErrorCode::TXN_OK) {
3039
0
            LOG_WARNING("failed to create txn").tag("err", err);
3040
0
            return -1;
3041
0
        }
3042
7
        std::string val;
3043
7
        err = txn->get(k, &val);
3044
7
        if (err ==
3045
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3046
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3047
0
            return 0;
3048
0
        }
3049
7
        if (err != TxnErrorCode::TXN_OK) {
3050
0
            LOG_WARNING("failed to get kv");
3051
0
            return -1;
3052
0
        }
3053
7
        part_pb.Clear();
3054
7
        if (!part_pb.ParseFromString(val)) {
3055
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3056
0
            return -1;
3057
0
        }
3058
        // Partitions with PREPARED state MUST have no data
3059
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3060
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3061
7
            txn->put(k, part_pb.SerializeAsString());
3062
7
            err = txn->commit();
3063
7
            if (err != TxnErrorCode::TXN_OK) {
3064
0
                LOG_WARNING("failed to commit txn: {}", err);
3065
0
                return -1;
3066
0
            }
3067
7
        }
3068
3069
7
        int ret = 0;
3070
31
        for (int64_t index_id : part_pb.index_id()) {
3071
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3072
0
                LOG_WARNING("failed to recycle tablets under partition")
3073
0
                        .tag("table_id", part_pb.table_id())
3074
0
                        .tag("instance_id", instance_id_)
3075
0
                        .tag("index_id", index_id)
3076
0
                        .tag("partition_id", partition_id);
3077
0
                ret = -1;
3078
0
            }
3079
31
        }
3080
7
        if (ret == 0 && part_pb.has_db_id()) {
3081
            // Recycle the versioned keys
3082
7
            std::unique_ptr<Transaction> txn;
3083
7
            err = txn_kv_->create_txn(&txn);
3084
7
            if (err != TxnErrorCode::TXN_OK) {
3085
0
                LOG_WARNING("failed to create txn").tag("err", err);
3086
0
                return -1;
3087
0
            }
3088
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3089
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3090
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3091
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3092
7
            std::string partition_version_key =
3093
7
                    versioned::partition_version_key({instance_id_, partition_id});
3094
7
            versioned_remove_all(txn.get(), meta_key);
3095
7
            txn->remove(index_key);
3096
7
            txn->remove(inverted_index_key);
3097
7
            versioned_remove_all(txn.get(), partition_version_key);
3098
7
            err = txn->commit();
3099
7
            if (err != TxnErrorCode::TXN_OK) {
3100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3101
0
                return -1;
3102
0
            }
3103
7
        }
3104
3105
7
        if (ret == 0) {
3106
7
            ++num_recycled;
3107
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3108
7
            partition_keys.push_back(k);
3109
7
            if (part_pb.db_id() > 0) {
3110
7
                partition_version_keys.push_back(partition_version_key(
3111
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3112
7
            }
3113
7
            metrics_context.total_recycled_num = num_recycled;
3114
7
            metrics_context.report();
3115
7
        }
3116
7
        return ret;
3117
7
    };
3118
3119
13
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3120
3
        if (partition_keys.empty()) return 0;
3121
3
        DORIS_CLOUD_DEFER {
3122
3
            partition_keys.clear();
3123
3
            partition_version_keys.clear();
3124
3
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3121
3
        DORIS_CLOUD_DEFER {
3122
3
            partition_keys.clear();
3123
3
            partition_version_keys.clear();
3124
3
        };
3125
3
        std::unique_ptr<Transaction> txn;
3126
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3127
3
        if (err != TxnErrorCode::TXN_OK) {
3128
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3129
0
            return -1;
3130
0
        }
3131
7
        for (auto& k : partition_keys) {
3132
7
            txn->remove(k);
3133
7
        }
3134
7
        for (auto& k : partition_version_keys) {
3135
7
            txn->remove(k);
3136
7
        }
3137
3
        err = txn->commit();
3138
3
        if (err != TxnErrorCode::TXN_OK) {
3139
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3140
0
                         << " err=" << err;
3141
0
            return -1;
3142
0
        }
3143
3
        return 0;
3144
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3119
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3120
3
        if (partition_keys.empty()) return 0;
3121
3
        DORIS_CLOUD_DEFER {
3122
3
            partition_keys.clear();
3123
3
            partition_version_keys.clear();
3124
3
        };
3125
3
        std::unique_ptr<Transaction> txn;
3126
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3127
3
        if (err != TxnErrorCode::TXN_OK) {
3128
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3129
0
            return -1;
3130
0
        }
3131
7
        for (auto& k : partition_keys) {
3132
7
            txn->remove(k);
3133
7
        }
3134
7
        for (auto& k : partition_version_keys) {
3135
7
            txn->remove(k);
3136
7
        }
3137
3
        err = txn->commit();
3138
3
        if (err != TxnErrorCode::TXN_OK) {
3139
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3140
0
                         << " err=" << err;
3141
0
            return -1;
3142
0
        }
3143
3
        return 0;
3144
3
    };
3145
3146
13
    if (config::enable_recycler_stats_metrics) {
3147
0
        scan_and_statistics_partitions();
3148
0
    }
3149
    // recycle_func and loop_done for scan and recycle
3150
13
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3151
13
}
3152
3153
14
int InstanceRecycler::recycle_versions() {
3154
14
    if (should_recycle_versioned_keys()) {
3155
2
        return recycle_orphan_partitions();
3156
2
    }
3157
3158
12
    int64_t num_scanned = 0;
3159
12
    int64_t num_recycled = 0;
3160
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3161
3162
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3163
3164
12
    auto start_time = steady_clock::now();
3165
3166
12
    DORIS_CLOUD_DEFER {
3167
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3168
12
        metrics_context.finish_report();
3169
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3170
12
                .tag("instance_id", instance_id_)
3171
12
                .tag("num_scanned", num_scanned)
3172
12
                .tag("num_recycled", num_recycled);
3173
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3166
12
    DORIS_CLOUD_DEFER {
3167
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3168
12
        metrics_context.finish_report();
3169
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3170
12
                .tag("instance_id", instance_id_)
3171
12
                .tag("num_scanned", num_scanned)
3172
12
                .tag("num_recycled", num_recycled);
3173
12
    };
3174
3175
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3176
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3177
12
    int64_t last_scanned_table_id = 0;
3178
12
    bool is_recycled = false; // Is last scanned kv recycled
3179
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3180
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3181
2
        ++num_scanned;
3182
2
        auto k1 = k;
3183
2
        k1.remove_prefix(1);
3184
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3185
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3186
2
        decode_key(&k1, &out);
3187
2
        DCHECK_EQ(out.size(), 6) << k;
3188
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3189
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3190
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3191
0
            return 0;
3192
0
        }
3193
2
        last_scanned_table_id = table_id;
3194
2
        is_recycled = false;
3195
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3196
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3197
2
        std::unique_ptr<Transaction> txn;
3198
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3199
2
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            return -1;
3201
0
        }
3202
2
        std::unique_ptr<RangeGetIterator> iter;
3203
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3204
2
        if (err != TxnErrorCode::TXN_OK) {
3205
0
            return -1;
3206
0
        }
3207
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3208
1
            return 0;
3209
1
        }
3210
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3211
        // 1. Remove all partition version kvs of this table
3212
1
        auto partition_version_key_begin =
3213
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3214
1
        auto partition_version_key_end =
3215
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3216
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3217
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3218
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3219
1
                     << " table_id=" << table_id;
3220
        // 2. Remove the table version kv of this table
3221
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3222
1
        txn->remove(tbl_version_key);
3223
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3224
        // 3. Remove mow delete bitmap update lock and tablet job lock
3225
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3226
1
        txn->remove(lock_key);
3227
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3228
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3229
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3230
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3231
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3232
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3233
1
                     << " table_id=" << table_id;
3234
1
        err = txn->commit();
3235
1
        if (err != TxnErrorCode::TXN_OK) {
3236
0
            return -1;
3237
0
        }
3238
1
        metrics_context.total_recycled_num = ++num_recycled;
3239
1
        metrics_context.report();
3240
1
        is_recycled = true;
3241
1
        return 0;
3242
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3180
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3181
2
        ++num_scanned;
3182
2
        auto k1 = k;
3183
2
        k1.remove_prefix(1);
3184
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3185
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3186
2
        decode_key(&k1, &out);
3187
2
        DCHECK_EQ(out.size(), 6) << k;
3188
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3189
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3190
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3191
0
            return 0;
3192
0
        }
3193
2
        last_scanned_table_id = table_id;
3194
2
        is_recycled = false;
3195
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3196
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3197
2
        std::unique_ptr<Transaction> txn;
3198
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3199
2
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            return -1;
3201
0
        }
3202
2
        std::unique_ptr<RangeGetIterator> iter;
3203
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3204
2
        if (err != TxnErrorCode::TXN_OK) {
3205
0
            return -1;
3206
0
        }
3207
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3208
1
            return 0;
3209
1
        }
3210
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3211
        // 1. Remove all partition version kvs of this table
3212
1
        auto partition_version_key_begin =
3213
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3214
1
        auto partition_version_key_end =
3215
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3216
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3217
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3218
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3219
1
                     << " table_id=" << table_id;
3220
        // 2. Remove the table version kv of this table
3221
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3222
1
        txn->remove(tbl_version_key);
3223
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3224
        // 3. Remove mow delete bitmap update lock and tablet job lock
3225
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3226
1
        txn->remove(lock_key);
3227
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3228
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3229
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3230
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3231
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3232
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3233
1
                     << " table_id=" << table_id;
3234
1
        err = txn->commit();
3235
1
        if (err != TxnErrorCode::TXN_OK) {
3236
0
            return -1;
3237
0
        }
3238
1
        metrics_context.total_recycled_num = ++num_recycled;
3239
1
        metrics_context.report();
3240
1
        is_recycled = true;
3241
1
        return 0;
3242
1
    };
3243
3244
12
    if (config::enable_recycler_stats_metrics) {
3245
0
        scan_and_statistics_versions();
3246
0
    }
3247
    // recycle_func and loop_done for scan and recycle
3248
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3249
14
}
3250
3251
3
int InstanceRecycler::recycle_orphan_partitions() {
3252
3
    int64_t num_scanned = 0;
3253
3
    int64_t num_recycled = 0;
3254
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3255
3256
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3257
3
            .tag("instance_id", instance_id_);
3258
3259
3
    auto start_time = steady_clock::now();
3260
3261
3
    DORIS_CLOUD_DEFER {
3262
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3263
3
        metrics_context.finish_report();
3264
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3265
3
                .tag("instance_id", instance_id_)
3266
3
                .tag("num_scanned", num_scanned)
3267
3
                .tag("num_recycled", num_recycled);
3268
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3261
3
    DORIS_CLOUD_DEFER {
3262
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3263
3
        metrics_context.finish_report();
3264
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3265
3
                .tag("instance_id", instance_id_)
3266
3
                .tag("num_scanned", num_scanned)
3267
3
                .tag("num_recycled", num_recycled);
3268
3
    };
3269
3270
3
    bool is_empty_table = false;        // whether the table has no indexes
3271
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3272
3
    int64_t current_table_id = 0;       // current scanning table id
3273
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3274
3
                         &current_table_id, &is_table_kvs_recycled,
3275
3
                         this](std::string_view k, std::string_view) {
3276
2
        ++num_scanned;
3277
3278
2
        std::string_view k1(k);
3279
2
        int64_t db_id, table_id, partition_id;
3280
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3281
2
                                                            &partition_id)) {
3282
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3283
0
            return -1;
3284
2
        } else if (table_id != current_table_id) {
3285
2
            current_table_id = table_id;
3286
2
            is_table_kvs_recycled = false;
3287
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3288
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3289
2
            if (err != TxnErrorCode::TXN_OK) {
3290
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3291
0
                             << " table_id=" << table_id << " err=" << err;
3292
0
                return -1;
3293
0
            }
3294
2
        }
3295
3296
2
        if (!is_empty_table) {
3297
            // table is not empty, skip recycle
3298
1
            return 0;
3299
1
        }
3300
3301
1
        std::unique_ptr<Transaction> txn;
3302
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3303
1
        if (err != TxnErrorCode::TXN_OK) {
3304
0
            return -1;
3305
0
        }
3306
3307
        // 1. Remove all partition related kvs
3308
1
        std::string partition_meta_key =
3309
1
                versioned::meta_partition_key({instance_id_, partition_id});
3310
1
        std::string partition_index_key =
3311
1
                versioned::partition_index_key({instance_id_, partition_id});
3312
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3313
1
                {instance_id_, db_id, table_id, partition_id});
3314
1
        std::string partition_version_key =
3315
1
                versioned::partition_version_key({instance_id_, partition_id});
3316
1
        txn->remove(partition_index_key);
3317
1
        txn->remove(partition_inverted_key);
3318
1
        versioned_remove_all(txn.get(), partition_meta_key);
3319
1
        versioned_remove_all(txn.get(), partition_version_key);
3320
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3321
1
                     << " table_id=" << table_id << " db_id=" << db_id
3322
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3323
1
                     << " partition_version_key=" << hex(partition_version_key);
3324
3325
1
        if (!is_table_kvs_recycled) {
3326
1
            is_table_kvs_recycled = true;
3327
3328
            // 2. Remove the table version kv of this table
3329
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3330
1
            versioned_remove_all(txn.get(), table_version_key);
3331
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3332
            // 3. Remove mow delete bitmap update lock and tablet job lock
3333
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3334
1
            txn->remove(lock_key);
3335
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3336
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3337
1
            std::string tablet_job_key_end =
3338
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3339
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3340
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3341
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3342
1
                         << " table_id=" << table_id;
3343
1
        }
3344
3345
1
        err = txn->commit();
3346
1
        if (err != TxnErrorCode::TXN_OK) {
3347
0
            return -1;
3348
0
        }
3349
1
        metrics_context.total_recycled_num = ++num_recycled;
3350
1
        metrics_context.report();
3351
1
        return 0;
3352
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
3275
2
                         this](std::string_view k, std::string_view) {
3276
2
        ++num_scanned;
3277
3278
2
        std::string_view k1(k);
3279
2
        int64_t db_id, table_id, partition_id;
3280
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3281
2
                                                            &partition_id)) {
3282
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3283
0
            return -1;
3284
2
        } else if (table_id != current_table_id) {
3285
2
            current_table_id = table_id;
3286
2
            is_table_kvs_recycled = false;
3287
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3288
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3289
2
            if (err != TxnErrorCode::TXN_OK) {
3290
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3291
0
                             << " table_id=" << table_id << " err=" << err;
3292
0
                return -1;
3293
0
            }
3294
2
        }
3295
3296
2
        if (!is_empty_table) {
3297
            // table is not empty, skip recycle
3298
1
            return 0;
3299
1
        }
3300
3301
1
        std::unique_ptr<Transaction> txn;
3302
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3303
1
        if (err != TxnErrorCode::TXN_OK) {
3304
0
            return -1;
3305
0
        }
3306
3307
        // 1. Remove all partition related kvs
3308
1
        std::string partition_meta_key =
3309
1
                versioned::meta_partition_key({instance_id_, partition_id});
3310
1
        std::string partition_index_key =
3311
1
                versioned::partition_index_key({instance_id_, partition_id});
3312
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3313
1
                {instance_id_, db_id, table_id, partition_id});
3314
1
        std::string partition_version_key =
3315
1
                versioned::partition_version_key({instance_id_, partition_id});
3316
1
        txn->remove(partition_index_key);
3317
1
        txn->remove(partition_inverted_key);
3318
1
        versioned_remove_all(txn.get(), partition_meta_key);
3319
1
        versioned_remove_all(txn.get(), partition_version_key);
3320
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3321
1
                     << " table_id=" << table_id << " db_id=" << db_id
3322
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3323
1
                     << " partition_version_key=" << hex(partition_version_key);
3324
3325
1
        if (!is_table_kvs_recycled) {
3326
1
            is_table_kvs_recycled = true;
3327
3328
            // 2. Remove the table version kv of this table
3329
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3330
1
            versioned_remove_all(txn.get(), table_version_key);
3331
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3332
            // 3. Remove mow delete bitmap update lock and tablet job lock
3333
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3334
1
            txn->remove(lock_key);
3335
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3336
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3337
1
            std::string tablet_job_key_end =
3338
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3339
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3340
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3341
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3342
1
                         << " table_id=" << table_id;
3343
1
        }
3344
3345
1
        err = txn->commit();
3346
1
        if (err != TxnErrorCode::TXN_OK) {
3347
0
            return -1;
3348
0
        }
3349
1
        metrics_context.total_recycled_num = ++num_recycled;
3350
1
        metrics_context.report();
3351
1
        return 0;
3352
1
    };
3353
3354
    // recycle_func and loop_done for scan and recycle
3355
3
    return scan_and_recycle(
3356
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3357
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3358
3
            std::move(recycle_func));
3359
3
}
3360
3361
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3362
                                      RecyclerMetricsContext& metrics_context,
3363
48
                                      int64_t partition_id) {
3364
48
    bool is_multi_version =
3365
48
            instance_info_.has_multi_version_status() &&
3366
48
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3367
48
    int64_t num_scanned = 0;
3368
48
    std::atomic_long num_recycled = 0;
3369
3370
48
    std::string tablet_key_begin, tablet_key_end;
3371
48
    std::string stats_key_begin, stats_key_end;
3372
48
    std::string job_key_begin, job_key_end;
3373
3374
48
    std::string tablet_belongs;
3375
48
    if (partition_id > 0) {
3376
        // recycle tablets in a partition belonging to the index
3377
31
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3378
31
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3379
31
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3380
31
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3381
31
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3382
31
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3383
31
        tablet_belongs = "partition";
3384
31
    } else {
3385
        // recycle tablets in the index
3386
17
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3387
17
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3388
17
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3389
17
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3390
17
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3391
17
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3392
17
        tablet_belongs = "index";
3393
17
    }
3394
3395
48
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3396
48
            .tag("table_id", table_id)
3397
48
            .tag("index_id", index_id)
3398
48
            .tag("partition_id", partition_id);
3399
3400
48
    auto start_time = steady_clock::now();
3401
3402
48
    DORIS_CLOUD_DEFER {
3403
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3404
48
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3405
48
                .tag("instance_id", instance_id_)
3406
48
                .tag("table_id", table_id)
3407
48
                .tag("index_id", index_id)
3408
48
                .tag("partition_id", partition_id)
3409
48
                .tag("num_scanned", num_scanned)
3410
48
                .tag("num_recycled", num_recycled);
3411
48
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3402
48
    DORIS_CLOUD_DEFER {
3403
48
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3404
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3405
48
                .tag("instance_id", instance_id_)
3406
48
                .tag("table_id", table_id)
3407
48
                .tag("index_id", index_id)
3408
48
                .tag("partition_id", partition_id)
3409
48
                .tag("num_scanned", num_scanned)
3410
48
                .tag("num_recycled", num_recycled);
3411
48
    };
3412
3413
    // The tablet key and id which have been recycled.
3414
48
    struct TabletInfo {
3415
48
        std::string_view tablet_meta_key;
3416
48
        int64_t tablet_id;
3417
48
    };
3418
48
    SyncExecutor<TabletInfo> sync_executor(
3419
48
            _thread_pool_group.recycle_tablet_pool,
3420
48
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3421
48
                        index_id, partition_id),
3422
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3422
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3423
3424
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3425
48
    std::vector<std::string> init_rs_keys;
3426
48
    bool has_failure = false;
3427
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3428
251
        ++num_scanned;
3429
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3430
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3431
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3432
0
            has_failure = true;
3433
0
            return -1;
3434
0
        }
3435
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3436
3437
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3438
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3439
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3440
1
            has_failure = true;
3441
1
            return -1;
3442
1
        }
3443
3444
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3445
250
        sync_executor.add(
3446
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3447
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3448
2
                        LOG_WARNING("failed to recycle tablet")
3449
2
                                .tag("instance_id", instance_id_)
3450
2
                                .tag("tablet_id", tid);
3451
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3452
2
                    }
3453
248
                    ++num_recycled;
3454
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3455
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3456
250
                });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3446
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3447
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3448
2
                        LOG_WARNING("failed to recycle tablet")
3449
2
                                .tag("instance_id", instance_id_)
3450
2
                                .tag("tablet_id", tid);
3451
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3452
2
                    }
3453
248
                    ++num_recycled;
3454
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3455
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3456
250
                });
3457
250
        return 0;
3458
250
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3427
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3428
251
        ++num_scanned;
3429
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3430
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3431
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3432
0
            has_failure = true;
3433
0
            return -1;
3434
0
        }
3435
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3436
3437
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3438
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3439
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3440
1
            has_failure = true;
3441
1
            return -1;
3442
1
        }
3443
3444
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3445
250
        sync_executor.add(
3446
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3447
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3448
250
                        LOG_WARNING("failed to recycle tablet")
3449
250
                                .tag("instance_id", instance_id_)
3450
250
                                .tag("tablet_id", tid);
3451
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3452
250
                    }
3453
250
                    ++num_recycled;
3454
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3455
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3456
250
                });
3457
250
        return 0;
3458
250
    };
3459
3460
48
    auto loop_done = [&, this]() -> int {
3461
48
        int ret = 0;
3462
48
        bool finished = true;
3463
48
        bool has_empty_key = false;
3464
48
        DORIS_CLOUD_DEFER {
3465
48
            init_rs_keys.clear();
3466
48
            has_failure = false;
3467
48
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3464
48
        DORIS_CLOUD_DEFER {
3465
48
            init_rs_keys.clear();
3466
48
            has_failure = false;
3467
48
        };
3468
48
        auto tablets_info = sync_executor.when_all(&finished);
3469
48
        if (!finished) {
3470
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3471
1
            return -1;
3472
1
        }
3473
3474
47
        size_t size_before_erase = tablets_info.size();
3475
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3475
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3476
47
        if (tablets_info.empty()) {
3477
0
            return size_before_erase == 0 ? 0 : -1;
3478
47
        } else if (size_before_erase != tablets_info.size()) {
3479
1
            has_empty_key = true;
3480
1
        }
3481
3482
47
        ret = has_empty_key ? -1 : 0;
3483
        // sort the vector using key's order
3484
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3485
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3486
958
        });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3484
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3485
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3486
958
        });
3487
47
        std::unique_ptr<Transaction> txn;
3488
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3489
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3490
0
            return -1;
3491
0
        }
3492
47
        std::string tablet_key_end;
3493
47
        if (!tablets_info.empty()) {
3494
47
            if (!has_empty_key && !has_failure) {
3495
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3496
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3497
45
            } else {
3498
8
                for (auto& tablet_info : tablets_info) {
3499
8
                    txn->remove(tablet_info.tablet_meta_key);
3500
8
                }
3501
2
            }
3502
47
        }
3503
47
        if (is_multi_version) {
3504
6
            for (auto& tablet_info : tablets_info) {
3505
                // Remove all versions of tablet compact stats for recycled tablet
3506
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3507
6
                LOG_INFO("remove versioned tablet compact stats key")
3508
6
                        .tag("compact_stats_key", hex(k));
3509
6
                versioned_remove_all(txn.get(), k);
3510
6
            }
3511
6
            for (auto& tablet_info : tablets_info) {
3512
                // Remove all versions of tablet load stats for recycled tablet
3513
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3514
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3515
6
                versioned_remove_all(txn.get(), k);
3516
6
            }
3517
6
            for (auto& tablet_info : tablets_info) {
3518
                // Remove all versions of meta tablet for recycled tablet
3519
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3520
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3521
6
                versioned_remove_all(txn.get(), k);
3522
6
            }
3523
5
        }
3524
248
        for (auto& tablet_info : tablets_info) {
3525
248
            std::string k;
3526
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3527
248
            txn->remove(k);
3528
248
        }
3529
248
        for (auto& tablet_info : tablets_info) {
3530
248
            std::string k;
3531
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3532
248
            txn->remove(k);
3533
248
        }
3534
47
        for (auto& k : init_rs_keys) {
3535
0
            txn->remove(k);
3536
0
        }
3537
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3538
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3539
0
                         << ", err=" << err;
3540
0
            return -1;
3541
0
        }
3542
47
        return ret;
3543
47
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3460
48
    auto loop_done = [&, this]() -> int {
3461
48
        int ret = 0;
3462
48
        bool finished = true;
3463
48
        bool has_empty_key = false;
3464
48
        DORIS_CLOUD_DEFER {
3465
48
            init_rs_keys.clear();
3466
48
            has_failure = false;
3467
48
        };
3468
48
        auto tablets_info = sync_executor.when_all(&finished);
3469
48
        if (!finished) {
3470
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3471
1
            return -1;
3472
1
        }
3473
3474
47
        size_t size_before_erase = tablets_info.size();
3475
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3476
47
        if (tablets_info.empty()) {
3477
0
            return size_before_erase == 0 ? 0 : -1;
3478
47
        } else if (size_before_erase != tablets_info.size()) {
3479
1
            has_empty_key = true;
3480
1
        }
3481
3482
47
        ret = has_empty_key ? -1 : 0;
3483
        // sort the vector using key's order
3484
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3485
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3486
47
        });
3487
47
        std::unique_ptr<Transaction> txn;
3488
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3489
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3490
0
            return -1;
3491
0
        }
3492
47
        std::string tablet_key_end;
3493
47
        if (!tablets_info.empty()) {
3494
47
            if (!has_empty_key && !has_failure) {
3495
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3496
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3497
45
            } else {
3498
8
                for (auto& tablet_info : tablets_info) {
3499
8
                    txn->remove(tablet_info.tablet_meta_key);
3500
8
                }
3501
2
            }
3502
47
        }
3503
47
        if (is_multi_version) {
3504
6
            for (auto& tablet_info : tablets_info) {
3505
                // Remove all versions of tablet compact stats for recycled tablet
3506
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3507
6
                LOG_INFO("remove versioned tablet compact stats key")
3508
6
                        .tag("compact_stats_key", hex(k));
3509
6
                versioned_remove_all(txn.get(), k);
3510
6
            }
3511
6
            for (auto& tablet_info : tablets_info) {
3512
                // Remove all versions of tablet load stats for recycled tablet
3513
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3514
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3515
6
                versioned_remove_all(txn.get(), k);
3516
6
            }
3517
6
            for (auto& tablet_info : tablets_info) {
3518
                // Remove all versions of meta tablet for recycled tablet
3519
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3520
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3521
6
                versioned_remove_all(txn.get(), k);
3522
6
            }
3523
5
        }
3524
248
        for (auto& tablet_info : tablets_info) {
3525
248
            std::string k;
3526
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3527
248
            txn->remove(k);
3528
248
        }
3529
248
        for (auto& tablet_info : tablets_info) {
3530
248
            std::string k;
3531
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3532
248
            txn->remove(k);
3533
248
        }
3534
47
        for (auto& k : init_rs_keys) {
3535
0
            txn->remove(k);
3536
0
        }
3537
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3538
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3539
0
                         << ", err=" << err;
3540
0
            return -1;
3541
0
        }
3542
47
        return ret;
3543
47
    };
3544
3545
48
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3546
48
                               std::move(loop_done));
3547
48
    if (ret != 0) {
3548
3
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3549
3
        return ret;
3550
3
    }
3551
3552
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3553
45
    std::unique_ptr<Transaction> txn;
3554
45
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3555
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3556
0
        return -1;
3557
0
    }
3558
45
    txn->remove(stats_key_begin, stats_key_end);
3559
45
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3560
45
                 << " end=" << hex(stats_key_end);
3561
45
    txn->remove(job_key_begin, job_key_end);
3562
45
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3563
45
    std::string schema_key_begin, schema_key_end;
3564
45
    std::string schema_dict_key;
3565
45
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3566
45
    if (partition_id <= 0) {
3567
        // Delete schema kv of this index
3568
14
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3569
14
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3570
14
        txn->remove(schema_key_begin, schema_key_end);
3571
14
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3572
14
                     << " end=" << hex(schema_key_end);
3573
14
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3574
14
        txn->remove(schema_dict_key);
3575
14
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3576
14
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3577
14
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3578
14
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3579
14
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3580
14
                     << " end=" << hex(versioned_schema_key_end);
3581
14
    }
3582
3583
45
    TxnErrorCode err = txn->commit();
3584
45
    if (err != TxnErrorCode::TXN_OK) {
3585
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3586
0
                     << " err=" << err;
3587
0
        return -1;
3588
0
    }
3589
3590
45
    return ret;
3591
45
}
3592
3593
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3594
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3595
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3596
5.61k
    if (num_segments <= 0) return 0;
3597
3598
5.61k
    std::vector<std::string> file_paths;
3599
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3600
0
        return -1;
3601
0
    }
3602
3603
    // Process inverted indexes
3604
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3605
    // default format as v1.
3606
5.61k
    InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
3607
5.61k
    bool delete_rowset_data_by_prefix = false;
3608
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3609
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3610
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3611
0
        delete_rowset_data_by_prefix = true;
3612
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3613
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3614
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3615
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3616
10.0k
            }
3617
10.0k
        }
3618
4.80k
        if (rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3619
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3620
2.00k
        }
3621
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3622
        // schema version and index id are not found, delete rowset data by prefix directly.
3623
0
        delete_rowset_data_by_prefix = true;
3624
809
    } else {
3625
        // otherwise, try to get schema kv
3626
809
        InvertedIndexInfo index_info;
3627
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3628
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3629
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3630
809
                                 &inverted_index_get_ret);
3631
809
        if (inverted_index_get_ret == 0) {
3632
809
            index_format = index_info.first;
3633
809
            index_ids = index_info.second;
3634
809
        } else if (inverted_index_get_ret == 1) {
3635
            // 1. Schema kv not found means tablet has been recycled
3636
            // Maybe some tablet recycle failed by some bugs
3637
            // We need to delete again to double check
3638
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3639
            // because we are uncertain about the inverted index information.
3640
            // If there are inverted indexes, some data might not be deleted,
3641
            // but this is acceptable as we have made our best effort to delete the data.
3642
0
            LOG_INFO(
3643
0
                    "delete rowset data schema kv not found, need to delete again to double "
3644
0
                    "check")
3645
0
                    .tag("instance_id", instance_id_)
3646
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3647
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3648
            // Currently index_ids is guaranteed to be empty,
3649
            // but we clear it again here as a safeguard against future code changes
3650
            // that might cause index_ids to no longer be empty
3651
0
            index_format = InvertedIndexStorageFormatPB::V2;
3652
0
            index_ids.clear();
3653
0
        } else {
3654
            // failed to get schema kv, delete rowset data by prefix directly.
3655
0
            delete_rowset_data_by_prefix = true;
3656
0
        }
3657
809
    }
3658
3659
5.61k
    if (delete_rowset_data_by_prefix) {
3660
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3661
0
                                  rs_meta_pb.rowset_id_v2());
3662
0
    }
3663
3664
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3665
5.61k
    if (it == accessor_map_.end()) {
3666
1.59k
        LOG_WARNING("instance has no such resource id")
3667
1.59k
                .tag("instance_id", instance_id_)
3668
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3669
1.59k
        return -1;
3670
1.59k
    }
3671
4.01k
    auto& accessor = it->second;
3672
3673
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3674
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3675
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3676
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3677
20.0k
                                         &file_paths);
3678
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3679
40.0k
            for (const auto& index_id : index_ids) {
3680
40.0k
                add_file_to_delete_if_not_packed(
3681
40.0k
                        rs_meta_pb,
3682
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3683
40.0k
                                               index_id.second),
3684
40.0k
                        &file_paths);
3685
40.0k
            }
3686
20.0k
        } else if (!index_ids.empty()) {
3687
0
            add_file_to_delete_if_not_packed(
3688
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3689
0
        }
3690
20.0k
    }
3691
3692
    // Process delete bitmap - check where it's stored.
3693
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3694
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3695
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3696
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3697
0
                .tag("instance_id", instance_id_)
3698
0
                .tag("tablet_id", tablet_id)
3699
0
                .tag("rowset_id", rowset_id);
3700
0
        return -1;
3701
0
    }
3702
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3703
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3704
2.00k
    }
3705
    // TODO(AlexYue): seems could do do batch
3706
4.01k
    return accessor->delete_files(file_paths);
3707
4.01k
}
3708
3709
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3710
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3711
62.6k
            .tag("instance_id", instance_id_)
3712
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3713
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3714
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3715
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3716
62.6k
    if (index_map.empty()) {
3717
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3718
62.6k
                .tag("instance_id", instance_id_)
3719
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3720
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3721
62.6k
        return 0;
3722
62.6k
    }
3723
3724
17
    struct PackedSmallFileInfo {
3725
17
        std::string small_file_path;
3726
17
    };
3727
17
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3728
17
    packed_file_updates.reserve(index_map.size());
3729
27
    for (const auto& [small_path, index_pb] : index_map) {
3730
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3731
0
            continue;
3732
0
        }
3733
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3734
27
                PackedSmallFileInfo {small_path});
3735
27
    }
3736
17
    if (packed_file_updates.empty()) {
3737
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3738
0
                .tag("instance_id", instance_id_)
3739
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3740
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3741
0
                .tag("index_map_size", index_map.size());
3742
0
        return 0;
3743
0
    }
3744
3745
17
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3746
17
    int ret = 0;
3747
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3748
24
        if (small_files.empty()) {
3749
0
            continue;
3750
0
        }
3751
3752
24
        bool success = false;
3753
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3754
24
            std::unique_ptr<Transaction> txn;
3755
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3756
24
            if (err != TxnErrorCode::TXN_OK) {
3757
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3758
0
                        .tag("instance_id", instance_id_)
3759
0
                        .tag("packed_file_path", packed_file_path)
3760
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3761
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3762
0
                        .tag("err", err);
3763
0
                ret = -1;
3764
0
                break;
3765
0
            }
3766
3767
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3768
24
            std::string packed_val;
3769
24
            err = txn->get(packed_key, &packed_val);
3770
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3771
0
                LOG_WARNING("packed file info not found when recycling rowset")
3772
0
                        .tag("instance_id", instance_id_)
3773
0
                        .tag("packed_file_path", packed_file_path)
3774
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3775
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3776
0
                        .tag("key", hex(packed_key))
3777
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3778
                // Skip this packed file entry and continue with others
3779
0
                success = true;
3780
0
                break;
3781
0
            }
3782
24
            if (err != TxnErrorCode::TXN_OK) {
3783
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3784
0
                        .tag("instance_id", instance_id_)
3785
0
                        .tag("packed_file_path", packed_file_path)
3786
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3787
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3788
0
                        .tag("err", err);
3789
0
                ret = -1;
3790
0
                break;
3791
0
            }
3792
3793
24
            cloud::PackedFileInfoPB packed_info;
3794
24
            if (!packed_info.ParseFromString(packed_val)) {
3795
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3796
0
                        .tag("instance_id", instance_id_)
3797
0
                        .tag("packed_file_path", packed_file_path)
3798
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3799
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3800
0
                ret = -1;
3801
0
                break;
3802
0
            }
3803
3804
24
            LOG_INFO("packed file update check")
3805
24
                    .tag("instance_id", instance_id_)
3806
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3807
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3808
24
                    .tag("merged_file_path", packed_file_path)
3809
24
                    .tag("requested_small_files", small_files.size())
3810
24
                    .tag("merge_entries", packed_info.slices_size());
3811
3812
24
            auto* small_file_entries = packed_info.mutable_slices();
3813
24
            int64_t changed_files = 0;
3814
24
            int64_t missing_entries = 0;
3815
24
            int64_t already_deleted = 0;
3816
27
            for (const auto& small_file_info : small_files) {
3817
27
                bool found = false;
3818
87
                for (auto& small_file_entry : *small_file_entries) {
3819
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3820
27
                        if (!small_file_entry.deleted()) {
3821
27
                            small_file_entry.set_deleted(true);
3822
27
                            if (!small_file_entry.corrected()) {
3823
27
                                small_file_entry.set_corrected(true);
3824
27
                            }
3825
27
                            ++changed_files;
3826
27
                        } else {
3827
0
                            ++already_deleted;
3828
0
                        }
3829
27
                        found = true;
3830
27
                        break;
3831
27
                    }
3832
87
                }
3833
27
                if (!found) {
3834
0
                    ++missing_entries;
3835
0
                    LOG_WARNING("packed file info missing small file entry")
3836
0
                            .tag("instance_id", instance_id_)
3837
0
                            .tag("packed_file_path", packed_file_path)
3838
0
                            .tag("small_file_path", small_file_info.small_file_path)
3839
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3840
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3841
0
                }
3842
27
            }
3843
3844
24
            if (changed_files == 0) {
3845
0
                LOG_INFO("skip merge file update: no merge entries changed")
3846
0
                        .tag("instance_id", instance_id_)
3847
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3848
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3849
0
                        .tag("merged_file_path", packed_file_path)
3850
0
                        .tag("missing_entries", missing_entries)
3851
0
                        .tag("already_deleted", already_deleted)
3852
0
                        .tag("requested_small_files", small_files.size())
3853
0
                        .tag("merge_entries", packed_info.slices_size());
3854
0
                success = true;
3855
0
                break;
3856
0
            }
3857
3858
            // Calculate remaining files
3859
24
            int64_t left_file_count = 0;
3860
24
            int64_t left_file_bytes = 0;
3861
141
            for (const auto& small_file_entry : packed_info.slices()) {
3862
141
                if (!small_file_entry.deleted()) {
3863
57
                    ++left_file_count;
3864
57
                    left_file_bytes += small_file_entry.size();
3865
57
                }
3866
141
            }
3867
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3868
24
            packed_info.set_ref_cnt(left_file_count);
3869
24
            LOG_INFO("updated packed file reference info")
3870
24
                    .tag("instance_id", instance_id_)
3871
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3872
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3873
24
                    .tag("packed_file_path", packed_file_path)
3874
24
                    .tag("ref_cnt", left_file_count)
3875
24
                    .tag("left_file_bytes", left_file_bytes);
3876
3877
24
            if (left_file_count == 0) {
3878
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3879
7
            }
3880
3881
24
            std::string updated_val;
3882
24
            if (!packed_info.SerializeToString(&updated_val)) {
3883
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3884
0
                        .tag("instance_id", instance_id_)
3885
0
                        .tag("packed_file_path", packed_file_path)
3886
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3887
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3888
0
                ret = -1;
3889
0
                break;
3890
0
            }
3891
3892
24
            txn->put(packed_key, updated_val);
3893
24
            err = txn->commit();
3894
24
            if (err == TxnErrorCode::TXN_OK) {
3895
24
                success = true;
3896
24
                if (left_file_count == 0) {
3897
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
3898
7
                            .tag("instance_id", instance_id_)
3899
7
                            .tag("packed_file_path", packed_file_path);
3900
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3901
0
                        ret = -1;
3902
0
                    }
3903
7
                }
3904
24
                break;
3905
24
            }
3906
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
3907
0
                if (attempt >= max_retry_times) {
3908
0
                    LOG_WARNING("packed file info update conflict after max retry")
3909
0
                            .tag("instance_id", instance_id_)
3910
0
                            .tag("packed_file_path", packed_file_path)
3911
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3912
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3913
0
                            .tag("changed_files", changed_files)
3914
0
                            .tag("attempt", attempt);
3915
0
                    ret = -1;
3916
0
                    break;
3917
0
                }
3918
0
                LOG_WARNING("packed file info update conflict, retrying")
3919
0
                        .tag("instance_id", instance_id_)
3920
0
                        .tag("packed_file_path", packed_file_path)
3921
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3922
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3923
0
                        .tag("changed_files", changed_files)
3924
0
                        .tag("attempt", attempt);
3925
0
                sleep_for_packed_file_retry();
3926
0
                continue;
3927
0
            }
3928
3929
0
            LOG_WARNING("failed to commit packed file info update")
3930
0
                    .tag("instance_id", instance_id_)
3931
0
                    .tag("packed_file_path", packed_file_path)
3932
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3933
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3934
0
                    .tag("err", err)
3935
0
                    .tag("changed_files", changed_files);
3936
0
            ret = -1;
3937
0
            break;
3938
0
        }
3939
3940
24
        if (!success) {
3941
0
            ret = -1;
3942
0
        }
3943
24
    }
3944
3945
17
    return ret;
3946
17
}
3947
3948
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3949
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
3950
61.0k
        std::vector<std::string>* keys) {
3951
61.0k
    if (out_storage_type) {
3952
58.4k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3953
58.4k
    }
3954
3955
    // Get delete bitmap storage info from FDB
3956
61.0k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3957
61.0k
    std::unique_ptr<Transaction> txn;
3958
61.0k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3959
61.0k
    if (err != TxnErrorCode::TXN_OK) {
3960
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3961
0
                .tag("instance_id", instance_id_)
3962
0
                .tag("tablet_id", tablet_id)
3963
0
                .tag("rowset_id", rowset_id)
3964
0
                .tag("err", err);
3965
0
        return -1;
3966
0
    }
3967
3968
61.0k
    ValueBuf dbm_val;
3969
61.0k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
3970
61.0k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3971
        // No delete bitmap for this rowset, nothing to do
3972
6.19k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
3973
6.19k
                .tag("instance_id", instance_id_)
3974
6.19k
                .tag("tablet_id", tablet_id)
3975
6.19k
                .tag("rowset_id", rowset_id);
3976
6.19k
        return 0;
3977
6.19k
    }
3978
54.8k
    if (err != TxnErrorCode::TXN_OK) {
3979
0
        LOG_WARNING("failed to get delete bitmap storage")
3980
0
                .tag("instance_id", instance_id_)
3981
0
                .tag("tablet_id", tablet_id)
3982
0
                .tag("rowset_id", rowset_id)
3983
0
                .tag("err", err);
3984
0
        return -1;
3985
0
    }
3986
3987
54.8k
    if (keys) {
3988
1.55k
        for (auto& key : dbm_val.keys()) {
3989
1.55k
            keys->push_back(std::move(key));
3990
1.55k
        }
3991
1.55k
    }
3992
3993
54.8k
    DeleteBitmapStoragePB storage;
3994
54.8k
    if (!dbm_val.to_pb(&storage)) {
3995
0
        LOG_WARNING("failed to parse delete bitmap storage")
3996
0
                .tag("instance_id", instance_id_)
3997
0
                .tag("tablet_id", tablet_id)
3998
0
                .tag("rowset_id", rowset_id);
3999
0
        return -1;
4000
0
    }
4001
4002
54.8k
    if (storage.store_in_fdb()) {
4003
1
        if (out_storage_type) {
4004
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4005
1
        }
4006
1
        return 0;
4007
1
    }
4008
4009
    // Check if delete bitmap is stored in standalone file.
4010
54.8k
    if (!storage.has_packed_slice_location() ||
4011
54.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4012
54.8k
        if (out_storage_type) {
4013
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4014
53.5k
        }
4015
54.8k
        return 0;
4016
54.8k
    }
4017
4018
18.4E
    if (out_storage_type) {
4019
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4020
0
    }
4021
4022
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4023
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4024
4025
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4026
18.4E
            .tag("instance_id", instance_id_)
4027
18.4E
            .tag("tablet_id", tablet_id)
4028
18.4E
            .tag("rowset_id", rowset_id)
4029
18.4E
            .tag("packed_file_path", packed_file_path);
4030
4031
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4032
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4033
1
        std::unique_ptr<Transaction> update_txn;
4034
1
        err = txn_kv_->create_txn(&update_txn);
4035
1
        if (err != TxnErrorCode::TXN_OK) {
4036
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4037
0
                    .tag("instance_id", instance_id_)
4038
0
                    .tag("tablet_id", tablet_id)
4039
0
                    .tag("rowset_id", rowset_id)
4040
0
                    .tag("err", err);
4041
0
            return -1;
4042
0
        }
4043
4044
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4045
1
        std::string packed_val;
4046
1
        err = update_txn->get(packed_key, &packed_val);
4047
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4048
0
            LOG_WARNING("packed file info not found for delete bitmap")
4049
0
                    .tag("instance_id", instance_id_)
4050
0
                    .tag("tablet_id", tablet_id)
4051
0
                    .tag("rowset_id", rowset_id)
4052
0
                    .tag("packed_file_path", packed_file_path);
4053
0
            return 0;
4054
0
        }
4055
1
        if (err != TxnErrorCode::TXN_OK) {
4056
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4057
0
                    .tag("instance_id", instance_id_)
4058
0
                    .tag("tablet_id", tablet_id)
4059
0
                    .tag("rowset_id", rowset_id)
4060
0
                    .tag("packed_file_path", packed_file_path)
4061
0
                    .tag("err", err);
4062
0
            return -1;
4063
0
        }
4064
4065
1
        cloud::PackedFileInfoPB packed_info;
4066
1
        if (!packed_info.ParseFromString(packed_val)) {
4067
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4068
0
                    .tag("instance_id", instance_id_)
4069
0
                    .tag("tablet_id", tablet_id)
4070
0
                    .tag("rowset_id", rowset_id)
4071
0
                    .tag("packed_file_path", packed_file_path);
4072
0
            return -1;
4073
0
        }
4074
4075
        // Find and mark the small file entry as deleted
4076
        // Use tablet_id and rowset_id to match entry instead of path,
4077
        // because path format may vary with path_version (with or without shard prefix)
4078
1
        auto* entries = packed_info.mutable_slices();
4079
1
        bool found = false;
4080
1
        bool already_deleted = false;
4081
1
        for (auto& entry : *entries) {
4082
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4083
1
                if (!entry.deleted()) {
4084
1
                    entry.set_deleted(true);
4085
1
                    if (!entry.corrected()) {
4086
1
                        entry.set_corrected(true);
4087
1
                    }
4088
1
                } else {
4089
0
                    already_deleted = true;
4090
0
                }
4091
1
                found = true;
4092
1
                break;
4093
1
            }
4094
1
        }
4095
4096
1
        if (!found) {
4097
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4098
0
                    .tag("instance_id", instance_id_)
4099
0
                    .tag("tablet_id", tablet_id)
4100
0
                    .tag("rowset_id", rowset_id)
4101
0
                    .tag("packed_file_path", packed_file_path);
4102
0
            return 0;
4103
0
        }
4104
4105
1
        if (already_deleted) {
4106
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4107
0
                    .tag("instance_id", instance_id_)
4108
0
                    .tag("tablet_id", tablet_id)
4109
0
                    .tag("rowset_id", rowset_id)
4110
0
                    .tag("packed_file_path", packed_file_path);
4111
0
            return 0;
4112
0
        }
4113
4114
        // Calculate remaining files
4115
1
        int64_t left_file_count = 0;
4116
1
        int64_t left_file_bytes = 0;
4117
1
        for (const auto& entry : packed_info.slices()) {
4118
1
            if (!entry.deleted()) {
4119
0
                ++left_file_count;
4120
0
                left_file_bytes += entry.size();
4121
0
            }
4122
1
        }
4123
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4124
1
        packed_info.set_ref_cnt(left_file_count);
4125
4126
1
        if (left_file_count == 0) {
4127
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4128
1
        }
4129
4130
1
        std::string updated_val;
4131
1
        if (!packed_info.SerializeToString(&updated_val)) {
4132
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4133
0
                    .tag("instance_id", instance_id_)
4134
0
                    .tag("tablet_id", tablet_id)
4135
0
                    .tag("rowset_id", rowset_id)
4136
0
                    .tag("packed_file_path", packed_file_path);
4137
0
            return -1;
4138
0
        }
4139
4140
1
        update_txn->put(packed_key, updated_val);
4141
1
        err = update_txn->commit();
4142
1
        if (err == TxnErrorCode::TXN_OK) {
4143
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4144
1
                    .tag("instance_id", instance_id_)
4145
1
                    .tag("tablet_id", tablet_id)
4146
1
                    .tag("rowset_id", rowset_id)
4147
1
                    .tag("packed_file_path", packed_file_path)
4148
1
                    .tag("left_file_count", left_file_count);
4149
1
            if (left_file_count == 0) {
4150
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4151
0
                    return -1;
4152
0
                }
4153
1
            }
4154
1
            return 0;
4155
1
        }
4156
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4157
0
            if (attempt >= max_retry_times) {
4158
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4159
0
                        .tag("instance_id", instance_id_)
4160
0
                        .tag("tablet_id", tablet_id)
4161
0
                        .tag("rowset_id", rowset_id)
4162
0
                        .tag("packed_file_path", packed_file_path)
4163
0
                        .tag("attempt", attempt);
4164
0
                return -1;
4165
0
            }
4166
0
            sleep_for_packed_file_retry();
4167
0
            continue;
4168
0
        }
4169
4170
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4171
0
                .tag("instance_id", instance_id_)
4172
0
                .tag("tablet_id", tablet_id)
4173
0
                .tag("rowset_id", rowset_id)
4174
0
                .tag("packed_file_path", packed_file_path)
4175
0
                .tag("err", err);
4176
0
        return -1;
4177
0
    }
4178
4179
18.4E
    return -1;
4180
18.4E
}
4181
4182
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4183
                                                const std::string& packed_key,
4184
8
                                                const cloud::PackedFileInfoPB& packed_info) {
4185
8
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4186
0
        LOG_WARNING("packed file missing resource id when recycling")
4187
0
                .tag("instance_id", instance_id_)
4188
0
                .tag("packed_file_path", packed_file_path);
4189
0
        return -1;
4190
0
    }
4191
4192
8
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4193
8
    if (!accessor) {
4194
0
        LOG_WARNING("no accessor available to delete packed file")
4195
0
                .tag("instance_id", instance_id_)
4196
0
                .tag("packed_file_path", packed_file_path)
4197
0
                .tag("resource_id", packed_info.resource_id());
4198
0
        return -1;
4199
0
    }
4200
4201
8
    int del_ret = accessor->delete_file(packed_file_path);
4202
8
    if (del_ret != 0 && del_ret != 1) {
4203
0
        LOG_WARNING("failed to delete packed file")
4204
0
                .tag("instance_id", instance_id_)
4205
0
                .tag("packed_file_path", packed_file_path)
4206
0
                .tag("resource_id", resource_id)
4207
0
                .tag("ret", del_ret);
4208
0
        return -1;
4209
0
    }
4210
8
    if (del_ret == 1) {
4211
0
        LOG_INFO("packed file already removed")
4212
0
                .tag("instance_id", instance_id_)
4213
0
                .tag("packed_file_path", packed_file_path)
4214
0
                .tag("resource_id", resource_id);
4215
8
    } else {
4216
8
        LOG_INFO("deleted packed file")
4217
8
                .tag("instance_id", instance_id_)
4218
8
                .tag("packed_file_path", packed_file_path)
4219
8
                .tag("resource_id", resource_id);
4220
8
    }
4221
4222
8
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4223
8
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4224
8
        std::unique_ptr<Transaction> del_txn;
4225
8
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4226
8
        if (err != TxnErrorCode::TXN_OK) {
4227
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4228
0
                    .tag("instance_id", instance_id_)
4229
0
                    .tag("packed_file_path", packed_file_path)
4230
0
                    .tag("attempt", attempt)
4231
0
                    .tag("err", err);
4232
0
            return -1;
4233
0
        }
4234
4235
8
        std::string latest_val;
4236
8
        err = del_txn->get(packed_key, &latest_val);
4237
8
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4238
0
            return 0;
4239
0
        }
4240
8
        if (err != TxnErrorCode::TXN_OK) {
4241
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4242
0
                    .tag("instance_id", instance_id_)
4243
0
                    .tag("packed_file_path", packed_file_path)
4244
0
                    .tag("attempt", attempt)
4245
0
                    .tag("err", err);
4246
0
            return -1;
4247
0
        }
4248
4249
8
        cloud::PackedFileInfoPB latest_info;
4250
8
        if (!latest_info.ParseFromString(latest_val)) {
4251
0
            LOG_WARNING("failed to parse packed file info before removal")
4252
0
                    .tag("instance_id", instance_id_)
4253
0
                    .tag("packed_file_path", packed_file_path)
4254
0
                    .tag("attempt", attempt);
4255
0
            return -1;
4256
0
        }
4257
4258
8
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4259
8
              latest_info.ref_cnt() == 0)) {
4260
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4261
0
                    .tag("instance_id", instance_id_)
4262
0
                    .tag("packed_file_path", packed_file_path)
4263
0
                    .tag("attempt", attempt);
4264
0
            return 0;
4265
0
        }
4266
4267
8
        del_txn->remove(packed_key);
4268
8
        err = del_txn->commit();
4269
8
        if (err == TxnErrorCode::TXN_OK) {
4270
8
            LOG_INFO("removed packed file metadata")
4271
8
                    .tag("instance_id", instance_id_)
4272
8
                    .tag("packed_file_path", packed_file_path);
4273
8
            return 0;
4274
8
        }
4275
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4276
0
            if (attempt >= max_retry_times) {
4277
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4278
0
                        .tag("instance_id", instance_id_)
4279
0
                        .tag("packed_file_path", packed_file_path)
4280
0
                        .tag("attempt", attempt);
4281
0
                return -1;
4282
0
            }
4283
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4284
0
                    .tag("instance_id", instance_id_)
4285
0
                    .tag("packed_file_path", packed_file_path)
4286
0
                    .tag("attempt", attempt);
4287
0
            sleep_for_packed_file_retry();
4288
0
            continue;
4289
0
        }
4290
0
        LOG_WARNING("failed to remove packed file kv")
4291
0
                .tag("instance_id", instance_id_)
4292
0
                .tag("packed_file_path", packed_file_path)
4293
0
                .tag("attempt", attempt)
4294
0
                .tag("err", err);
4295
0
        return -1;
4296
0
    }
4297
0
    return -1;
4298
8
}
4299
4300
int InstanceRecycler::delete_rowset_data(
4301
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4302
        RecyclerMetricsContext& metrics_context,
4303
94
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4304
94
    int ret = 0;
4305
    // resource_id -> file_paths
4306
94
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4307
    // (resource_id, tablet_id, rowset_id)
4308
94
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4309
94
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4310
4311
56.4k
    for (const auto& [_, rs] : rowsets) {
4312
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4313
        // due to aborted schema change.
4314
56.4k
        if (is_formal_rowset) {
4315
3.16k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4316
                // Tablet has been recycled and this rowset has no packed slices, so file data
4317
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4318
                // slice info must still run to decrement packed file ref counts.
4319
0
                continue;
4320
0
            }
4321
3.16k
        }
4322
4323
56.4k
        int64_t num_segments = rs.num_segments();
4324
        // Check num_segments before accessor lookup, because empty rowsets
4325
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4326
        // set. Skipping them early avoids a spurious "no such resource id" error
4327
        // that marks the entire batch as failed and prevents txn_remove from
4328
        // cleaning up recycle KV keys.
4329
56.4k
        if (num_segments <= 0) {
4330
0
            metrics_context.total_recycled_num++;
4331
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4332
0
            continue;
4333
0
        }
4334
4335
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4336
        // possible if the accessor is not initilized correctly
4337
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4338
2.00k
            LOG_WARNING("instance has no such resource id")
4339
2.00k
                    .tag("instance_id", instance_id_)
4340
2.00k
                    .tag("resource_id", rs.resource_id());
4341
2.00k
            ret = -1;
4342
2.00k
            continue;
4343
2.00k
        }
4344
4345
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4346
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4347
54.4k
        int64_t tablet_id = rs.tablet_id();
4348
54.4k
        LOG_INFO("recycle rowset merge index size")
4349
54.4k
                .tag("instance_id", instance_id_)
4350
54.4k
                .tag("tablet_id", tablet_id)
4351
54.4k
                .tag("rowset_id", rowset_id)
4352
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4353
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4354
0
            ret = -1;
4355
0
            continue;
4356
0
        }
4357
4358
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4359
54.4k
        std::vector<std::string> rowset_dbm_keys;
4360
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4361
54.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4362
54.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4363
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4364
0
                    .tag("instance_id", instance_id_)
4365
0
                    .tag("tablet_id", tablet_id)
4366
0
                    .tag("rowset_id", rowset_id);
4367
0
            ret = -1;
4368
0
            continue;
4369
0
        }
4370
54.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4371
1.55k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4372
1.55k
        }
4373
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4374
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4375
51.5k
        }
4376
4377
        // Process inverted indexes
4378
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4379
        // default format as v1.
4380
54.4k
        InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
4381
54.4k
        int inverted_index_get_ret = 0;
4382
54.4k
        if (rs.has_tablet_schema()) {
4383
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4384
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4385
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4386
53.5k
                }
4387
53.5k
            }
4388
26.8k
            if (rs.tablet_schema().has_inverted_index_storage_format()) {
4389
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4390
26.5k
            }
4391
27.5k
        } else {
4392
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4393
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4394
0
                                "instance_id="
4395
0
                             << instance_id_ << " tablet_id=" << tablet_id
4396
0
                             << " rowset_id=" << rowset_id;
4397
0
                ret = -1;
4398
0
                continue;
4399
0
            }
4400
27.5k
            InvertedIndexInfo index_info;
4401
27.5k
            inverted_index_get_ret =
4402
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4403
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4404
27.5k
                                     &inverted_index_get_ret);
4405
27.5k
            if (inverted_index_get_ret == 0) {
4406
27.0k
                index_format = index_info.first;
4407
27.0k
                index_ids = index_info.second;
4408
27.0k
            } else if (inverted_index_get_ret == 1) {
4409
                // 1. Schema kv not found means tablet has been recycled
4410
                // Maybe some tablet recycle failed by some bugs
4411
                // We need to delete again to double check
4412
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4413
                // because we are uncertain about the inverted index information.
4414
                // If there are inverted indexes, some data might not be deleted,
4415
                // but this is acceptable as we have made our best effort to delete the data.
4416
503
                LOG_INFO(
4417
503
                        "delete rowset data schema kv not found, need to delete again to "
4418
503
                        "double "
4419
503
                        "check")
4420
503
                        .tag("instance_id", instance_id_)
4421
503
                        .tag("tablet_id", tablet_id)
4422
503
                        .tag("rowset", rs.ShortDebugString());
4423
                // Currently index_ids is guaranteed to be empty,
4424
                // but we clear it again here as a safeguard against future code changes
4425
                // that might cause index_ids to no longer be empty
4426
503
                index_format = InvertedIndexStorageFormatPB::V2;
4427
503
                index_ids.clear();
4428
18.4E
            } else {
4429
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4430
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4431
18.4E
                ret = -1;
4432
18.4E
                continue;
4433
18.4E
            }
4434
27.5k
        }
4435
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4436
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4437
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4438
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4439
5
            continue;
4440
5
        }
4441
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4442
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4443
270k
                                             &file_paths);
4444
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4445
537k
                for (const auto& index_id : index_ids) {
4446
537k
                    add_file_to_delete_if_not_packed(
4447
537k
                            rs,
4448
537k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4449
537k
                                                   index_id.second),
4450
537k
                            &file_paths);
4451
537k
                }
4452
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4453
                // try to recycle inverted index v2 when get_ret == 1
4454
                // we treat schema not found as if it has a v2 format inverted index
4455
                // to reduce chance of data leakage
4456
2.50k
                if (inverted_index_get_ret == 1) {
4457
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4458
2.50k
                            .tag("instance_id", instance_id_)
4459
2.50k
                            .tag("inverted index v2 path",
4460
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4461
2.50k
                }
4462
2.50k
                add_file_to_delete_if_not_packed(
4463
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4464
2.50k
            }
4465
270k
        }
4466
54.4k
    }
4467
4468
94
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4469
94
                                                 "delete_rowset_data",
4470
94
                                                 [](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
4470
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
4470
54
                                                 [](const int& ret) { return ret != 0; });
4471
94
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4472
55
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4473
55
            DCHECK(accessor_map_.count(*rid))
4474
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4475
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4476
55
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4477
55
                                     &accessor_map_);
4478
55
            if (!accessor_map_.contains(*rid)) {
4479
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4480
0
                        .tag("resource_id", resource_id)
4481
0
                        .tag("instance_id", instance_id_);
4482
0
                return -1;
4483
0
            }
4484
55
            auto& accessor = accessor_map_[*rid];
4485
55
            int ret = accessor->delete_files(*paths);
4486
55
            if (!ret) {
4487
                // deduplication of different files with the same rowset id
4488
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4489
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4490
55
                std::set<std::string> deleted_rowset_id;
4491
4492
55
                std::for_each(paths->begin(), paths->end(),
4493
55
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4494
862k
                               this](const std::string& path) {
4495
862k
                                  std::vector<std::string> str;
4496
862k
                                  butil::SplitString(path, '/', &str);
4497
862k
                                  std::string rowset_id;
4498
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4499
860k
                                      rowset_id = str.back().substr(0, pos);
4500
860k
                                  } else {
4501
2.01k
                                      if (path.find("packed_file/") != std::string::npos) {
4502
0
                                          return; // packed files do not have rowset_id encoded
4503
0
                                      }
4504
2.01k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4505
2.01k
                                      return;
4506
2.01k
                                  }
4507
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4508
860k
                                  if (rs_meta != rowsets.end() &&
4509
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4510
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4511
54.4k
                                      metrics_context.total_recycled_data_size +=
4512
54.4k
                                              rs_meta->second.total_disk_size();
4513
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4514
54.4k
                                              rs_meta->second.num_segments();
4515
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4516
54.4k
                                              rs_meta->second.total_disk_size();
4517
54.4k
                                      metrics_context.total_recycled_num++;
4518
54.4k
                                  }
4519
860k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4494
7
                               this](const std::string& path) {
4495
7
                                  std::vector<std::string> str;
4496
7
                                  butil::SplitString(path, '/', &str);
4497
7
                                  std::string rowset_id;
4498
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4499
7
                                      rowset_id = str.back().substr(0, pos);
4500
7
                                  } else {
4501
0
                                      if (path.find("packed_file/") != std::string::npos) {
4502
0
                                          return; // packed files do not have rowset_id encoded
4503
0
                                      }
4504
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4505
0
                                      return;
4506
0
                                  }
4507
7
                                  auto rs_meta = rowsets.find(rowset_id);
4508
7
                                  if (rs_meta != rowsets.end() &&
4509
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4510
7
                                      deleted_rowset_id.emplace(rowset_id);
4511
7
                                      metrics_context.total_recycled_data_size +=
4512
7
                                              rs_meta->second.total_disk_size();
4513
7
                                      segment_metrics_context_.total_recycled_num +=
4514
7
                                              rs_meta->second.num_segments();
4515
7
                                      segment_metrics_context_.total_recycled_data_size +=
4516
7
                                              rs_meta->second.total_disk_size();
4517
7
                                      metrics_context.total_recycled_num++;
4518
7
                                  }
4519
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
4494
862k
                               this](const std::string& path) {
4495
862k
                                  std::vector<std::string> str;
4496
862k
                                  butil::SplitString(path, '/', &str);
4497
862k
                                  std::string rowset_id;
4498
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4499
860k
                                      rowset_id = str.back().substr(0, pos);
4500
860k
                                  } else {
4501
2.01k
                                      if (path.find("packed_file/") != std::string::npos) {
4502
0
                                          return; // packed files do not have rowset_id encoded
4503
0
                                      }
4504
2.01k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4505
2.01k
                                      return;
4506
2.01k
                                  }
4507
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4508
860k
                                  if (rs_meta != rowsets.end() &&
4509
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4510
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4511
54.4k
                                      metrics_context.total_recycled_data_size +=
4512
54.4k
                                              rs_meta->second.total_disk_size();
4513
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4514
54.4k
                                              rs_meta->second.num_segments();
4515
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4516
54.4k
                                              rs_meta->second.total_disk_size();
4517
54.4k
                                      metrics_context.total_recycled_num++;
4518
54.4k
                                  }
4519
860k
                              });
4520
55
            }
4521
55
            return ret;
4522
55
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4472
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4473
6
            DCHECK(accessor_map_.count(*rid))
4474
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4475
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4476
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4477
6
                                     &accessor_map_);
4478
6
            if (!accessor_map_.contains(*rid)) {
4479
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4480
0
                        .tag("resource_id", resource_id)
4481
0
                        .tag("instance_id", instance_id_);
4482
0
                return -1;
4483
0
            }
4484
6
            auto& accessor = accessor_map_[*rid];
4485
6
            int ret = accessor->delete_files(*paths);
4486
6
            if (!ret) {
4487
                // deduplication of different files with the same rowset id
4488
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4489
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4490
6
                std::set<std::string> deleted_rowset_id;
4491
4492
6
                std::for_each(paths->begin(), paths->end(),
4493
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4494
6
                               this](const std::string& path) {
4495
6
                                  std::vector<std::string> str;
4496
6
                                  butil::SplitString(path, '/', &str);
4497
6
                                  std::string rowset_id;
4498
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4499
6
                                      rowset_id = str.back().substr(0, pos);
4500
6
                                  } else {
4501
6
                                      if (path.find("packed_file/") != std::string::npos) {
4502
6
                                          return; // packed files do not have rowset_id encoded
4503
6
                                      }
4504
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4505
6
                                      return;
4506
6
                                  }
4507
6
                                  auto rs_meta = rowsets.find(rowset_id);
4508
6
                                  if (rs_meta != rowsets.end() &&
4509
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4510
6
                                      deleted_rowset_id.emplace(rowset_id);
4511
6
                                      metrics_context.total_recycled_data_size +=
4512
6
                                              rs_meta->second.total_disk_size();
4513
6
                                      segment_metrics_context_.total_recycled_num +=
4514
6
                                              rs_meta->second.num_segments();
4515
6
                                      segment_metrics_context_.total_recycled_data_size +=
4516
6
                                              rs_meta->second.total_disk_size();
4517
6
                                      metrics_context.total_recycled_num++;
4518
6
                                  }
4519
6
                              });
4520
6
            }
4521
6
            return ret;
4522
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4472
49
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4473
49
            DCHECK(accessor_map_.count(*rid))
4474
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4475
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4476
49
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4477
49
                                     &accessor_map_);
4478
49
            if (!accessor_map_.contains(*rid)) {
4479
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4480
0
                        .tag("resource_id", resource_id)
4481
0
                        .tag("instance_id", instance_id_);
4482
0
                return -1;
4483
0
            }
4484
49
            auto& accessor = accessor_map_[*rid];
4485
49
            int ret = accessor->delete_files(*paths);
4486
49
            if (!ret) {
4487
                // deduplication of different files with the same rowset id
4488
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4489
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4490
49
                std::set<std::string> deleted_rowset_id;
4491
4492
49
                std::for_each(paths->begin(), paths->end(),
4493
49
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4494
49
                               this](const std::string& path) {
4495
49
                                  std::vector<std::string> str;
4496
49
                                  butil::SplitString(path, '/', &str);
4497
49
                                  std::string rowset_id;
4498
49
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4499
49
                                      rowset_id = str.back().substr(0, pos);
4500
49
                                  } else {
4501
49
                                      if (path.find("packed_file/") != std::string::npos) {
4502
49
                                          return; // packed files do not have rowset_id encoded
4503
49
                                      }
4504
49
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4505
49
                                      return;
4506
49
                                  }
4507
49
                                  auto rs_meta = rowsets.find(rowset_id);
4508
49
                                  if (rs_meta != rowsets.end() &&
4509
49
                                      !deleted_rowset_id.contains(rowset_id)) {
4510
49
                                      deleted_rowset_id.emplace(rowset_id);
4511
49
                                      metrics_context.total_recycled_data_size +=
4512
49
                                              rs_meta->second.total_disk_size();
4513
49
                                      segment_metrics_context_.total_recycled_num +=
4514
49
                                              rs_meta->second.num_segments();
4515
49
                                      segment_metrics_context_.total_recycled_data_size +=
4516
49
                                              rs_meta->second.total_disk_size();
4517
49
                                      metrics_context.total_recycled_num++;
4518
49
                                  }
4519
49
                              });
4520
49
            }
4521
49
            return ret;
4522
49
        });
4523
55
    }
4524
94
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4525
5
        LOG_INFO(
4526
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4527
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4528
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4529
5
        concurrent_delete_executor.add([&]() -> int {
4530
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4531
5
            if (!ret) {
4532
5
                auto rs = rowsets.at(rowset_id);
4533
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4534
5
                metrics_context.total_recycled_num++;
4535
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4536
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4537
5
            }
4538
5
            return ret;
4539
5
        });
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
4529
5
        concurrent_delete_executor.add([&]() -> int {
4530
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4531
5
            if (!ret) {
4532
5
                auto rs = rowsets.at(rowset_id);
4533
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4534
5
                metrics_context.total_recycled_num++;
4535
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4536
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4537
5
            }
4538
5
            return ret;
4539
5
        });
4540
5
    }
4541
4542
94
    bool finished = true;
4543
94
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4544
94
    for (int r : rets) {
4545
60
        if (r != 0) {
4546
0
            ret = -1;
4547
0
            break;
4548
0
        }
4549
60
    }
4550
94
    ret = finished ? ret : -1;
4551
94
    return ret;
4552
94
}
4553
4554
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4555
3.57k
                                         const std::string& rowset_id) {
4556
3.57k
    auto it = accessor_map_.find(resource_id);
4557
3.57k
    if (it == accessor_map_.end()) {
4558
400
        LOG_WARNING("instance has no such resource id")
4559
400
                .tag("instance_id", instance_id_)
4560
400
                .tag("resource_id", resource_id)
4561
400
                .tag("tablet_id", tablet_id)
4562
400
                .tag("rowset_id", rowset_id);
4563
400
        return -1;
4564
400
    }
4565
3.17k
    auto& accessor = it->second;
4566
3.17k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4567
3.57k
}
4568
4569
55.5k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4570
55.5k
    std::lock_guard lock(recycled_tablets_mtx_);
4571
55.5k
    return recycled_tablets_.contains(tablet_id);
4572
55.5k
}
4573
4574
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4575
52.4k
                                                                int64_t tablet_id) {
4576
52.4k
    bool is_mow = true;
4577
52.4k
    if (partition_id != -1) {
4578
52.2k
        std::lock_guard lock(partition_mow_cache_mutex);
4579
52.2k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4580
            // cache hit
4581
1
            is_mow = it->second;
4582
1
            return is_mow ? 1 : 0;
4583
1
        }
4584
52.2k
    }
4585
4586
52.4k
    TabletIndexPB tablet_index;
4587
52.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4588
52.4k
    if (ret == 1) {
4589
        // maybe recycled
4590
52.4k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4591
52.4k
    }
4592
33
    if (ret != 0) {
4593
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4594
0
                     << ", tablet_id=" << tablet_id;
4595
0
        return ret;
4596
0
    }
4597
4598
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4599
    // obtaining its partition ID from the tablet index.
4600
33
    if (partition_id == -1) {
4601
0
        partition_id = tablet_index.partition_id();
4602
0
        std::lock_guard lock(partition_mow_cache_mutex);
4603
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4604
0
            is_mow = it->second;
4605
0
            return is_mow ? 1 : 0;
4606
0
        }
4607
0
    }
4608
4609
33
    std::string tablet_meta_key =
4610
33
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4611
33
                             partition_id, tablet_id});
4612
33
    std::string tablet_meta_value;
4613
33
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4614
33
    if (ret == 1) {
4615
        // maybe recycled
4616
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4617
10
    }
4618
23
    if (ret != 0) {
4619
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4620
0
                     << ", tablet_id=" << tablet_id;
4621
0
        return ret;
4622
0
    }
4623
4624
23
    TabletMetaCloudPB tablet_meta;
4625
23
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4626
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4627
0
                     << ", tablet_id=" << tablet_id;
4628
0
        return -1;
4629
0
    }
4630
23
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4631
23
    std::lock_guard lock(partition_mow_cache_mutex);
4632
23
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4633
23
    return it->second ? 1 : 0;
4634
23
}
4635
4636
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4637
52.4k
                                                         const std::string& rowset_id) {
4638
52.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4639
52.4k
    if (ret <= 0) {
4640
1.00k
        return ret;
4641
1.00k
    }
4642
4643
51.4k
    std::string dbm_start_key =
4644
51.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4645
51.4k
    std::string dbm_end_key = dbm_start_key;
4646
51.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4647
51.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4648
51.4k
    if (ret != 0) {
4649
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4650
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4651
0
                     << " rowset_id=" << rowset_id;
4652
0
    }
4653
51.4k
    return ret;
4654
52.4k
}
4655
4656
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4657
51.2k
    std::string delete_bitmap_start =
4658
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4659
51.2k
    std::string delete_bitmap_end =
4660
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4661
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4662
51.2k
    if (ret != 0) {
4663
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4664
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4665
0
    }
4666
51.2k
    return ret;
4667
51.2k
}
4668
4669
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4670
4
    if (key.empty()) {
4671
0
        return false;
4672
0
    }
4673
4
    std::string_view key_view = key;
4674
4
    key_view.remove_prefix(1); // remove keyspace prefix
4675
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4676
4
    if (decode_key(&key_view, &decoded) != 0) {
4677
0
        return false;
4678
0
    }
4679
4
    if (decoded.size() < 4) {
4680
0
        return false;
4681
0
    }
4682
4
    try {
4683
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4684
4
    } catch (const std::bad_variant_access&) {
4685
0
        return false;
4686
0
    }
4687
4
    return true;
4688
4
}
4689
4690
14
int InstanceRecycler::recycle_packed_files() {
4691
14
    const std::string task_name = "recycle_packed_files";
4692
14
    auto start_tp = steady_clock::now();
4693
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4694
14
    int ret = 0;
4695
14
    PackedFileRecycleStats stats;
4696
4697
14
    register_recycle_task(task_name, start_time);
4698
14
    DORIS_CLOUD_DEFER {
4699
14
        unregister_recycle_task(task_name);
4700
14
        int64_t cost =
4701
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4702
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4703
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4704
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4705
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4706
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4707
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4708
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4709
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4710
14
                                                             stats.bytes_object_deleted);
4711
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4712
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4713
14
                .tag("instance_id", instance_id_)
4714
14
                .tag("num_scanned", stats.num_scanned)
4715
14
                .tag("num_corrected", stats.num_corrected)
4716
14
                .tag("num_deleted", stats.num_deleted)
4717
14
                .tag("num_failed", stats.num_failed)
4718
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4719
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4720
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4721
14
                .tag("bytes_deleted", stats.bytes_deleted)
4722
14
                .tag("ret", ret);
4723
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4698
14
    DORIS_CLOUD_DEFER {
4699
14
        unregister_recycle_task(task_name);
4700
14
        int64_t cost =
4701
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4702
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4703
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4704
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4705
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4706
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4707
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4708
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4709
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4710
14
                                                             stats.bytes_object_deleted);
4711
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4712
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4713
14
                .tag("instance_id", instance_id_)
4714
14
                .tag("num_scanned", stats.num_scanned)
4715
14
                .tag("num_corrected", stats.num_corrected)
4716
14
                .tag("num_deleted", stats.num_deleted)
4717
14
                .tag("num_failed", stats.num_failed)
4718
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4719
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4720
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4721
14
                .tag("bytes_deleted", stats.bytes_deleted)
4722
14
                .tag("ret", ret);
4723
14
    };
4724
4725
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4726
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4727
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4728
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
4725
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4726
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4727
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4728
4
    };
4729
4730
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4731
4732
14
    std::string begin = packed_file_key({instance_id_, ""});
4733
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4734
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4735
0
        ret = -1;
4736
0
    }
4737
4738
14
    return ret;
4739
14
}
4740
4741
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4742
                                                  RecyclerMetricsContext& metrics_context,
4743
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4744
0
    std::string tablet_key_begin, tablet_key_end;
4745
4746
0
    if (partition_id > 0) {
4747
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4748
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4749
0
    } else {
4750
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4751
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4752
0
    }
4753
    // for calculate the total num or bytes of recyled objects
4754
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4755
0
                                                          std::string_view v) -> int {
4756
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4757
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4758
0
            return 0;
4759
0
        }
4760
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4761
4762
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4763
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4764
0
            return 0;
4765
0
        }
4766
4767
0
        if (!is_empty_tablet) {
4768
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4769
0
                return 0;
4770
0
            }
4771
0
            tablet_metrics_context_.total_need_recycle_num++;
4772
0
        }
4773
0
        return 0;
4774
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_
4775
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4776
0
    metrics_context.report(true);
4777
0
    tablet_metrics_context_.report(true);
4778
0
    segment_metrics_context_.report(true);
4779
0
    return ret;
4780
0
}
4781
4782
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4783
0
                                                 RecyclerMetricsContext& metrics_context) {
4784
0
    int ret = 0;
4785
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4786
0
    std::unique_ptr<Transaction> txn;
4787
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4788
0
        LOG_WARNING("failed to recycle tablet ")
4789
0
                .tag("tablet id", tablet_id)
4790
0
                .tag("instance_id", instance_id_)
4791
0
                .tag("reason", "failed to create txn");
4792
0
        ret = -1;
4793
0
    }
4794
0
    GetRowsetResponse resp;
4795
0
    std::string msg;
4796
0
    MetaServiceCode code = MetaServiceCode::OK;
4797
    // get rowsets in tablet
4798
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4799
0
                        tablet_id, code, msg, &resp);
4800
0
    if (code != MetaServiceCode::OK) {
4801
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4802
0
                .tag("tablet id", tablet_id)
4803
0
                .tag("msg", msg)
4804
0
                .tag("code", code)
4805
0
                .tag("instance id", instance_id_);
4806
0
        ret = -1;
4807
0
    }
4808
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4809
        /*
4810
        * For compatibility, we skip the loop for [0-1] here.
4811
        * The purpose of this loop is to delete object files,
4812
        * and since [0-1] only has meta and doesn't have object files,
4813
        * skipping it doesn't affect system correctness.
4814
        *
4815
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4816
        * would return error -1 directly, causing the recycle operation to fail.
4817
        *
4818
        * [0-1] doesn't have resource id is a bug.
4819
        * In the future, we will fix this problem, after that,
4820
        * we can remove this if statement.
4821
        *
4822
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4823
        */
4824
4825
0
        if (rs_meta.end_version() == 1) {
4826
            // Assert that [0-1] has no resource_id to make sure
4827
            // this if statement will not be forgetted to remove
4828
            // when the resource id bug is fixed
4829
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4830
0
            continue;
4831
0
        }
4832
0
        if (!rs_meta.has_resource_id()) {
4833
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4834
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4835
0
                    .tag("instance_id", instance_id_)
4836
0
                    .tag("tablet_id", tablet_id);
4837
0
            continue;
4838
0
        }
4839
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4840
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4841
        // possible if the accessor is not initilized correctly
4842
0
        if (it == accessor_map_.end()) [[unlikely]] {
4843
0
            LOG_WARNING(
4844
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4845
0
                    "recycle process")
4846
0
                    .tag("tablet id", tablet_id)
4847
0
                    .tag("instance_id", instance_id_)
4848
0
                    .tag("resource_id", rs_meta.resource_id())
4849
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4850
0
            continue;
4851
0
        }
4852
4853
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4854
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4855
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4856
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4857
0
    }
4858
0
    return ret;
4859
0
}
4860
4861
263
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4862
263
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4863
263
            .tag("instance_id", instance_id_)
4864
263
            .tag("tablet_id", tablet_id);
4865
4866
263
    if (should_recycle_versioned_keys()) {
4867
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4868
14
        if (ret != 0) {
4869
0
            return ret;
4870
0
        }
4871
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4872
        // during the recycle_versioned_tablet process.
4873
        //
4874
        // .. And remove restore job rowsets of this tablet too
4875
14
    }
4876
4877
263
    int ret = 0;
4878
263
    auto start_time = steady_clock::now();
4879
4880
263
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4881
4882
    // collect resource ids
4883
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4884
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4885
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4886
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4887
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4888
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4889
4890
260
    std::set<std::string> resource_ids;
4891
260
    int64_t recycle_rowsets_number = 0;
4892
260
    int64_t recycle_segments_number = 0;
4893
260
    int64_t recycle_rowsets_data_size = 0;
4894
260
    int64_t recycle_rowsets_index_size = 0;
4895
260
    int64_t recycle_restore_job_rowsets_number = 0;
4896
260
    int64_t recycle_restore_job_segments_number = 0;
4897
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
4898
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
4899
260
    int64_t max_rowset_version = 0;
4900
260
    int64_t min_rowset_creation_time = INT64_MAX;
4901
260
    int64_t max_rowset_creation_time = 0;
4902
260
    int64_t min_rowset_expiration_time = INT64_MAX;
4903
260
    int64_t max_rowset_expiration_time = 0;
4904
4905
260
    DORIS_CLOUD_DEFER {
4906
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4907
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4908
260
                .tag("instance_id", instance_id_)
4909
260
                .tag("tablet_id", tablet_id)
4910
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4911
260
                .tag("recycle segments number", recycle_segments_number)
4912
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4913
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4914
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4915
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4916
260
                .tag("all restore job rowsets recycle data size",
4917
260
                     recycle_restore_job_rowsets_data_size)
4918
260
                .tag("all restore job rowsets recycle index size",
4919
260
                     recycle_restore_job_rowsets_index_size)
4920
260
                .tag("max rowset version", max_rowset_version)
4921
260
                .tag("min rowset creation time", min_rowset_creation_time)
4922
260
                .tag("max rowset creation time", max_rowset_creation_time)
4923
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4924
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4925
260
                .tag("task type", metrics_context.operation_type)
4926
260
                .tag("ret", ret);
4927
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4905
260
    DORIS_CLOUD_DEFER {
4906
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4907
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4908
260
                .tag("instance_id", instance_id_)
4909
260
                .tag("tablet_id", tablet_id)
4910
260
                .tag("recycle rowsets number", recycle_rowsets_number)
4911
260
                .tag("recycle segments number", recycle_segments_number)
4912
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4913
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4914
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4915
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4916
260
                .tag("all restore job rowsets recycle data size",
4917
260
                     recycle_restore_job_rowsets_data_size)
4918
260
                .tag("all restore job rowsets recycle index size",
4919
260
                     recycle_restore_job_rowsets_index_size)
4920
260
                .tag("max rowset version", max_rowset_version)
4921
260
                .tag("min rowset creation time", min_rowset_creation_time)
4922
260
                .tag("max rowset creation time", max_rowset_creation_time)
4923
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
4924
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
4925
260
                .tag("task type", metrics_context.operation_type)
4926
260
                .tag("ret", ret);
4927
260
    };
4928
4929
260
    std::unique_ptr<Transaction> txn;
4930
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4931
0
        LOG_WARNING("failed to recycle tablet ")
4932
0
                .tag("tablet id", tablet_id)
4933
0
                .tag("instance_id", instance_id_)
4934
0
                .tag("reason", "failed to create txn");
4935
0
        ret = -1;
4936
0
    }
4937
260
    GetRowsetResponse resp;
4938
260
    std::string msg;
4939
260
    MetaServiceCode code = MetaServiceCode::OK;
4940
    // get rowsets in tablet
4941
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4942
260
                        tablet_id, code, msg, &resp);
4943
260
    if (code != MetaServiceCode::OK) {
4944
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4945
0
                .tag("tablet id", tablet_id)
4946
0
                .tag("msg", msg)
4947
0
                .tag("code", code)
4948
0
                .tag("instance id", instance_id_);
4949
0
        ret = -1;
4950
0
    }
4951
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4952
4953
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4954
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4955
3
            if (rs_meta.num_segments() <= 0) {
4956
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
4957
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
4958
2
                        .tag("instance_id", instance_id_)
4959
2
                        .tag("tablet_id", tablet_id);
4960
2
                recycle_rowsets_number += 1;
4961
2
                continue;
4962
2
            }
4963
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
4964
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
4965
1
                    .tag("instance_id", instance_id_)
4966
1
                    .tag("tablet_id", tablet_id);
4967
1
            return -1;
4968
3
        }
4969
18.4E
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
4970
18.4E
                << "rs_meta" << rs_meta.ShortDebugString();
4971
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
4972
        // possible if the accessor is not initilized correctly
4973
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
4974
1
            LOG_WARNING(
4975
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4976
1
                    "recycle process")
4977
1
                    .tag("tablet id", tablet_id)
4978
1
                    .tag("instance_id", instance_id_)
4979
1
                    .tag("resource_id", rs_meta.resource_id())
4980
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4981
1
            return -1;
4982
1
        }
4983
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
4984
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
4985
0
                    .tag("instance_id", instance_id_)
4986
0
                    .tag("tablet_id", tablet_id)
4987
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4988
0
            return -1;
4989
0
        }
4990
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
4991
2.54k
                                                           nullptr) != 0) {
4992
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4993
0
                    .tag("instance_id", instance_id_)
4994
0
                    .tag("tablet_id", tablet_id)
4995
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
4996
0
            return -1;
4997
0
        }
4998
2.54k
        recycle_rowsets_number += 1;
4999
2.54k
        recycle_segments_number += rs_meta.num_segments();
5000
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5001
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5002
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5003
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5004
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5005
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5006
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5007
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5008
2.54k
    }
5009
5010
    // get restore job rowset in tablet
5011
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5012
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5013
258
    if (code != MetaServiceCode::OK) {
5014
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5015
0
                .tag("tablet id", tablet_id)
5016
0
                .tag("msg", msg)
5017
0
                .tag("code", code)
5018
0
                .tag("instance id", instance_id_);
5019
0
        return -1;
5020
0
    }
5021
5022
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5023
0
        if (!rs_meta.has_resource_id()) {
5024
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5025
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5026
0
                    .tag("instance_id", instance_id_)
5027
0
                    .tag("tablet_id", tablet_id);
5028
0
            return -1;
5029
0
        }
5030
5031
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5032
        // possible if the accessor is not initilized correctly
5033
0
        if (it == accessor_map_.end()) [[unlikely]] {
5034
0
            LOG_WARNING(
5035
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5036
0
                    "recycle process")
5037
0
                    .tag("tablet id", tablet_id)
5038
0
                    .tag("instance_id", instance_id_)
5039
0
                    .tag("resource_id", rs_meta.resource_id())
5040
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5041
0
            return -1;
5042
0
        }
5043
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5044
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5045
0
                    .tag("instance_id", instance_id_)
5046
0
                    .tag("tablet_id", tablet_id)
5047
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5048
0
            return -1;
5049
0
        }
5050
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5051
0
                                                           nullptr) != 0) {
5052
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5053
0
                    .tag("instance_id", instance_id_)
5054
0
                    .tag("tablet_id", tablet_id)
5055
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5056
0
            return -1;
5057
0
        }
5058
0
        recycle_restore_job_rowsets_number += 1;
5059
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5060
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5061
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5062
0
        resource_ids.emplace(rs_meta.resource_id());
5063
0
    }
5064
5065
258
    LOG_INFO("recycle tablet start to delete object")
5066
258
            .tag("instance id", instance_id_)
5067
258
            .tag("tablet id", tablet_id)
5068
258
            .tag("recycle tablet resource ids are",
5069
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5070
258
                                 [](std::string rs_id, const auto& it) {
5071
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5072
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
5070
217
                                 [](std::string rs_id, const auto& it) {
5071
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5072
217
                                 }));
5073
5074
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5075
258
            _thread_pool_group.s3_producer_pool,
5076
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5077
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
5077
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5078
5079
    // delete all rowset data in this tablet
5080
    // ATTN: there may be data leak if not all accessor initilized successfully
5081
    //       partial data deleted if the tablet is stored cross-storage vault
5082
    //       vault id is not attached to TabletMeta...
5083
258
    for (const auto& resource_id : resource_ids) {
5084
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5085
217
        concurrent_delete_executor.add(
5086
217
                [&, rs_id = resource_id,
5087
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5088
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5089
217
                    if (res != 0) {
5090
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5091
3
                                     << " path=" << accessor_ptr->uri()
5092
3
                                     << " task type=" << metrics_context.operation_type;
5093
3
                        return std::make_pair(-1, rs_id);
5094
3
                    }
5095
214
                    return std::make_pair(0, rs_id);
5096
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5087
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5088
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5089
217
                    if (res != 0) {
5090
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5091
3
                                     << " path=" << accessor_ptr->uri()
5092
3
                                     << " task type=" << metrics_context.operation_type;
5093
3
                        return std::make_pair(-1, rs_id);
5094
3
                    }
5095
214
                    return std::make_pair(0, rs_id);
5096
217
                });
5097
217
    }
5098
5099
258
    bool finished = true;
5100
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5101
258
    for (auto& r : rets) {
5102
217
        if (r.first != 0) {
5103
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5104
3
            ret = -1;
5105
3
        }
5106
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5107
217
    }
5108
258
    ret = finished ? ret : -1;
5109
5110
258
    if (ret != 0) { // failed recycle tablet data
5111
3
        LOG_WARNING("ret!=0")
5112
3
                .tag("finished", finished)
5113
3
                .tag("ret", ret)
5114
3
                .tag("instance_id", instance_id_)
5115
3
                .tag("tablet_id", tablet_id);
5116
3
        return ret;
5117
3
    }
5118
5119
255
    tablet_metrics_context_.total_recycled_data_size +=
5120
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5121
255
    tablet_metrics_context_.total_recycled_num += 1;
5122
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5123
255
    segment_metrics_context_.total_recycled_data_size +=
5124
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5125
255
    metrics_context.total_recycled_data_size +=
5126
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5127
255
    tablet_metrics_context_.report();
5128
255
    segment_metrics_context_.report();
5129
255
    metrics_context.report();
5130
5131
255
    txn.reset();
5132
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5133
0
        LOG_WARNING("failed to recycle tablet ")
5134
0
                .tag("tablet id", tablet_id)
5135
0
                .tag("instance_id", instance_id_)
5136
0
                .tag("reason", "failed to create txn");
5137
0
        ret = -1;
5138
0
    }
5139
    // delete all rowset kv in this tablet
5140
255
    txn->remove(rs_key0, rs_key1);
5141
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5142
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5143
5144
    // remove delete bitmap for MoW table
5145
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5146
255
    txn->remove(pending_key);
5147
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5148
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5149
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5150
5151
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5152
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5153
255
    txn->remove(dbm_start_key, dbm_end_key);
5154
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5155
255
              << " end=" << hex(dbm_end_key);
5156
5157
255
    TxnErrorCode err = txn->commit();
5158
255
    if (err != TxnErrorCode::TXN_OK) {
5159
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5160
0
        ret = -1;
5161
0
    }
5162
5163
255
    if (ret == 0) {
5164
        // All object files under tablet have been deleted
5165
255
        std::lock_guard lock(recycled_tablets_mtx_);
5166
255
        recycled_tablets_.insert(tablet_id);
5167
255
    }
5168
5169
255
    return ret;
5170
258
}
5171
5172
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5173
14
                                               RecyclerMetricsContext& metrics_context) {
5174
14
    int ret = 0;
5175
14
    auto start_time = steady_clock::now();
5176
5177
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5178
5179
    // collect resource ids
5180
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5181
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5182
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5183
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5184
5185
11
    int64_t recycle_rowsets_number = 0;
5186
11
    int64_t recycle_segments_number = 0;
5187
11
    int64_t recycle_rowsets_data_size = 0;
5188
11
    int64_t recycle_rowsets_index_size = 0;
5189
11
    int64_t max_rowset_version = 0;
5190
11
    int64_t min_rowset_creation_time = INT64_MAX;
5191
11
    int64_t max_rowset_creation_time = 0;
5192
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5193
11
    int64_t max_rowset_expiration_time = 0;
5194
5195
11
    DORIS_CLOUD_DEFER {
5196
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5197
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5198
11
                .tag("instance_id", instance_id_)
5199
11
                .tag("tablet_id", tablet_id)
5200
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5201
11
                .tag("recycle segments number", recycle_segments_number)
5202
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5203
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5204
11
                .tag("max rowset version", max_rowset_version)
5205
11
                .tag("min rowset creation time", min_rowset_creation_time)
5206
11
                .tag("max rowset creation time", max_rowset_creation_time)
5207
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5208
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5209
11
                .tag("ret", ret);
5210
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5195
11
    DORIS_CLOUD_DEFER {
5196
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5197
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5198
11
                .tag("instance_id", instance_id_)
5199
11
                .tag("tablet_id", tablet_id)
5200
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5201
11
                .tag("recycle segments number", recycle_segments_number)
5202
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5203
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5204
11
                .tag("max rowset version", max_rowset_version)
5205
11
                .tag("min rowset creation time", min_rowset_creation_time)
5206
11
                .tag("max rowset creation time", max_rowset_creation_time)
5207
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5208
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5209
11
                .tag("ret", ret);
5210
11
    };
5211
5212
11
    std::unique_ptr<Transaction> txn;
5213
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5214
0
        LOG_WARNING("failed to recycle tablet ")
5215
0
                .tag("tablet id", tablet_id)
5216
0
                .tag("instance_id", instance_id_)
5217
0
                .tag("reason", "failed to create txn");
5218
0
        ret = -1;
5219
0
    }
5220
5221
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5222
    // by the related operation logs.
5223
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5224
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5225
11
    MetaReader meta_reader(instance_id_);
5226
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5227
11
    if (err == TxnErrorCode::TXN_OK) {
5228
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5229
11
    }
5230
11
    if (err != TxnErrorCode::TXN_OK) {
5231
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5232
0
                .tag("tablet id", tablet_id)
5233
0
                .tag("err", err)
5234
0
                .tag("instance id", instance_id_);
5235
0
        ret = -1;
5236
0
    }
5237
5238
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5239
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5240
11
            .tag("instance_id", instance_id_)
5241
11
            .tag("tablet_id", tablet_id);
5242
5243
11
    SyncExecutor<int> concurrent_delete_executor(
5244
11
            _thread_pool_group.s3_producer_pool,
5245
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5246
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
5247
5248
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5249
60
        recycle_rowsets_number += 1;
5250
60
        recycle_segments_number += rs_meta.num_segments();
5251
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5252
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5253
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5254
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5255
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5256
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5257
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5258
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5248
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5249
60
        recycle_rowsets_number += 1;
5250
60
        recycle_segments_number += rs_meta.num_segments();
5251
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5252
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5253
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5254
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5255
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5256
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5257
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5258
60
    };
5259
5260
11
    std::vector<RowsetDeleteTask> all_tasks;
5261
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5262
60
        update_rowset_stats(rs_meta);
5263
        // Version 0-1 rowset has no resource_id and no actual data files,
5264
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5265
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5266
60
        RowsetDeleteTask task;
5267
60
        task.rowset_meta = rs_meta;
5268
60
        task.versioned_rowset_key =
5269
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5270
60
        task.non_versioned_rowset_key =
5271
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5272
60
        task.versionstamp = versionstamp;
5273
60
        all_tasks.push_back(std::move(task));
5274
60
    }
5275
5276
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5277
0
        update_rowset_stats(rs_meta);
5278
        // Version 0-1 rowset has no resource_id and no actual data files,
5279
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5280
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5281
0
        RowsetDeleteTask task;
5282
0
        task.rowset_meta = rs_meta;
5283
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5284
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5285
0
        task.non_versioned_rowset_key =
5286
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5287
0
        task.versionstamp = versionstamp;
5288
0
        all_tasks.push_back(std::move(task));
5289
0
    }
5290
5291
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5292
0
        RecycleRowsetPB recycle_rowset;
5293
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5294
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5295
0
            return -1;
5296
0
        }
5297
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5298
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5299
                // in old version, keep this key-value pair and it needs to be checked manually
5300
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5301
0
                return -1;
5302
0
            }
5303
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5304
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5305
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5306
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5307
0
                return -1;
5308
0
            }
5309
            // decode rowset_id
5310
0
            auto k1 = k;
5311
0
            k1.remove_prefix(1);
5312
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5313
0
            decode_key(&k1, &out);
5314
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5315
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5316
0
            LOG_INFO("delete old-version rowset data")
5317
0
                    .tag("instance_id", instance_id_)
5318
0
                    .tag("tablet_id", tablet_id)
5319
0
                    .tag("rowset_id", rowset_id);
5320
5321
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5322
            // so we must use prefix deletion directly instead of batch delete.
5323
0
            concurrent_delete_executor.add(
5324
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5325
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5326
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5327
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
5328
0
        } else {
5329
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5330
            // Version 0-1 rowset has no resource_id and no actual data files,
5331
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5332
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5333
0
            RowsetDeleteTask task;
5334
0
            task.rowset_meta = rowset_meta;
5335
0
            task.recycle_rowset_key = k;
5336
0
            all_tasks.push_back(std::move(task));
5337
0
        }
5338
0
        return 0;
5339
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_
5340
5341
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5342
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5343
0
                .tag("tablet id", tablet_id)
5344
0
                .tag("instance_id", instance_id_)
5345
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5346
0
        ret = -1;
5347
0
    }
5348
5349
    // Phase 1: Classify tasks by ref_count
5350
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5351
60
    for (auto& task : all_tasks) {
5352
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5353
60
        if (classify_ret < 0) {
5354
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5355
0
                    .tag("instance_id", instance_id_)
5356
0
                    .tag("tablet_id", tablet_id)
5357
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5358
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5359
0
                return recycle_rowset_meta_and_data(t);
5360
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5361
0
        }
5362
60
    }
5363
5364
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5365
5366
11
    LOG_INFO("batch delete plan created")
5367
11
            .tag("instance_id", instance_id_)
5368
11
            .tag("tablet_id", tablet_id)
5369
11
            .tag("plan_count", batch_delete_tasks.size());
5370
5371
    // Phase 2: Execute batch delete using existing delete_rowset_data
5372
11
    if (!batch_delete_tasks.empty()) {
5373
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5374
49
        for (const auto& task : batch_delete_tasks) {
5375
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5376
49
            if (task.rowset_meta.resource_id().empty()) {
5377
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5378
10
                        .tag("instance_id", instance_id_)
5379
10
                        .tag("tablet_id", tablet_id)
5380
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5381
10
                continue;
5382
10
            }
5383
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5384
39
        }
5385
5386
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5387
10
        bool delete_success = true;
5388
10
        if (!rowsets_to_delete.empty()) {
5389
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5390
9
                                                         "batch_delete_versioned_tablet");
5391
9
            int delete_ret = delete_rowset_data(
5392
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5393
9
            if (delete_ret != 0) {
5394
0
                LOG_WARNING("batch delete execution failed")
5395
0
                        .tag("instance_id", instance_id_)
5396
0
                        .tag("tablet_id", tablet_id);
5397
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5398
0
                ret = -1;
5399
0
                delete_success = false;
5400
0
            }
5401
9
        }
5402
5403
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5404
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5405
10
        if (delete_success) {
5406
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5407
10
            if (cleanup_ret != 0) {
5408
0
                LOG_WARNING("batch delete cleanup failed")
5409
0
                        .tag("instance_id", instance_id_)
5410
0
                        .tag("tablet_id", tablet_id);
5411
0
                ret = -1;
5412
0
            }
5413
10
        }
5414
10
    }
5415
5416
    // Always wait for fallback tasks to complete before returning
5417
11
    bool finished = true;
5418
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5419
11
    for (int r : rets) {
5420
0
        if (r != 0) {
5421
0
            ret = -1;
5422
0
        }
5423
0
    }
5424
5425
11
    ret = finished ? ret : -1;
5426
5427
11
    if (ret != 0) { // failed recycle tablet data
5428
0
        LOG_WARNING("recycle versioned tablet failed")
5429
0
                .tag("finished", finished)
5430
0
                .tag("ret", ret)
5431
0
                .tag("instance_id", instance_id_)
5432
0
                .tag("tablet_id", tablet_id);
5433
0
        return ret;
5434
0
    }
5435
5436
11
    tablet_metrics_context_.total_recycled_data_size +=
5437
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5438
11
    tablet_metrics_context_.total_recycled_num += 1;
5439
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5440
11
    segment_metrics_context_.total_recycled_data_size +=
5441
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5442
11
    metrics_context.total_recycled_data_size +=
5443
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5444
11
    tablet_metrics_context_.report();
5445
11
    segment_metrics_context_.report();
5446
11
    metrics_context.report();
5447
5448
11
    txn.reset();
5449
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5450
0
        LOG_WARNING("failed to recycle tablet ")
5451
0
                .tag("tablet id", tablet_id)
5452
0
                .tag("instance_id", instance_id_)
5453
0
                .tag("reason", "failed to create txn");
5454
0
        ret = -1;
5455
0
    }
5456
    // delete all rowset kv in this tablet
5457
11
    txn->remove(rs_key0, rs_key1);
5458
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5459
5460
    // remove delete bitmap for MoW table
5461
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5462
11
    txn->remove(pending_key);
5463
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5464
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5465
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5466
5467
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5468
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5469
11
    txn->remove(dbm_start_key, dbm_end_key);
5470
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5471
11
              << " end=" << hex(dbm_end_key);
5472
5473
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5474
11
    std::string tablet_index_val;
5475
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5476
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5477
0
        LOG_WARNING("failed to get tablet index kv")
5478
0
                .tag("instance_id", instance_id_)
5479
0
                .tag("tablet_id", tablet_id)
5480
0
                .tag("err", err);
5481
0
        ret = -1;
5482
11
    } else if (err == TxnErrorCode::TXN_OK) {
5483
        // If the tablet index kv exists, we need to delete it
5484
10
        TabletIndexPB tablet_index_pb;
5485
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5486
0
            LOG_WARNING("failed to parse tablet index pb")
5487
0
                    .tag("instance_id", instance_id_)
5488
0
                    .tag("tablet_id", tablet_id);
5489
0
            ret = -1;
5490
10
        } else {
5491
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5492
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5493
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5494
10
            txn->remove(versioned_inverted_idx_key);
5495
10
            txn->remove(versioned_idx_key);
5496
10
        }
5497
10
    }
5498
5499
11
    err = txn->commit();
5500
11
    if (err != TxnErrorCode::TXN_OK) {
5501
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5502
0
        ret = -1;
5503
0
    }
5504
5505
11
    if (ret == 0) {
5506
        // All object files under tablet have been deleted
5507
11
        std::lock_guard lock(recycled_tablets_mtx_);
5508
11
        recycled_tablets_.insert(tablet_id);
5509
11
    }
5510
5511
11
    return ret;
5512
11
}
5513
5514
47
int InstanceRecycler::recycle_rowsets() {
5515
47
    if (should_recycle_versioned_keys()) {
5516
5
        return recycle_versioned_rowsets();
5517
5
    }
5518
5519
42
    const std::string task_name = "recycle_rowsets";
5520
42
    int64_t num_scanned = 0;
5521
42
    int64_t num_expired = 0;
5522
42
    int64_t num_prepare = 0;
5523
42
    int64_t num_compacted = 0;
5524
42
    int64_t num_empty_rowset = 0;
5525
42
    size_t total_rowset_key_size = 0;
5526
42
    size_t total_rowset_value_size = 0;
5527
42
    size_t expired_rowset_size = 0;
5528
42
    std::atomic_long num_recycled = 0;
5529
42
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5530
5531
42
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5532
42
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5533
42
    std::string recyc_rs_key0;
5534
42
    std::string recyc_rs_key1;
5535
42
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5536
42
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5537
5538
42
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5539
5540
42
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5541
42
    register_recycle_task(task_name, start_time);
5542
5543
42
    DORIS_CLOUD_DEFER {
5544
42
        unregister_recycle_task(task_name);
5545
42
        int64_t cost =
5546
42
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5547
42
        metrics_context.finish_report();
5548
42
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5549
42
                .tag("instance_id", instance_id_)
5550
42
                .tag("num_scanned", num_scanned)
5551
42
                .tag("num_expired", num_expired)
5552
42
                .tag("num_recycled", num_recycled)
5553
42
                .tag("num_recycled.prepare", num_prepare)
5554
42
                .tag("num_recycled.compacted", num_compacted)
5555
42
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5556
42
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5557
42
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5558
42
                .tag("expired_rowset_meta_size", expired_rowset_size);
5559
42
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5543
7
    DORIS_CLOUD_DEFER {
5544
7
        unregister_recycle_task(task_name);
5545
7
        int64_t cost =
5546
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5547
7
        metrics_context.finish_report();
5548
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5549
7
                .tag("instance_id", instance_id_)
5550
7
                .tag("num_scanned", num_scanned)
5551
7
                .tag("num_expired", num_expired)
5552
7
                .tag("num_recycled", num_recycled)
5553
7
                .tag("num_recycled.prepare", num_prepare)
5554
7
                .tag("num_recycled.compacted", num_compacted)
5555
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5556
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5557
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5558
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5559
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5543
35
    DORIS_CLOUD_DEFER {
5544
35
        unregister_recycle_task(task_name);
5545
35
        int64_t cost =
5546
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5547
35
        metrics_context.finish_report();
5548
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5549
35
                .tag("instance_id", instance_id_)
5550
35
                .tag("num_scanned", num_scanned)
5551
35
                .tag("num_expired", num_expired)
5552
35
                .tag("num_recycled", num_recycled)
5553
35
                .tag("num_recycled.prepare", num_prepare)
5554
35
                .tag("num_recycled.compacted", num_compacted)
5555
35
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5556
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5557
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5558
35
                .tag("expired_rowset_meta_size", expired_rowset_size);
5559
35
    };
5560
5561
42
    std::vector<std::string> rowset_keys;
5562
42
    std::vector<std::string> rowset_keys_to_mark_recycled;
5563
42
    std::vector<std::string> rowset_keys_to_abort_job;
5564
    // rowset_id -> rowset_meta
5565
    // store rowset id and meta for statistics rs size when delete
5566
42
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5567
5568
42
    std::mutex async_recycled_rowset_keys_mutex;
5569
42
    std::vector<std::string> async_recycled_rowset_keys;
5570
42
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5571
42
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5572
42
    worker_pool->start();
5573
42
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5574
42
                                            int64_t partition_id, int64_t tablet_id,
5575
903
                                            const std::string& rowset_id) {
5576
        // Try to delete rowset data in background thread
5577
903
        int ret = worker_pool->submit_with_timeout(
5578
903
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5579
732
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5580
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5581
0
                        return;
5582
0
                    }
5583
732
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5584
732
                        0) {
5585
0
                        return;
5586
0
                    }
5587
732
                    std::vector<std::string> keys;
5588
732
                    {
5589
732
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5590
732
                        async_recycled_rowset_keys.push_back(std::move(key));
5591
732
                        if (async_recycled_rowset_keys.size() > 100) {
5592
7
                            keys.swap(async_recycled_rowset_keys);
5593
7
                        }
5594
732
                    }
5595
732
                    if (keys.empty()) return;
5596
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5598
0
                                     << instance_id_;
5599
7
                    } else {
5600
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5601
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5602
7
                                           num_recycled, start_time);
5603
7
                    }
5604
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5578
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5579
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5580
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5581
0
                        return;
5582
0
                    }
5583
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5584
1
                        0) {
5585
0
                        return;
5586
0
                    }
5587
1
                    std::vector<std::string> keys;
5588
1
                    {
5589
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5590
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5591
1
                        if (async_recycled_rowset_keys.size() > 100) {
5592
0
                            keys.swap(async_recycled_rowset_keys);
5593
0
                        }
5594
1
                    }
5595
1
                    if (keys.empty()) return;
5596
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5598
0
                                     << instance_id_;
5599
0
                    } else {
5600
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5601
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5602
0
                                           num_recycled, start_time);
5603
0
                    }
5604
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5578
731
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5579
731
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5580
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5581
0
                        return;
5582
0
                    }
5583
731
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5584
731
                        0) {
5585
0
                        return;
5586
0
                    }
5587
731
                    std::vector<std::string> keys;
5588
731
                    {
5589
731
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5590
731
                        async_recycled_rowset_keys.push_back(std::move(key));
5591
731
                        if (async_recycled_rowset_keys.size() > 100) {
5592
7
                            keys.swap(async_recycled_rowset_keys);
5593
7
                        }
5594
731
                    }
5595
731
                    if (keys.empty()) return;
5596
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5598
0
                                     << instance_id_;
5599
7
                    } else {
5600
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5601
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5602
7
                                           num_recycled, start_time);
5603
7
                    }
5604
7
                },
5605
903
                0);
5606
903
        if (ret == 0) return 0;
5607
        // Submit task failed, delete rowset data in current thread
5608
171
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5609
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5610
0
            return -1;
5611
0
        }
5612
171
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5613
0
            return -1;
5614
0
        }
5615
171
        rowset_keys.push_back(std::move(key));
5616
171
        return 0;
5617
171
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5575
1
                                            const std::string& rowset_id) {
5576
        // Try to delete rowset data in background thread
5577
1
        int ret = worker_pool->submit_with_timeout(
5578
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5579
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5580
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5581
1
                        return;
5582
1
                    }
5583
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5584
1
                        0) {
5585
1
                        return;
5586
1
                    }
5587
1
                    std::vector<std::string> keys;
5588
1
                    {
5589
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5590
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5591
1
                        if (async_recycled_rowset_keys.size() > 100) {
5592
1
                            keys.swap(async_recycled_rowset_keys);
5593
1
                        }
5594
1
                    }
5595
1
                    if (keys.empty()) return;
5596
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5597
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5598
1
                                     << instance_id_;
5599
1
                    } else {
5600
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5601
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5602
1
                                           num_recycled, start_time);
5603
1
                    }
5604
1
                },
5605
1
                0);
5606
1
        if (ret == 0) return 0;
5607
        // Submit task failed, delete rowset data in current thread
5608
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5609
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5610
0
            return -1;
5611
0
        }
5612
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5613
0
            return -1;
5614
0
        }
5615
0
        rowset_keys.push_back(std::move(key));
5616
0
        return 0;
5617
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5575
902
                                            const std::string& rowset_id) {
5576
        // Try to delete rowset data in background thread
5577
902
        int ret = worker_pool->submit_with_timeout(
5578
902
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5579
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5580
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5581
902
                        return;
5582
902
                    }
5583
902
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5584
902
                        0) {
5585
902
                        return;
5586
902
                    }
5587
902
                    std::vector<std::string> keys;
5588
902
                    {
5589
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5590
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5591
902
                        if (async_recycled_rowset_keys.size() > 100) {
5592
902
                            keys.swap(async_recycled_rowset_keys);
5593
902
                        }
5594
902
                    }
5595
902
                    if (keys.empty()) return;
5596
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5597
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5598
902
                                     << instance_id_;
5599
902
                    } else {
5600
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5601
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5602
902
                                           num_recycled, start_time);
5603
902
                    }
5604
902
                },
5605
902
                0);
5606
902
        if (ret == 0) return 0;
5607
        // Submit task failed, delete rowset data in current thread
5608
171
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5609
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5610
0
            return -1;
5611
0
        }
5612
171
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5613
0
            return -1;
5614
0
        }
5615
171
        rowset_keys.push_back(std::move(key));
5616
171
        return 0;
5617
171
    };
5618
5619
42
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5620
5621
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5622
4.28k
        ++num_scanned;
5623
4.28k
        total_rowset_key_size += k.size();
5624
4.28k
        total_rowset_value_size += v.size();
5625
4.28k
        RecycleRowsetPB rowset;
5626
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5627
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5628
0
            return -1;
5629
0
        }
5630
5631
4.28k
        int64_t current_time = ::time(nullptr);
5632
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5633
5634
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5635
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5636
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5637
4.28k
        if (current_time < expiration) { // not expired
5638
0
            return 0;
5639
0
        }
5640
4.28k
        ++num_expired;
5641
4.28k
        expired_rowset_size += v.size();
5642
5643
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5644
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5645
                // in old version, keep this key-value pair and it needs to be checked manually
5646
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5647
0
                return -1;
5648
0
            }
5649
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5650
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5651
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5652
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5653
0
                rowset_keys.emplace_back(k);
5654
0
                return -1;
5655
0
            }
5656
            // decode rowset_id
5657
250
            auto k1 = k;
5658
250
            k1.remove_prefix(1);
5659
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5660
250
            decode_key(&k1, &out);
5661
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5662
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5663
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5664
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5665
250
                      << " task_type=" << metrics_context.operation_type;
5666
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5667
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5668
0
                return -1;
5669
0
            }
5670
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5671
250
            metrics_context.total_recycled_num++;
5672
250
            segment_metrics_context_.total_recycled_data_size +=
5673
250
                    rowset.rowset_meta().total_disk_size();
5674
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5675
250
            return 0;
5676
250
        }
5677
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5678
5679
        // TODO(plat1ko): check rowset not referenced
5680
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5681
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5682
0
                LOG_INFO("recycle rowset that has empty resource id");
5683
0
            } else {
5684
                // other situations, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
0
        }
5689
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5690
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5691
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5692
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5693
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5694
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5695
4.03k
                  << " rowset_meta_size=" << v.size()
5696
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5697
4.03k
                  << " task_type=" << metrics_context.operation_type;
5698
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5699
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5700
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5701
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5702
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5703
13
                                 "kv "
5704
13
                                 "at next turn, instance_id="
5705
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5706
13
                              << " version=[" << rowset_meta->start_version() << '-'
5707
13
                              << rowset_meta->end_version() << "]";
5708
13
                    return 0;
5709
13
                }
5710
23
            }
5711
5712
925
            num_prepare += 1;
5713
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5714
925
                rowset_meta->end_version() != 1) {
5715
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5716
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5717
272
                                 "instance_id="
5718
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5719
272
                              << " version=[" << rowset_meta->start_version() << '-'
5720
272
                              << rowset_meta->end_version() << "]";
5721
272
                    rowset_keys_to_abort_job.emplace_back(k);
5722
272
                    return 0;
5723
272
                }
5724
273
            }
5725
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5726
653
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5727
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5728
0
                return -1;
5729
0
            }
5730
3.10k
        } else {
5731
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5732
3.10k
            rowset_keys.emplace_back(k);
5733
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5734
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5735
3.10k
                ++num_empty_rowset;
5736
3.10k
            }
5737
3.10k
        }
5738
3.75k
        return 0;
5739
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5621
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5622
7
        ++num_scanned;
5623
7
        total_rowset_key_size += k.size();
5624
7
        total_rowset_value_size += v.size();
5625
7
        RecycleRowsetPB rowset;
5626
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5627
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5628
0
            return -1;
5629
0
        }
5630
5631
7
        int64_t current_time = ::time(nullptr);
5632
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5633
5634
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5635
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5636
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5637
7
        if (current_time < expiration) { // not expired
5638
0
            return 0;
5639
0
        }
5640
7
        ++num_expired;
5641
7
        expired_rowset_size += v.size();
5642
5643
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5644
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5645
                // in old version, keep this key-value pair and it needs to be checked manually
5646
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5647
0
                return -1;
5648
0
            }
5649
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5650
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5651
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5652
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5653
0
                rowset_keys.emplace_back(k);
5654
0
                return -1;
5655
0
            }
5656
            // decode rowset_id
5657
0
            auto k1 = k;
5658
0
            k1.remove_prefix(1);
5659
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5660
0
            decode_key(&k1, &out);
5661
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5662
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5663
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5664
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5665
0
                      << " task_type=" << metrics_context.operation_type;
5666
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5667
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5668
0
                return -1;
5669
0
            }
5670
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5671
0
            metrics_context.total_recycled_num++;
5672
0
            segment_metrics_context_.total_recycled_data_size +=
5673
0
                    rowset.rowset_meta().total_disk_size();
5674
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5675
0
            return 0;
5676
0
        }
5677
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5678
5679
        // TODO(plat1ko): check rowset not referenced
5680
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5681
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5682
0
                LOG_INFO("recycle rowset that has empty resource id");
5683
0
            } else {
5684
                // other situations, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
0
        }
5689
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5690
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5691
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5692
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5693
7
                  << "] txn_id=" << rowset_meta->txn_id()
5694
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5695
7
                  << " rowset_meta_size=" << v.size()
5696
7
                  << " creation_time=" << rowset_meta->creation_time()
5697
7
                  << " task_type=" << metrics_context.operation_type;
5698
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5699
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5700
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5701
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5702
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5703
4
                                 "kv "
5704
4
                                 "at next turn, instance_id="
5705
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5706
4
                              << " version=[" << rowset_meta->start_version() << '-'
5707
4
                              << rowset_meta->end_version() << "]";
5708
4
                    return 0;
5709
4
                }
5710
6
            }
5711
5712
3
            num_prepare += 1;
5713
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5714
3
                rowset_meta->end_version() != 1) {
5715
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5716
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5717
2
                                 "instance_id="
5718
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5719
2
                              << " version=[" << rowset_meta->start_version() << '-'
5720
2
                              << rowset_meta->end_version() << "]";
5721
2
                    rowset_keys_to_abort_job.emplace_back(k);
5722
2
                    return 0;
5723
2
                }
5724
2
            }
5725
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5726
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5727
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5728
0
                return -1;
5729
0
            }
5730
1
        } else {
5731
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5732
0
            rowset_keys.emplace_back(k);
5733
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5734
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5735
0
                ++num_empty_rowset;
5736
0
            }
5737
0
        }
5738
1
        return 0;
5739
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5621
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5622
4.28k
        ++num_scanned;
5623
4.28k
        total_rowset_key_size += k.size();
5624
4.28k
        total_rowset_value_size += v.size();
5625
4.28k
        RecycleRowsetPB rowset;
5626
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5627
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5628
0
            return -1;
5629
0
        }
5630
5631
4.28k
        int64_t current_time = ::time(nullptr);
5632
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5633
5634
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5635
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5636
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5637
4.28k
        if (current_time < expiration) { // not expired
5638
0
            return 0;
5639
0
        }
5640
4.28k
        ++num_expired;
5641
4.28k
        expired_rowset_size += v.size();
5642
5643
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5644
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5645
                // in old version, keep this key-value pair and it needs to be checked manually
5646
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5647
0
                return -1;
5648
0
            }
5649
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5650
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5651
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5652
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5653
0
                rowset_keys.emplace_back(k);
5654
0
                return -1;
5655
0
            }
5656
            // decode rowset_id
5657
250
            auto k1 = k;
5658
250
            k1.remove_prefix(1);
5659
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5660
250
            decode_key(&k1, &out);
5661
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5662
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5663
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5664
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5665
250
                      << " task_type=" << metrics_context.operation_type;
5666
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5667
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5668
0
                return -1;
5669
0
            }
5670
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5671
250
            metrics_context.total_recycled_num++;
5672
250
            segment_metrics_context_.total_recycled_data_size +=
5673
250
                    rowset.rowset_meta().total_disk_size();
5674
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5675
250
            return 0;
5676
250
        }
5677
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5678
5679
        // TODO(plat1ko): check rowset not referenced
5680
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5681
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5682
0
                LOG_INFO("recycle rowset that has empty resource id");
5683
0
            } else {
5684
                // other situations, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
0
        }
5689
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5690
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5691
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5692
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5693
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5694
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5695
4.03k
                  << " rowset_meta_size=" << v.size()
5696
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5697
4.03k
                  << " task_type=" << metrics_context.operation_type;
5698
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5699
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5700
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5701
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5702
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5703
9
                                 "kv "
5704
9
                                 "at next turn, instance_id="
5705
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5706
9
                              << " version=[" << rowset_meta->start_version() << '-'
5707
9
                              << rowset_meta->end_version() << "]";
5708
9
                    return 0;
5709
9
                }
5710
17
            }
5711
5712
922
            num_prepare += 1;
5713
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5714
922
                rowset_meta->end_version() != 1) {
5715
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5716
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5717
270
                                 "instance_id="
5718
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5719
270
                              << " version=[" << rowset_meta->start_version() << '-'
5720
270
                              << rowset_meta->end_version() << "]";
5721
270
                    rowset_keys_to_abort_job.emplace_back(k);
5722
270
                    return 0;
5723
270
                }
5724
271
            }
5725
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5726
652
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5727
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5728
0
                return -1;
5729
0
            }
5730
3.10k
        } else {
5731
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5732
3.10k
            rowset_keys.emplace_back(k);
5733
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5734
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5735
3.10k
                ++num_empty_rowset;
5736
3.10k
            }
5737
3.10k
        }
5738
3.75k
        return 0;
5739
4.03k
    };
5740
5741
48
    auto loop_done = [&]() -> int {
5742
48
        std::vector<std::string> rowset_keys_to_delete;
5743
        // rowset_id -> rowset_meta
5744
        // store rowset id and meta for statistics rs size when delete
5745
48
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5746
48
        std::vector<std::string> mark_keys_to_process;
5747
48
        std::vector<std::string> abort_job_keys_to_process;
5748
48
        rowset_keys_to_delete.swap(rowset_keys);
5749
48
        rowsets_to_delete.swap(rowsets);
5750
48
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5751
48
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5752
48
        if (!mark_keys_to_process.empty()) {
5753
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5754
11
                    *worker_pool, std::move(mark_keys_to_process));
5755
11
        }
5756
48
        if (!abort_job_keys_to_process.empty()) {
5757
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5758
15
                                               &num_recycled);
5759
15
        }
5760
48
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5761
48
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5762
48
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5763
48
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5764
48
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5765
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5766
0
                return;
5767
0
            }
5768
48
            if (!versioned_delete_bitmap_key_groups.empty() &&
5769
48
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5770
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
5771
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5772
0
                             << instance_id_;
5773
0
                return;
5774
0
            }
5775
48
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5776
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5777
0
                return;
5778
0
            }
5779
48
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5780
48
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5761
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5762
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5763
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5764
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5765
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5766
0
                return;
5767
0
            }
5768
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5769
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5770
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
5771
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5772
0
                             << instance_id_;
5773
0
                return;
5774
0
            }
5775
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5776
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5777
0
                return;
5778
0
            }
5779
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5780
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5761
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5762
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5763
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5764
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5765
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5766
0
                return;
5767
0
            }
5768
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5769
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5770
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
5771
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5772
0
                             << instance_id_;
5773
0
                return;
5774
0
            }
5775
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5776
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5777
0
                return;
5778
0
            }
5779
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5780
41
        });
5781
48
        return 0;
5782
48
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5741
7
    auto loop_done = [&]() -> int {
5742
7
        std::vector<std::string> rowset_keys_to_delete;
5743
        // rowset_id -> rowset_meta
5744
        // store rowset id and meta for statistics rs size when delete
5745
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5746
7
        std::vector<std::string> mark_keys_to_process;
5747
7
        std::vector<std::string> abort_job_keys_to_process;
5748
7
        rowset_keys_to_delete.swap(rowset_keys);
5749
7
        rowsets_to_delete.swap(rowsets);
5750
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5751
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5752
7
        if (!mark_keys_to_process.empty()) {
5753
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5754
4
                    *worker_pool, std::move(mark_keys_to_process));
5755
4
        }
5756
7
        if (!abort_job_keys_to_process.empty()) {
5757
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5758
2
                                               &num_recycled);
5759
2
        }
5760
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5761
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5762
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5763
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5764
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5765
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5766
7
                return;
5767
7
            }
5768
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5769
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5770
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
5771
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5772
7
                             << instance_id_;
5773
7
                return;
5774
7
            }
5775
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5776
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5777
7
                return;
5778
7
            }
5779
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5780
7
        });
5781
7
        return 0;
5782
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5741
41
    auto loop_done = [&]() -> int {
5742
41
        std::vector<std::string> rowset_keys_to_delete;
5743
        // rowset_id -> rowset_meta
5744
        // store rowset id and meta for statistics rs size when delete
5745
41
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5746
41
        std::vector<std::string> mark_keys_to_process;
5747
41
        std::vector<std::string> abort_job_keys_to_process;
5748
41
        rowset_keys_to_delete.swap(rowset_keys);
5749
41
        rowsets_to_delete.swap(rowsets);
5750
41
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5751
41
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5752
41
        if (!mark_keys_to_process.empty()) {
5753
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5754
7
                    *worker_pool, std::move(mark_keys_to_process));
5755
7
        }
5756
41
        if (!abort_job_keys_to_process.empty()) {
5757
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5758
13
                                               &num_recycled);
5759
13
        }
5760
41
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5761
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5762
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5763
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5764
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5765
41
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5766
41
                return;
5767
41
            }
5768
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5769
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5770
41
                                                         versioned_delete_bitmap_key_groups) != 0) {
5771
41
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5772
41
                             << instance_id_;
5773
41
                return;
5774
41
            }
5775
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5776
41
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5777
41
                return;
5778
41
            }
5779
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5780
41
        });
5781
41
        return 0;
5782
41
    };
5783
5784
42
    if (config::enable_recycler_stats_metrics) {
5785
0
        scan_and_statistics_rowsets();
5786
0
    }
5787
    // recycle_func and loop_done for scan and recycle
5788
42
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5789
42
                               std::move(loop_done));
5790
5791
42
    worker_pool->stop();
5792
5793
42
    if (!async_recycled_rowset_keys.empty()) {
5794
4
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5795
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5796
0
            return -1;
5797
4
        } else {
5798
4
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5799
4
        }
5800
4
    }
5801
5802
    // Report final metrics after all concurrent tasks completed
5803
42
    segment_metrics_context_.report();
5804
42
    metrics_context.report();
5805
5806
42
    return ret;
5807
42
}
5808
5809
13
int InstanceRecycler::recycle_restore_jobs() {
5810
13
    const std::string task_name = "recycle_restore_jobs";
5811
13
    int64_t num_scanned = 0;
5812
13
    int64_t num_expired = 0;
5813
13
    int64_t num_recycled = 0;
5814
13
    int64_t num_aborted = 0;
5815
5816
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5817
5818
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5819
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5820
13
    std::string restore_job_key0;
5821
13
    std::string restore_job_key1;
5822
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5823
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5824
5825
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5826
5827
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5828
13
    register_recycle_task(task_name, start_time);
5829
5830
13
    DORIS_CLOUD_DEFER {
5831
13
        unregister_recycle_task(task_name);
5832
13
        int64_t cost =
5833
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5834
13
        metrics_context.finish_report();
5835
5836
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5837
13
                .tag("instance_id", instance_id_)
5838
13
                .tag("num_scanned", num_scanned)
5839
13
                .tag("num_expired", num_expired)
5840
13
                .tag("num_recycled", num_recycled)
5841
13
                .tag("num_aborted", num_aborted);
5842
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5830
13
    DORIS_CLOUD_DEFER {
5831
13
        unregister_recycle_task(task_name);
5832
13
        int64_t cost =
5833
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5834
13
        metrics_context.finish_report();
5835
5836
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5837
13
                .tag("instance_id", instance_id_)
5838
13
                .tag("num_scanned", num_scanned)
5839
13
                .tag("num_expired", num_expired)
5840
13
                .tag("num_recycled", num_recycled)
5841
13
                .tag("num_aborted", num_aborted);
5842
13
    };
5843
5844
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5845
5846
13
    std::vector<std::string_view> restore_job_keys;
5847
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5848
41
        ++num_scanned;
5849
41
        RestoreJobCloudPB restore_job_pb;
5850
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5851
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5852
0
            return -1;
5853
0
        }
5854
41
        int64_t expiration =
5855
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5856
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5857
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5858
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5859
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5860
0
                   << " state=" << restore_job_pb.state();
5861
41
        int64_t current_time = ::time(nullptr);
5862
41
        if (current_time < expiration) { // not expired
5863
0
            return 0;
5864
0
        }
5865
41
        ++num_expired;
5866
5867
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5868
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5869
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5870
5871
41
        std::unique_ptr<Transaction> txn;
5872
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5873
41
        if (err != TxnErrorCode::TXN_OK) {
5874
0
            LOG_WARNING("failed to recycle restore job")
5875
0
                    .tag("err", err)
5876
0
                    .tag("tablet id", tablet_id)
5877
0
                    .tag("instance_id", instance_id_)
5878
0
                    .tag("reason", "failed to create txn");
5879
0
            return -1;
5880
0
        }
5881
5882
41
        std::string val;
5883
41
        err = txn->get(k, &val);
5884
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5885
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5886
0
            return 0;
5887
0
        }
5888
41
        if (err != TxnErrorCode::TXN_OK) {
5889
0
            LOG_WARNING("failed to get kv");
5890
0
            return -1;
5891
0
        }
5892
41
        restore_job_pb.Clear();
5893
41
        if (!restore_job_pb.ParseFromString(val)) {
5894
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5895
0
            return -1;
5896
0
        }
5897
5898
        // PREPARED or COMMITTED, change state to DROPPED and return
5899
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5900
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5901
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5902
0
            restore_job_pb.set_need_recycle_data(true);
5903
0
            txn->put(k, restore_job_pb.SerializeAsString());
5904
0
            err = txn->commit();
5905
0
            if (err != TxnErrorCode::TXN_OK) {
5906
0
                LOG_WARNING("failed to commit txn: {}", err);
5907
0
                return -1;
5908
0
            }
5909
0
            num_aborted++;
5910
0
            return 0;
5911
0
        }
5912
5913
        // Change state to RECYCLING
5914
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5915
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5916
21
            txn->put(k, restore_job_pb.SerializeAsString());
5917
21
            err = txn->commit();
5918
21
            if (err != TxnErrorCode::TXN_OK) {
5919
0
                LOG_WARNING("failed to commit txn: {}", err);
5920
0
                return -1;
5921
0
            }
5922
21
            return 0;
5923
21
        }
5924
5925
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5926
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5927
5928
        // Recycle all data associated with the restore job.
5929
        // This includes rowsets, segments, and related resources.
5930
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5931
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5932
0
            LOG_WARNING("failed to recycle tablet")
5933
0
                    .tag("tablet_id", tablet_id)
5934
0
                    .tag("instance_id", instance_id_);
5935
0
            return -1;
5936
0
        }
5937
5938
        // delete all restore job rowset kv
5939
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5940
5941
20
        err = txn->commit();
5942
20
        if (err != TxnErrorCode::TXN_OK) {
5943
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5944
0
                    .tag("err", err)
5945
0
                    .tag("tablet id", tablet_id)
5946
0
                    .tag("instance_id", instance_id_)
5947
0
                    .tag("reason", "failed to commit txn");
5948
0
            return -1;
5949
0
        }
5950
5951
20
        metrics_context.total_recycled_num = ++num_recycled;
5952
20
        metrics_context.report();
5953
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5954
20
        restore_job_keys.push_back(k);
5955
5956
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5957
20
                  << " tablet_id=" << tablet_id;
5958
20
        return 0;
5959
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
5847
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5848
41
        ++num_scanned;
5849
41
        RestoreJobCloudPB restore_job_pb;
5850
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5851
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5852
0
            return -1;
5853
0
        }
5854
41
        int64_t expiration =
5855
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5856
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5857
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5858
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5859
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5860
0
                   << " state=" << restore_job_pb.state();
5861
41
        int64_t current_time = ::time(nullptr);
5862
41
        if (current_time < expiration) { // not expired
5863
0
            return 0;
5864
0
        }
5865
41
        ++num_expired;
5866
5867
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5868
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5869
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5870
5871
41
        std::unique_ptr<Transaction> txn;
5872
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5873
41
        if (err != TxnErrorCode::TXN_OK) {
5874
0
            LOG_WARNING("failed to recycle restore job")
5875
0
                    .tag("err", err)
5876
0
                    .tag("tablet id", tablet_id)
5877
0
                    .tag("instance_id", instance_id_)
5878
0
                    .tag("reason", "failed to create txn");
5879
0
            return -1;
5880
0
        }
5881
5882
41
        std::string val;
5883
41
        err = txn->get(k, &val);
5884
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5885
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5886
0
            return 0;
5887
0
        }
5888
41
        if (err != TxnErrorCode::TXN_OK) {
5889
0
            LOG_WARNING("failed to get kv");
5890
0
            return -1;
5891
0
        }
5892
41
        restore_job_pb.Clear();
5893
41
        if (!restore_job_pb.ParseFromString(val)) {
5894
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5895
0
            return -1;
5896
0
        }
5897
5898
        // PREPARED or COMMITTED, change state to DROPPED and return
5899
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5900
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5901
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5902
0
            restore_job_pb.set_need_recycle_data(true);
5903
0
            txn->put(k, restore_job_pb.SerializeAsString());
5904
0
            err = txn->commit();
5905
0
            if (err != TxnErrorCode::TXN_OK) {
5906
0
                LOG_WARNING("failed to commit txn: {}", err);
5907
0
                return -1;
5908
0
            }
5909
0
            num_aborted++;
5910
0
            return 0;
5911
0
        }
5912
5913
        // Change state to RECYCLING
5914
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5915
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5916
21
            txn->put(k, restore_job_pb.SerializeAsString());
5917
21
            err = txn->commit();
5918
21
            if (err != TxnErrorCode::TXN_OK) {
5919
0
                LOG_WARNING("failed to commit txn: {}", err);
5920
0
                return -1;
5921
0
            }
5922
21
            return 0;
5923
21
        }
5924
5925
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5926
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5927
5928
        // Recycle all data associated with the restore job.
5929
        // This includes rowsets, segments, and related resources.
5930
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5931
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5932
0
            LOG_WARNING("failed to recycle tablet")
5933
0
                    .tag("tablet_id", tablet_id)
5934
0
                    .tag("instance_id", instance_id_);
5935
0
            return -1;
5936
0
        }
5937
5938
        // delete all restore job rowset kv
5939
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5940
5941
20
        err = txn->commit();
5942
20
        if (err != TxnErrorCode::TXN_OK) {
5943
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5944
0
                    .tag("err", err)
5945
0
                    .tag("tablet id", tablet_id)
5946
0
                    .tag("instance_id", instance_id_)
5947
0
                    .tag("reason", "failed to commit txn");
5948
0
            return -1;
5949
0
        }
5950
5951
20
        metrics_context.total_recycled_num = ++num_recycled;
5952
20
        metrics_context.report();
5953
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5954
20
        restore_job_keys.push_back(k);
5955
5956
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5957
20
                  << " tablet_id=" << tablet_id;
5958
20
        return 0;
5959
20
    };
5960
5961
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5962
3
        if (restore_job_keys.empty()) return 0;
5963
1
        DORIS_CLOUD_DEFER {
5964
1
            restore_job_keys.clear();
5965
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5963
1
        DORIS_CLOUD_DEFER {
5964
1
            restore_job_keys.clear();
5965
1
        };
5966
5967
1
        std::unique_ptr<Transaction> txn;
5968
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5969
1
        if (err != TxnErrorCode::TXN_OK) {
5970
0
            LOG_WARNING("failed to recycle restore job")
5971
0
                    .tag("err", err)
5972
0
                    .tag("instance_id", instance_id_)
5973
0
                    .tag("reason", "failed to create txn");
5974
0
            return -1;
5975
0
        }
5976
20
        for (auto& k : restore_job_keys) {
5977
20
            txn->remove(k);
5978
20
        }
5979
1
        err = txn->commit();
5980
1
        if (err != TxnErrorCode::TXN_OK) {
5981
0
            LOG_WARNING("failed to recycle restore job")
5982
0
                    .tag("err", err)
5983
0
                    .tag("instance_id", instance_id_)
5984
0
                    .tag("reason", "failed to commit txn");
5985
0
            return -1;
5986
0
        }
5987
1
        return 0;
5988
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5961
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5962
3
        if (restore_job_keys.empty()) return 0;
5963
1
        DORIS_CLOUD_DEFER {
5964
1
            restore_job_keys.clear();
5965
1
        };
5966
5967
1
        std::unique_ptr<Transaction> txn;
5968
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5969
1
        if (err != TxnErrorCode::TXN_OK) {
5970
0
            LOG_WARNING("failed to recycle restore job")
5971
0
                    .tag("err", err)
5972
0
                    .tag("instance_id", instance_id_)
5973
0
                    .tag("reason", "failed to create txn");
5974
0
            return -1;
5975
0
        }
5976
20
        for (auto& k : restore_job_keys) {
5977
20
            txn->remove(k);
5978
20
        }
5979
1
        err = txn->commit();
5980
1
        if (err != TxnErrorCode::TXN_OK) {
5981
0
            LOG_WARNING("failed to recycle restore job")
5982
0
                    .tag("err", err)
5983
0
                    .tag("instance_id", instance_id_)
5984
0
                    .tag("reason", "failed to commit txn");
5985
0
            return -1;
5986
0
        }
5987
1
        return 0;
5988
1
    };
5989
5990
13
    if (config::enable_recycler_stats_metrics) {
5991
0
        scan_and_statistics_restore_jobs();
5992
0
    }
5993
5994
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
5995
13
                            std::move(loop_done));
5996
13
}
5997
5998
11
int InstanceRecycler::recycle_versioned_rowsets() {
5999
11
    const std::string task_name = "recycle_rowsets";
6000
11
    int64_t num_scanned = 0;
6001
11
    int64_t num_expired = 0;
6002
11
    int64_t num_prepare = 0;
6003
11
    int64_t num_compacted = 0;
6004
11
    int64_t num_empty_rowset = 0;
6005
11
    size_t total_rowset_key_size = 0;
6006
11
    size_t total_rowset_value_size = 0;
6007
11
    size_t expired_rowset_size = 0;
6008
11
    std::atomic_long num_recycled = 0;
6009
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6010
6011
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6012
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6013
11
    std::string recyc_rs_key0;
6014
11
    std::string recyc_rs_key1;
6015
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6016
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6017
6018
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6019
6020
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6021
11
    register_recycle_task(task_name, start_time);
6022
6023
11
    DORIS_CLOUD_DEFER {
6024
11
        unregister_recycle_task(task_name);
6025
11
        int64_t cost =
6026
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6027
11
        metrics_context.finish_report();
6028
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6029
11
                .tag("instance_id", instance_id_)
6030
11
                .tag("num_scanned", num_scanned)
6031
11
                .tag("num_expired", num_expired)
6032
11
                .tag("num_recycled", num_recycled)
6033
11
                .tag("num_recycled.prepare", num_prepare)
6034
11
                .tag("num_recycled.compacted", num_compacted)
6035
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6036
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6037
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6038
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6039
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6023
11
    DORIS_CLOUD_DEFER {
6024
11
        unregister_recycle_task(task_name);
6025
11
        int64_t cost =
6026
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6027
11
        metrics_context.finish_report();
6028
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6029
11
                .tag("instance_id", instance_id_)
6030
11
                .tag("num_scanned", num_scanned)
6031
11
                .tag("num_expired", num_expired)
6032
11
                .tag("num_recycled", num_recycled)
6033
11
                .tag("num_recycled.prepare", num_prepare)
6034
11
                .tag("num_recycled.compacted", num_compacted)
6035
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6036
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6037
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6038
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6039
11
    };
6040
6041
11
    std::vector<std::string> orphan_rowset_keys;
6042
6043
    // Store keys of rowset recycled by background workers
6044
11
    std::mutex async_recycled_rowset_keys_mutex;
6045
11
    std::vector<std::string> async_recycled_rowset_keys;
6046
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6047
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6048
11
    worker_pool->start();
6049
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6050
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6051
        // Try to delete rowset data in background thread
6052
400
        int ret = worker_pool->submit_with_timeout(
6053
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6054
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6055
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6056
400
                        return;
6057
400
                    }
6058
                    // The async recycled rowsets are staled format or has not been used,
6059
                    // so we don't need to check the rowset ref count key.
6060
0
                    std::vector<std::string> keys;
6061
0
                    {
6062
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6063
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6064
0
                        if (async_recycled_rowset_keys.size() > 100) {
6065
0
                            keys.swap(async_recycled_rowset_keys);
6066
0
                        }
6067
0
                    }
6068
0
                    if (keys.empty()) return;
6069
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6070
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6071
0
                                     << instance_id_;
6072
0
                    } else {
6073
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6074
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6075
0
                                           num_recycled, start_time);
6076
0
                    }
6077
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
6053
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6054
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6055
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6056
400
                        return;
6057
400
                    }
6058
                    // The async recycled rowsets are staled format or has not been used,
6059
                    // so we don't need to check the rowset ref count key.
6060
0
                    std::vector<std::string> keys;
6061
0
                    {
6062
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6063
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6064
0
                        if (async_recycled_rowset_keys.size() > 100) {
6065
0
                            keys.swap(async_recycled_rowset_keys);
6066
0
                        }
6067
0
                    }
6068
0
                    if (keys.empty()) return;
6069
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6070
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6071
0
                                     << instance_id_;
6072
0
                    } else {
6073
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6074
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6075
0
                                           num_recycled, start_time);
6076
0
                    }
6077
0
                },
6078
400
                0);
6079
400
        if (ret == 0) return 0;
6080
        // Submit task failed, delete rowset data in current thread
6081
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6082
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6083
0
            return -1;
6084
0
        }
6085
0
        orphan_rowset_keys.push_back(std::move(key));
6086
0
        return 0;
6087
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
6050
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6051
        // Try to delete rowset data in background thread
6052
400
        int ret = worker_pool->submit_with_timeout(
6053
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6054
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6055
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6056
400
                        return;
6057
400
                    }
6058
                    // The async recycled rowsets are staled format or has not been used,
6059
                    // so we don't need to check the rowset ref count key.
6060
400
                    std::vector<std::string> keys;
6061
400
                    {
6062
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6063
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6064
400
                        if (async_recycled_rowset_keys.size() > 100) {
6065
400
                            keys.swap(async_recycled_rowset_keys);
6066
400
                        }
6067
400
                    }
6068
400
                    if (keys.empty()) return;
6069
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6070
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6071
400
                                     << instance_id_;
6072
400
                    } else {
6073
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6074
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6075
400
                                           num_recycled, start_time);
6076
400
                    }
6077
400
                },
6078
400
                0);
6079
400
        if (ret == 0) return 0;
6080
        // Submit task failed, delete rowset data in current thread
6081
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6082
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6083
0
            return -1;
6084
0
        }
6085
0
        orphan_rowset_keys.push_back(std::move(key));
6086
0
        return 0;
6087
0
    };
6088
6089
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6090
6091
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6092
2.01k
        ++num_scanned;
6093
2.01k
        total_rowset_key_size += k.size();
6094
2.01k
        total_rowset_value_size += v.size();
6095
2.01k
        RecycleRowsetPB rowset;
6096
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6097
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6098
0
            return -1;
6099
0
        }
6100
6101
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6102
6103
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6104
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6105
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6106
2.01k
        int64_t current_time = ::time(nullptr);
6107
2.01k
        if (current_time < final_expiration) { // not expired
6108
0
            return 0;
6109
0
        }
6110
2.01k
        ++num_expired;
6111
2.01k
        expired_rowset_size += v.size();
6112
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6113
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6114
                // in old version, keep this key-value pair and it needs to be checked manually
6115
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6116
0
                return -1;
6117
0
            }
6118
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6119
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6120
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6121
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6122
0
                orphan_rowset_keys.emplace_back(k);
6123
0
                return -1;
6124
0
            }
6125
            // decode rowset_id
6126
0
            auto k1 = k;
6127
0
            k1.remove_prefix(1);
6128
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6129
0
            decode_key(&k1, &out);
6130
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6131
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6132
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6133
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6134
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6135
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6136
0
                return -1;
6137
0
            }
6138
0
            return 0;
6139
0
        }
6140
        // TODO(plat1ko): check rowset not referenced
6141
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6142
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6143
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6144
0
                LOG_INFO("recycle rowset that has empty resource id");
6145
0
            } else {
6146
                // other situations, keep this key-value pair and it needs to be checked manually
6147
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6148
0
                return -1;
6149
0
            }
6150
0
        }
6151
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6152
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6153
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6154
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6155
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6156
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6157
2.01k
                  << " rowset_meta_size=" << v.size()
6158
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6159
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6160
            // unable to calculate file path, can only be deleted by rowset id prefix
6161
400
            num_prepare += 1;
6162
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6163
400
                                             rowset_meta->tablet_id(),
6164
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6165
0
                return -1;
6166
0
            }
6167
1.61k
        } else {
6168
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6169
1.61k
            worker_pool->submit(
6170
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6171
                        // The load & compact rowset keys are recycled during recycling operation logs.
6172
1.61k
                        RowsetDeleteTask task;
6173
1.61k
                        task.rowset_meta = rowset_meta;
6174
1.61k
                        task.recycle_rowset_key = k;
6175
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6176
1.60k
                            return;
6177
1.60k
                        }
6178
13
                        num_compacted += is_compacted;
6179
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6180
13
                        if (rowset_meta.num_segments() == 0) {
6181
0
                            ++num_empty_rowset;
6182
0
                        }
6183
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
6170
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6171
                        // The load & compact rowset keys are recycled during recycling operation logs.
6172
1.61k
                        RowsetDeleteTask task;
6173
1.61k
                        task.rowset_meta = rowset_meta;
6174
1.61k
                        task.recycle_rowset_key = k;
6175
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6176
1.60k
                            return;
6177
1.60k
                        }
6178
13
                        num_compacted += is_compacted;
6179
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6180
13
                        if (rowset_meta.num_segments() == 0) {
6181
0
                            ++num_empty_rowset;
6182
0
                        }
6183
13
                    });
6184
1.61k
        }
6185
2.01k
        return 0;
6186
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
6091
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6092
2.01k
        ++num_scanned;
6093
2.01k
        total_rowset_key_size += k.size();
6094
2.01k
        total_rowset_value_size += v.size();
6095
2.01k
        RecycleRowsetPB rowset;
6096
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6097
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6098
0
            return -1;
6099
0
        }
6100
6101
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6102
6103
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6104
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6105
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6106
2.01k
        int64_t current_time = ::time(nullptr);
6107
2.01k
        if (current_time < final_expiration) { // not expired
6108
0
            return 0;
6109
0
        }
6110
2.01k
        ++num_expired;
6111
2.01k
        expired_rowset_size += v.size();
6112
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6113
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6114
                // in old version, keep this key-value pair and it needs to be checked manually
6115
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6116
0
                return -1;
6117
0
            }
6118
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6119
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6120
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6121
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6122
0
                orphan_rowset_keys.emplace_back(k);
6123
0
                return -1;
6124
0
            }
6125
            // decode rowset_id
6126
0
            auto k1 = k;
6127
0
            k1.remove_prefix(1);
6128
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6129
0
            decode_key(&k1, &out);
6130
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6131
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6132
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6133
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6134
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6135
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6136
0
                return -1;
6137
0
            }
6138
0
            return 0;
6139
0
        }
6140
        // TODO(plat1ko): check rowset not referenced
6141
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6142
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6143
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6144
0
                LOG_INFO("recycle rowset that has empty resource id");
6145
0
            } else {
6146
                // other situations, keep this key-value pair and it needs to be checked manually
6147
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6148
0
                return -1;
6149
0
            }
6150
0
        }
6151
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6152
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6153
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6154
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6155
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6156
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6157
2.01k
                  << " rowset_meta_size=" << v.size()
6158
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6159
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6160
            // unable to calculate file path, can only be deleted by rowset id prefix
6161
400
            num_prepare += 1;
6162
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6163
400
                                             rowset_meta->tablet_id(),
6164
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6165
0
                return -1;
6166
0
            }
6167
1.61k
        } else {
6168
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6169
1.61k
            worker_pool->submit(
6170
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6171
                        // The load & compact rowset keys are recycled during recycling operation logs.
6172
1.61k
                        RowsetDeleteTask task;
6173
1.61k
                        task.rowset_meta = rowset_meta;
6174
1.61k
                        task.recycle_rowset_key = k;
6175
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6176
1.61k
                            return;
6177
1.61k
                        }
6178
1.61k
                        num_compacted += is_compacted;
6179
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6180
1.61k
                        if (rowset_meta.num_segments() == 0) {
6181
1.61k
                            ++num_empty_rowset;
6182
1.61k
                        }
6183
1.61k
                    });
6184
1.61k
        }
6185
2.01k
        return 0;
6186
2.01k
    };
6187
6188
11
    if (config::enable_recycler_stats_metrics) {
6189
0
        scan_and_statistics_rowsets();
6190
0
    }
6191
6192
11
    auto loop_done = [&]() -> int {
6193
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6194
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6195
0
        }
6196
6
        orphan_rowset_keys.clear();
6197
6
        return 0;
6198
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6192
6
    auto loop_done = [&]() -> int {
6193
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6194
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6195
0
        }
6196
6
        orphan_rowset_keys.clear();
6197
6
        return 0;
6198
6
    };
6199
6200
    // recycle_func and loop_done for scan and recycle
6201
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6202
11
                               std::move(loop_done));
6203
6204
11
    worker_pool->stop();
6205
6206
11
    if (!async_recycled_rowset_keys.empty()) {
6207
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6208
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6209
0
            return -1;
6210
0
        } else {
6211
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6212
0
        }
6213
0
    }
6214
6215
    // Report final metrics after all concurrent tasks completed
6216
11
    segment_metrics_context_.report();
6217
11
    metrics_context.report();
6218
6219
11
    return ret;
6220
11
}
6221
6222
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6223
1.61k
    constexpr int MAX_RETRY = 10;
6224
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6225
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6226
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6227
1.61k
    std::string_view reference_instance_id = instance_id_;
6228
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6229
8
        reference_instance_id = rowset_meta.reference_instance_id();
6230
8
    }
6231
6232
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6233
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6234
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6235
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6236
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6237
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6238
1.61k
        std::unique_ptr<Transaction> txn;
6239
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6240
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6241
0
            LOG_WARNING("failed to create txn").tag("err", err);
6242
0
            return -1;
6243
0
        }
6244
6245
1.61k
        std::string rowset_ref_count_key =
6246
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6247
1.61k
        int64_t ref_count = 0;
6248
1.61k
        {
6249
1.61k
            std::string value;
6250
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6251
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6252
                // This is the old version rowset, we could recycle it directly.
6253
1.60k
                ref_count = 1;
6254
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6255
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6256
0
                return -1;
6257
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6258
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6259
0
                return -1;
6260
0
            }
6261
1.61k
        }
6262
6263
1.61k
        if (ref_count == 1) {
6264
            // It would not be added since it is recycling.
6265
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6266
1.60k
                LOG_WARNING("failed to delete rowset data");
6267
1.60k
                return -1;
6268
1.60k
            }
6269
6270
            // Reset the transaction to avoid timeout.
6271
10
            err = txn_kv_->create_txn(&txn);
6272
10
            if (err != TxnErrorCode::TXN_OK) {
6273
0
                LOG_WARNING("failed to create txn").tag("err", err);
6274
0
                return -1;
6275
0
            }
6276
10
            txn->remove(rowset_ref_count_key);
6277
10
            LOG_INFO("delete rowset data ref count key")
6278
10
                    .tag("txn_id", rowset_meta.txn_id())
6279
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6280
6281
10
            std::string dbm_start_key =
6282
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6283
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6284
10
                    {reference_instance_id, tablet_id, rowset_id,
6285
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6286
10
            txn->remove(dbm_start_key, dbm_end_key);
6287
10
            LOG_INFO("remove delete bitmap kv")
6288
10
                    .tag("begin", hex(dbm_start_key))
6289
10
                    .tag("end", hex(dbm_end_key));
6290
6291
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6292
10
                    {reference_instance_id, tablet_id, rowset_id});
6293
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6294
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6295
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6296
10
            LOG_INFO("remove versioned delete bitmap kv")
6297
10
                    .tag("begin", hex(versioned_dbm_start_key))
6298
10
                    .tag("end", hex(versioned_dbm_end_key));
6299
10
        } else {
6300
            // Decrease the rowset ref count.
6301
            //
6302
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6303
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6304
3
            txn->atomic_add(rowset_ref_count_key, -1);
6305
3
            LOG_INFO("decrease rowset data ref count")
6306
3
                    .tag("txn_id", rowset_meta.txn_id())
6307
3
                    .tag("ref_count", ref_count - 1)
6308
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6309
3
        }
6310
6311
13
        if (!task.versioned_rowset_key.empty()) {
6312
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6313
0
                                                          task.versionstamp);
6314
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6315
0
        }
6316
6317
13
        if (!task.non_versioned_rowset_key.empty()) {
6318
0
            txn->remove(task.non_versioned_rowset_key);
6319
0
            LOG_INFO("remove non versioned rowset key")
6320
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6321
0
        }
6322
6323
        // empty when recycle ref rowsets for deleted instance
6324
13
        if (!task.recycle_rowset_key.empty()) {
6325
13
            txn->remove(task.recycle_rowset_key);
6326
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6327
13
        }
6328
6329
13
        err = txn->commit();
6330
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6331
            // The rowset ref count key has been changed, we need to retry.
6332
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6333
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6334
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6335
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6336
0
            continue;
6337
13
        } else if (err != TxnErrorCode::TXN_OK) {
6338
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6339
0
            return -1;
6340
0
        }
6341
13
        LOG_INFO("recycle rowset meta and data success");
6342
13
        return 0;
6343
13
    }
6344
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6345
0
            .tag("tablet_id", tablet_id)
6346
0
            .tag("rowset_id", rowset_id)
6347
0
            .tag("retry", MAX_RETRY);
6348
0
    return -1;
6349
1.61k
}
6350
6351
37
int InstanceRecycler::recycle_tmp_rowsets() {
6352
37
    const std::string task_name = "recycle_tmp_rowsets";
6353
37
    int64_t num_scanned = 0;
6354
37
    int64_t num_expired = 0;
6355
37
    std::atomic_long num_recycled = 0;
6356
37
    size_t expired_rowset_size = 0;
6357
37
    size_t total_rowset_key_size = 0;
6358
37
    size_t total_rowset_value_size = 0;
6359
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6360
6361
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6362
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6363
37
    std::string tmp_rs_key0;
6364
37
    std::string tmp_rs_key1;
6365
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6366
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6367
6368
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6369
6370
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6371
37
    register_recycle_task(task_name, start_time);
6372
6373
37
    DORIS_CLOUD_DEFER {
6374
37
        unregister_recycle_task(task_name);
6375
37
        int64_t cost =
6376
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6377
37
        metrics_context.finish_report();
6378
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6379
37
                .tag("instance_id", instance_id_)
6380
37
                .tag("num_scanned", num_scanned)
6381
37
                .tag("num_expired", num_expired)
6382
37
                .tag("num_recycled", num_recycled)
6383
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6384
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6385
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6386
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6373
12
    DORIS_CLOUD_DEFER {
6374
12
        unregister_recycle_task(task_name);
6375
12
        int64_t cost =
6376
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6377
12
        metrics_context.finish_report();
6378
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6379
12
                .tag("instance_id", instance_id_)
6380
12
                .tag("num_scanned", num_scanned)
6381
12
                .tag("num_expired", num_expired)
6382
12
                .tag("num_recycled", num_recycled)
6383
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6384
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6385
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6386
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6373
25
    DORIS_CLOUD_DEFER {
6374
25
        unregister_recycle_task(task_name);
6375
25
        int64_t cost =
6376
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6377
25
        metrics_context.finish_report();
6378
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6379
25
                .tag("instance_id", instance_id_)
6380
25
                .tag("num_scanned", num_scanned)
6381
25
                .tag("num_expired", num_expired)
6382
25
                .tag("num_recycled", num_recycled)
6383
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6384
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6385
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6386
25
    };
6387
6388
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6389
37
    std::vector<std::string> tmp_rowset_keys;
6390
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6391
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6392
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6393
6394
    // rowset_id -> rowset_meta
6395
    // store tmp_rowset id and meta for statistics rs size when delete
6396
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6397
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6398
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6399
37
    worker_pool->start();
6400
6401
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6402
6403
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6404
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6405
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6406
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6407
53.2k
                                    std::string_view k, std::string_view v) -> int {
6408
53.2k
        ++num_scanned;
6409
53.2k
        total_rowset_key_size += k.size();
6410
53.2k
        total_rowset_value_size += v.size();
6411
53.2k
        doris::RowsetMetaCloudPB rowset;
6412
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6413
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6414
0
            return -1;
6415
0
        }
6416
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6417
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6418
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6419
0
                   << " txn_expiration=" << rowset.txn_expiration()
6420
0
                   << " rowset_creation_time=" << rowset.creation_time();
6421
53.2k
        int64_t current_time = ::time(nullptr);
6422
53.2k
        if (current_time < expiration) { // not expired
6423
0
            return 0;
6424
0
        }
6425
53.2k
        ++num_expired;
6426
53.2k
        expired_rowset_size += v.size();
6427
53.2k
        if (!rowset.has_resource_id()) {
6428
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6429
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6430
0
                return -1;
6431
0
            }
6432
            // might be a delete pred rowset
6433
0
            tmp_rowset_keys.emplace_back(k);
6434
0
            return 0;
6435
0
        }
6436
6437
        // TODO(plat1ko): check rowset not referenced
6438
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6439
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6440
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6441
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6442
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6443
53.2k
                  << " num_expired=" << num_expired
6444
53.2k
                  << " task_type=" << metrics_context.operation_type;
6445
6446
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6447
16
            if (need_mark_rowset_as_recycled(rowset)) {
6448
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6449
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6450
9
                             "at next turn, instance_id="
6451
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6452
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6453
9
                return 0;
6454
9
            }
6455
16
        }
6456
6457
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6458
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6459
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6460
261
                             "instance_id="
6461
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6462
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6463
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6464
261
                return 0;
6465
261
            }
6466
265
        }
6467
6468
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6469
        // Remove the rowset ref count key directly since it has not been used.
6470
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6471
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6472
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6473
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6474
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6475
6476
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6477
53.0k
        return 0;
6478
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6407
16
                                    std::string_view k, std::string_view v) -> int {
6408
16
        ++num_scanned;
6409
16
        total_rowset_key_size += k.size();
6410
16
        total_rowset_value_size += v.size();
6411
16
        doris::RowsetMetaCloudPB rowset;
6412
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6413
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6414
0
            return -1;
6415
0
        }
6416
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6417
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6418
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6419
0
                   << " txn_expiration=" << rowset.txn_expiration()
6420
0
                   << " rowset_creation_time=" << rowset.creation_time();
6421
16
        int64_t current_time = ::time(nullptr);
6422
16
        if (current_time < expiration) { // not expired
6423
0
            return 0;
6424
0
        }
6425
16
        ++num_expired;
6426
16
        expired_rowset_size += v.size();
6427
16
        if (!rowset.has_resource_id()) {
6428
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6429
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6430
0
                return -1;
6431
0
            }
6432
            // might be a delete pred rowset
6433
0
            tmp_rowset_keys.emplace_back(k);
6434
0
            return 0;
6435
0
        }
6436
6437
        // TODO(plat1ko): check rowset not referenced
6438
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6439
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6440
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6441
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6442
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6443
16
                  << " num_expired=" << num_expired
6444
16
                  << " task_type=" << metrics_context.operation_type;
6445
6446
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6447
16
            if (need_mark_rowset_as_recycled(rowset)) {
6448
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6449
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6450
9
                             "at next turn, instance_id="
6451
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6452
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6453
9
                return 0;
6454
9
            }
6455
16
        }
6456
6457
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6458
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6459
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6460
3
                             "instance_id="
6461
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6462
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6463
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6464
3
                return 0;
6465
3
            }
6466
7
        }
6467
6468
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6469
        // Remove the rowset ref count key directly since it has not been used.
6470
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6471
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6472
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6473
4
                  << "key=" << hex(rowset_ref_count_key);
6474
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6475
6476
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6477
4
        return 0;
6478
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6407
53.2k
                                    std::string_view k, std::string_view v) -> int {
6408
53.2k
        ++num_scanned;
6409
53.2k
        total_rowset_key_size += k.size();
6410
53.2k
        total_rowset_value_size += v.size();
6411
53.2k
        doris::RowsetMetaCloudPB rowset;
6412
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6413
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6414
0
            return -1;
6415
0
        }
6416
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6417
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6418
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6419
0
                   << " txn_expiration=" << rowset.txn_expiration()
6420
0
                   << " rowset_creation_time=" << rowset.creation_time();
6421
53.2k
        int64_t current_time = ::time(nullptr);
6422
53.2k
        if (current_time < expiration) { // not expired
6423
0
            return 0;
6424
0
        }
6425
53.2k
        ++num_expired;
6426
53.2k
        expired_rowset_size += v.size();
6427
53.2k
        if (!rowset.has_resource_id()) {
6428
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6429
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6430
0
                return -1;
6431
0
            }
6432
            // might be a delete pred rowset
6433
0
            tmp_rowset_keys.emplace_back(k);
6434
0
            return 0;
6435
0
        }
6436
6437
        // TODO(plat1ko): check rowset not referenced
6438
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6439
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6440
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6441
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6442
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6443
53.2k
                  << " num_expired=" << num_expired
6444
53.2k
                  << " task_type=" << metrics_context.operation_type;
6445
6446
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6447
0
            if (need_mark_rowset_as_recycled(rowset)) {
6448
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6449
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6450
0
                             "at next turn, instance_id="
6451
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6452
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6453
0
                return 0;
6454
0
            }
6455
0
        }
6456
6457
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6458
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6459
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6460
258
                             "instance_id="
6461
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6462
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6463
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6464
258
                return 0;
6465
258
            }
6466
258
        }
6467
6468
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6469
        // Remove the rowset ref count key directly since it has not been used.
6470
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6471
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6472
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6473
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6474
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6475
6476
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6477
53.0k
        return 0;
6478
53.2k
    };
6479
6480
37
    auto loop_done = [&]() -> int {
6481
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6482
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6483
24
        std::vector<std::string> mark_keys_to_process;
6484
24
        std::vector<std::string> abort_keys_to_process;
6485
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6486
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6487
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6488
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6489
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6490
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6491
24
        if (!mark_keys_to_process.empty()) {
6492
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6493
7
                    *worker_pool, std::move(mark_keys_to_process));
6494
7
        }
6495
24
        if (!abort_keys_to_process.empty()) {
6496
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6497
5
                                           &num_recycled, &metrics_context);
6498
5
        }
6499
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6500
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6501
24
                             tmp_rowset_ref_count_keys_to_delete =
6502
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6503
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6504
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6505
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6506
24
                                   metrics_context) != 0) {
6507
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6508
2
                return;
6509
2
            }
6510
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6511
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6512
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6513
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6514
0
                                 << rs.ShortDebugString();
6515
0
                    return;
6516
0
                }
6517
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6518
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6519
0
                                 << rs.ShortDebugString();
6520
0
                    return;
6521
0
                }
6522
51.0k
            }
6523
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6524
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6525
0
                return;
6526
0
            }
6527
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6528
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6529
0
                return;
6530
0
            }
6531
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6532
22
            return;
6533
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6504
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6505
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6506
12
                                   metrics_context) != 0) {
6507
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6508
0
                return;
6509
0
            }
6510
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6511
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6512
4
                                                       rs.rowset_id_v2()) != 0) {
6513
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6514
0
                                 << rs.ShortDebugString();
6515
0
                    return;
6516
0
                }
6517
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6518
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6519
0
                                 << rs.ShortDebugString();
6520
0
                    return;
6521
0
                }
6522
4
            }
6523
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6524
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6525
0
                return;
6526
0
            }
6527
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6528
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6529
0
                return;
6530
0
            }
6531
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6532
12
            return;
6533
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6504
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6505
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6506
12
                                   metrics_context) != 0) {
6507
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6508
2
                return;
6509
2
            }
6510
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6511
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6512
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6513
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6514
0
                                 << rs.ShortDebugString();
6515
0
                    return;
6516
0
                }
6517
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6518
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6519
0
                                 << rs.ShortDebugString();
6520
0
                    return;
6521
0
                }
6522
51.0k
            }
6523
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6524
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6525
0
                return;
6526
0
            }
6527
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6528
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6529
0
                return;
6530
0
            }
6531
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6532
10
            return;
6533
10
        });
6534
24
        return 0;
6535
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6480
12
    auto loop_done = [&]() -> int {
6481
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6482
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6483
12
        std::vector<std::string> mark_keys_to_process;
6484
12
        std::vector<std::string> abort_keys_to_process;
6485
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6486
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6487
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6488
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6489
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6490
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6491
12
        if (!mark_keys_to_process.empty()) {
6492
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6493
7
                    *worker_pool, std::move(mark_keys_to_process));
6494
7
        }
6495
12
        if (!abort_keys_to_process.empty()) {
6496
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6497
3
                                           &num_recycled, &metrics_context);
6498
3
        }
6499
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6500
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6501
12
                             tmp_rowset_ref_count_keys_to_delete =
6502
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6503
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6504
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6505
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6506
12
                                   metrics_context) != 0) {
6507
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6508
12
                return;
6509
12
            }
6510
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6511
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6512
12
                                                       rs.rowset_id_v2()) != 0) {
6513
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6514
12
                                 << rs.ShortDebugString();
6515
12
                    return;
6516
12
                }
6517
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6518
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6519
12
                                 << rs.ShortDebugString();
6520
12
                    return;
6521
12
                }
6522
12
            }
6523
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6524
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6525
12
                return;
6526
12
            }
6527
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6528
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6529
12
                return;
6530
12
            }
6531
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6532
12
            return;
6533
12
        });
6534
12
        return 0;
6535
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6480
12
    auto loop_done = [&]() -> int {
6481
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6482
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6483
12
        std::vector<std::string> mark_keys_to_process;
6484
12
        std::vector<std::string> abort_keys_to_process;
6485
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6486
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6487
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6488
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6489
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6490
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6491
12
        if (!mark_keys_to_process.empty()) {
6492
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6493
0
                    *worker_pool, std::move(mark_keys_to_process));
6494
0
        }
6495
12
        if (!abort_keys_to_process.empty()) {
6496
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6497
2
                                           &num_recycled, &metrics_context);
6498
2
        }
6499
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6500
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6501
12
                             tmp_rowset_ref_count_keys_to_delete =
6502
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6503
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6504
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6505
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6506
12
                                   metrics_context) != 0) {
6507
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6508
12
                return;
6509
12
            }
6510
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6511
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6512
12
                                                       rs.rowset_id_v2()) != 0) {
6513
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6514
12
                                 << rs.ShortDebugString();
6515
12
                    return;
6516
12
                }
6517
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6518
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6519
12
                                 << rs.ShortDebugString();
6520
12
                    return;
6521
12
                }
6522
12
            }
6523
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6524
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6525
12
                return;
6526
12
            }
6527
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6528
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6529
12
                return;
6530
12
            }
6531
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6532
12
            return;
6533
12
        });
6534
12
        return 0;
6535
12
    };
6536
6537
37
    if (config::enable_recycler_stats_metrics) {
6538
0
        scan_and_statistics_tmp_rowsets();
6539
0
    }
6540
    // recycle_func and loop_done for scan and recycle
6541
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6542
37
                               std::move(loop_done));
6543
6544
37
    worker_pool->stop();
6545
6546
    // Report final metrics after all concurrent tasks completed
6547
37
    segment_metrics_context_.report();
6548
37
    metrics_context.report();
6549
6550
37
    return ret;
6551
37
}
6552
6553
int InstanceRecycler::scan_and_recycle(
6554
        std::string begin, std::string_view end,
6555
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6556
281
        std::function<int()> loop_done) {
6557
281
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6558
281
    int ret = 0;
6559
281
    int64_t cnt = 0;
6560
281
    int get_range_retried = 0;
6561
281
    std::string err;
6562
281
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6563
281
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6564
281
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6565
281
                  << " ret=" << ret << " err=" << err;
6566
281
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6562
19
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6563
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6564
19
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6565
19
                  << " ret=" << ret << " err=" << err;
6566
19
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6562
262
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6563
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6564
262
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6565
262
                  << " ret=" << ret << " err=" << err;
6566
262
    };
6567
6568
281
    std::unique_ptr<RangeGetIterator> it;
6569
448
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6570
310
        if (get_range_retried > 1000) {
6571
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6572
0
            ret = -3;
6573
0
            return ret;
6574
0
        }
6575
310
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6576
310
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6577
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6578
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6579
0
                         << " get_range_retried=" << get_range_retried;
6580
0
            ++get_range_retried;
6581
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6582
0
            continue; // try again
6583
0
        }
6584
310
        if (!it->has_next()) {
6585
143
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6586
143
            break; // scan finished
6587
143
        }
6588
110k
        while (it->has_next()) {
6589
109k
            ++cnt;
6590
            // recycle corresponding resources
6591
109k
            auto [k, v] = it->next();
6592
109k
            if (!it->has_next()) {
6593
168
                begin = k;
6594
168
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6595
168
            }
6596
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6597
109k
            if (recycle_func(k, v) != 0) {
6598
1
                err = "recycle_func error";
6599
1
                ret = -1;
6600
1
            }
6601
109k
        }
6602
167
        begin.push_back('\x00'); // Update to next smallest key for iteration
6603
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6604
167
        if (loop_done && loop_done() != 0) {
6605
8
            err = "loop_done error";
6606
8
            ret = -1;
6607
8
        }
6608
167
    }
6609
281
    return ret;
6610
281
}
6611
6612
16
int InstanceRecycler::abort_timeout_txn() {
6613
16
    const std::string task_name = "abort_timeout_txn";
6614
16
    int64_t num_scanned = 0;
6615
16
    int64_t num_timeout = 0;
6616
16
    int64_t num_abort = 0;
6617
16
    int64_t num_advance = 0;
6618
16
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6619
6620
16
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6621
16
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6622
16
    std::string begin_txn_running_key;
6623
16
    std::string end_txn_running_key;
6624
16
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6625
16
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6626
6627
16
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6628
6629
16
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6630
16
    register_recycle_task(task_name, start_time);
6631
6632
16
    DORIS_CLOUD_DEFER {
6633
16
        unregister_recycle_task(task_name);
6634
16
        int64_t cost =
6635
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6636
16
        metrics_context.finish_report();
6637
16
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6638
16
                .tag("instance_id", instance_id_)
6639
16
                .tag("num_scanned", num_scanned)
6640
16
                .tag("num_timeout", num_timeout)
6641
16
                .tag("num_abort", num_abort)
6642
16
                .tag("num_advance", num_advance);
6643
16
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6632
16
    DORIS_CLOUD_DEFER {
6633
16
        unregister_recycle_task(task_name);
6634
16
        int64_t cost =
6635
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6636
16
        metrics_context.finish_report();
6637
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6638
16
                .tag("instance_id", instance_id_)
6639
16
                .tag("num_scanned", num_scanned)
6640
16
                .tag("num_timeout", num_timeout)
6641
16
                .tag("num_abort", num_abort)
6642
16
                .tag("num_advance", num_advance);
6643
16
    };
6644
6645
16
    int64_t current_time =
6646
16
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6647
6648
16
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6649
16
                                  &current_time, &metrics_context,
6650
16
                                  this](std::string_view k, std::string_view v) -> int {
6651
6
        ++num_scanned;
6652
6653
6
        std::unique_ptr<Transaction> txn;
6654
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6655
6
        if (err != TxnErrorCode::TXN_OK) {
6656
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6657
0
            return -1;
6658
0
        }
6659
6
        std::string_view k1 = k;
6660
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6661
6
        k1.remove_prefix(1); // Remove key space
6662
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6663
6
        if (decode_key(&k1, &out) != 0) {
6664
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6665
0
            return -1;
6666
0
        }
6667
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6668
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6669
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6670
        // Update txn_info
6671
6
        std::string txn_inf_key, txn_inf_val;
6672
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6673
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6674
6
        if (err != TxnErrorCode::TXN_OK) {
6675
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6676
0
            return -1;
6677
0
        }
6678
6
        TxnInfoPB txn_info;
6679
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6680
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6681
0
            return -1;
6682
0
        }
6683
6684
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6685
0
            txn.reset();
6686
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6687
0
            std::shared_ptr<TxnLazyCommitTask> task =
6688
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6689
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6690
0
            if (ret.first != MetaServiceCode::OK) {
6691
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6692
0
                             << "msg=" << ret.second;
6693
0
                return -1;
6694
0
            }
6695
0
            ++num_advance;
6696
0
            return 0;
6697
6
        } else {
6698
6
            TxnRunningPB txn_running_pb;
6699
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6700
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6701
0
                return -1;
6702
0
            }
6703
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6704
4
                return 0;
6705
4
            }
6706
2
            ++num_timeout;
6707
6708
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6709
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6710
2
            txn_info.set_finish_time(current_time);
6711
2
            txn_info.set_reason("timeout");
6712
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6713
2
            txn_inf_val.clear();
6714
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6715
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6716
0
                return -1;
6717
0
            }
6718
2
            txn->put(txn_inf_key, txn_inf_val);
6719
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6720
            // Put recycle txn key
6721
2
            std::string recyc_txn_key, recyc_txn_val;
6722
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6723
2
            RecycleTxnPB recycle_txn_pb;
6724
2
            recycle_txn_pb.set_creation_time(current_time);
6725
2
            recycle_txn_pb.set_label(txn_info.label());
6726
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6727
0
                LOG_WARNING("failed to serialize txn recycle info")
6728
0
                        .tag("key", hex(k))
6729
0
                        .tag("db_id", db_id)
6730
0
                        .tag("txn_id", txn_id);
6731
0
                return -1;
6732
0
            }
6733
2
            txn->put(recyc_txn_key, recyc_txn_val);
6734
            // Remove txn running key
6735
2
            txn->remove(k);
6736
2
            err = txn->commit();
6737
2
            if (err != TxnErrorCode::TXN_OK) {
6738
0
                LOG_WARNING("failed to commit txn err={}", err)
6739
0
                        .tag("key", hex(k))
6740
0
                        .tag("db_id", db_id)
6741
0
                        .tag("txn_id", txn_id);
6742
0
                return -1;
6743
0
            }
6744
2
            metrics_context.total_recycled_num = ++num_abort;
6745
2
            metrics_context.report();
6746
2
        }
6747
6748
2
        return 0;
6749
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6650
6
                                  this](std::string_view k, std::string_view v) -> int {
6651
6
        ++num_scanned;
6652
6653
6
        std::unique_ptr<Transaction> txn;
6654
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6655
6
        if (err != TxnErrorCode::TXN_OK) {
6656
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6657
0
            return -1;
6658
0
        }
6659
6
        std::string_view k1 = k;
6660
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6661
6
        k1.remove_prefix(1); // Remove key space
6662
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6663
6
        if (decode_key(&k1, &out) != 0) {
6664
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6665
0
            return -1;
6666
0
        }
6667
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6668
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6669
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6670
        // Update txn_info
6671
6
        std::string txn_inf_key, txn_inf_val;
6672
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6673
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6674
6
        if (err != TxnErrorCode::TXN_OK) {
6675
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6676
0
            return -1;
6677
0
        }
6678
6
        TxnInfoPB txn_info;
6679
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6680
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6681
0
            return -1;
6682
0
        }
6683
6684
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6685
0
            txn.reset();
6686
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6687
0
            std::shared_ptr<TxnLazyCommitTask> task =
6688
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6689
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6690
0
            if (ret.first != MetaServiceCode::OK) {
6691
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6692
0
                             << "msg=" << ret.second;
6693
0
                return -1;
6694
0
            }
6695
0
            ++num_advance;
6696
0
            return 0;
6697
6
        } else {
6698
6
            TxnRunningPB txn_running_pb;
6699
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6700
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6701
0
                return -1;
6702
0
            }
6703
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6704
4
                return 0;
6705
4
            }
6706
2
            ++num_timeout;
6707
6708
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6709
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6710
2
            txn_info.set_finish_time(current_time);
6711
2
            txn_info.set_reason("timeout");
6712
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6713
2
            txn_inf_val.clear();
6714
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6715
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6716
0
                return -1;
6717
0
            }
6718
2
            txn->put(txn_inf_key, txn_inf_val);
6719
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6720
            // Put recycle txn key
6721
2
            std::string recyc_txn_key, recyc_txn_val;
6722
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6723
2
            RecycleTxnPB recycle_txn_pb;
6724
2
            recycle_txn_pb.set_creation_time(current_time);
6725
2
            recycle_txn_pb.set_label(txn_info.label());
6726
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6727
0
                LOG_WARNING("failed to serialize txn recycle info")
6728
0
                        .tag("key", hex(k))
6729
0
                        .tag("db_id", db_id)
6730
0
                        .tag("txn_id", txn_id);
6731
0
                return -1;
6732
0
            }
6733
2
            txn->put(recyc_txn_key, recyc_txn_val);
6734
            // Remove txn running key
6735
2
            txn->remove(k);
6736
2
            err = txn->commit();
6737
2
            if (err != TxnErrorCode::TXN_OK) {
6738
0
                LOG_WARNING("failed to commit txn err={}", err)
6739
0
                        .tag("key", hex(k))
6740
0
                        .tag("db_id", db_id)
6741
0
                        .tag("txn_id", txn_id);
6742
0
                return -1;
6743
0
            }
6744
2
            metrics_context.total_recycled_num = ++num_abort;
6745
2
            metrics_context.report();
6746
2
        }
6747
6748
2
        return 0;
6749
6
    };
6750
6751
16
    if (config::enable_recycler_stats_metrics) {
6752
0
        scan_and_statistics_abort_timeout_txn();
6753
0
    }
6754
    // recycle_func and loop_done for scan and recycle
6755
16
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6756
16
                            std::move(handle_txn_running_kv));
6757
16
}
6758
6759
21
int InstanceRecycler::recycle_expired_txn_label() {
6760
21
    const std::string task_name = "recycle_expired_txn_label";
6761
21
    int64_t num_scanned = 0;
6762
21
    int64_t num_expired = 0;
6763
21
    std::atomic_long num_recycled = 0;
6764
21
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6765
21
    int ret = 0;
6766
6767
21
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6768
21
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6769
21
    std::string begin_recycle_txn_key;
6770
21
    std::string end_recycle_txn_key;
6771
21
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6772
21
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6773
21
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
6774
6775
21
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6776
6777
21
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6778
21
    register_recycle_task(task_name, start_time);
6779
21
    DORIS_CLOUD_DEFER {
6780
21
        unregister_recycle_task(task_name);
6781
21
        int64_t cost =
6782
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6783
21
        metrics_context.finish_report();
6784
21
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6785
21
                .tag("instance_id", instance_id_)
6786
21
                .tag("num_scanned", num_scanned)
6787
21
                .tag("num_expired", num_expired)
6788
21
                .tag("num_recycled", num_recycled);
6789
21
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6779
21
    DORIS_CLOUD_DEFER {
6780
21
        unregister_recycle_task(task_name);
6781
21
        int64_t cost =
6782
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6783
21
        metrics_context.finish_report();
6784
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6785
21
                .tag("instance_id", instance_id_)
6786
21
                .tag("num_scanned", num_scanned)
6787
21
                .tag("num_expired", num_expired)
6788
21
                .tag("num_recycled", num_recycled);
6789
21
    };
6790
6791
21
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6792
6793
21
    SyncExecutor<int> concurrent_delete_executor(
6794
21
            _thread_pool_group.s3_producer_pool,
6795
21
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6796
38.0k
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6796
38.0k
            [](const int& ret) { return ret != 0; });
6797
6798
21
    int64_t current_time_ms =
6799
21
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6800
6801
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6802
50.0k
        ++num_scanned;
6803
50.0k
        RecycleTxnPB recycle_txn_pb;
6804
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6805
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6806
0
            return -1;
6807
0
        }
6808
50.0k
        if ((config::force_immediate_recycle) ||
6809
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6810
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6811
50.0k
             current_time_ms)) {
6812
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6813
38.0k
            num_expired++;
6814
6815
38.0k
            std::string_view k1 = k;
6816
38.0k
            k1.remove_prefix(1); // Remove key space
6817
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6818
38.0k
            if (decode_key(&k1, &out) != 0) {
6819
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6820
0
                return -1;
6821
0
            }
6822
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6823
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6824
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6825
38.0k
        }
6826
50.0k
        return 0;
6827
50.0k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6801
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6802
50.0k
        ++num_scanned;
6803
50.0k
        RecycleTxnPB recycle_txn_pb;
6804
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6805
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6806
0
            return -1;
6807
0
        }
6808
50.0k
        if ((config::force_immediate_recycle) ||
6809
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6810
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6811
50.0k
             current_time_ms)) {
6812
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6813
38.0k
            num_expired++;
6814
6815
38.0k
            std::string_view k1 = k;
6816
38.0k
            k1.remove_prefix(1); // Remove key space
6817
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6818
38.0k
            if (decode_key(&k1, &out) != 0) {
6819
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6820
0
                return -1;
6821
0
            }
6822
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6823
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6824
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6825
38.0k
        }
6826
50.0k
        return 0;
6827
50.0k
    };
6828
6829
    // int 0 for success, 1 for conflict, -1 for error
6830
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6831
38.0k
        std::string_view k1 = k;
6832
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6833
38.0k
        k1.remove_prefix(1); // Remove key space
6834
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
38.0k
        int ret = decode_key(&k1, &out);
6836
38.0k
        if (ret != 0) {
6837
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6838
0
            return -1;
6839
0
        }
6840
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6841
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6842
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6843
38.0k
        std::unique_ptr<Transaction> txn;
6844
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6845
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6846
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6847
0
            return -1;
6848
0
        }
6849
        // Remove txn index kv
6850
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6851
38.0k
        txn->remove(index_key);
6852
        // Remove txn info kv
6853
38.0k
        std::string info_key, info_val;
6854
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6855
38.0k
        err = txn->get(info_key, &info_val);
6856
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6857
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6858
0
            return -1;
6859
0
        }
6860
38.0k
        TxnInfoPB txn_info;
6861
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6862
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6863
0
            return -1;
6864
0
        }
6865
38.0k
        txn->remove(info_key);
6866
        // Remove sub txn index kvs
6867
38.0k
        std::vector<std::string> sub_txn_index_keys;
6868
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6869
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6870
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6871
38.0k
        }
6872
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6873
37.9k
            txn->remove(sub_txn_index_key);
6874
37.9k
        }
6875
        // Update txn label
6876
38.0k
        std::string label_key, label_val;
6877
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6878
38.0k
        err = txn->get(label_key, &label_val);
6879
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6880
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6881
0
                         << " err=" << err;
6882
0
            return -1;
6883
0
        }
6884
38.0k
        TxnLabelPB txn_label;
6885
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6886
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6887
0
            return -1;
6888
0
        }
6889
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6890
38.0k
        if (it != txn_label.txn_ids().end()) {
6891
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6892
38.0k
        }
6893
38.0k
        if (txn_label.txn_ids().empty()) {
6894
38.0k
            txn->remove(label_key);
6895
38.0k
            TEST_SYNC_POINT_CALLBACK(
6896
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6897
38.0k
        } else {
6898
11
            if (!txn_label.SerializeToString(&label_val)) {
6899
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6900
0
                return -1;
6901
0
            }
6902
11
            TEST_SYNC_POINT_CALLBACK(
6903
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6904
11
            txn->atomic_set_ver_value(label_key, label_val);
6905
11
            TEST_SYNC_POINT_CALLBACK(
6906
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6907
11
        }
6908
        // Remove recycle txn kv
6909
38.0k
        txn->remove(k);
6910
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6911
38.0k
        err = txn->commit();
6912
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6913
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6914
4
                TEST_SYNC_POINT_CALLBACK(
6915
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6916
                // log the txn_id and label
6917
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6918
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6919
4
                             << " txn_label=" << txn_info.label();
6920
4
                return 1;
6921
4
            }
6922
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6923
0
            return -1;
6924
4
        }
6925
38.0k
        ++num_recycled;
6926
6927
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6928
38.0k
        return 0;
6929
38.0k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6830
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6831
38.0k
        std::string_view k1 = k;
6832
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6833
38.0k
        k1.remove_prefix(1); // Remove key space
6834
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
38.0k
        int ret = decode_key(&k1, &out);
6836
38.0k
        if (ret != 0) {
6837
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6838
0
            return -1;
6839
0
        }
6840
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6841
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6842
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6843
38.0k
        std::unique_ptr<Transaction> txn;
6844
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6845
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6846
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6847
0
            return -1;
6848
0
        }
6849
        // Remove txn index kv
6850
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6851
38.0k
        txn->remove(index_key);
6852
        // Remove txn info kv
6853
38.0k
        std::string info_key, info_val;
6854
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6855
38.0k
        err = txn->get(info_key, &info_val);
6856
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6857
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6858
0
            return -1;
6859
0
        }
6860
38.0k
        TxnInfoPB txn_info;
6861
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6862
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6863
0
            return -1;
6864
0
        }
6865
38.0k
        txn->remove(info_key);
6866
        // Remove sub txn index kvs
6867
38.0k
        std::vector<std::string> sub_txn_index_keys;
6868
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6869
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6870
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6871
38.0k
        }
6872
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6873
37.9k
            txn->remove(sub_txn_index_key);
6874
37.9k
        }
6875
        // Update txn label
6876
38.0k
        std::string label_key, label_val;
6877
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6878
38.0k
        err = txn->get(label_key, &label_val);
6879
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6880
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6881
0
                         << " err=" << err;
6882
0
            return -1;
6883
0
        }
6884
38.0k
        TxnLabelPB txn_label;
6885
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6886
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6887
0
            return -1;
6888
0
        }
6889
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6890
38.0k
        if (it != txn_label.txn_ids().end()) {
6891
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6892
38.0k
        }
6893
38.0k
        if (txn_label.txn_ids().empty()) {
6894
38.0k
            txn->remove(label_key);
6895
38.0k
            TEST_SYNC_POINT_CALLBACK(
6896
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6897
38.0k
        } else {
6898
11
            if (!txn_label.SerializeToString(&label_val)) {
6899
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6900
0
                return -1;
6901
0
            }
6902
11
            TEST_SYNC_POINT_CALLBACK(
6903
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6904
11
            txn->atomic_set_ver_value(label_key, label_val);
6905
11
            TEST_SYNC_POINT_CALLBACK(
6906
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6907
11
        }
6908
        // Remove recycle txn kv
6909
38.0k
        txn->remove(k);
6910
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6911
38.0k
        err = txn->commit();
6912
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6913
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6914
4
                TEST_SYNC_POINT_CALLBACK(
6915
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6916
                // log the txn_id and label
6917
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6918
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6919
4
                             << " txn_label=" << txn_info.label();
6920
4
                return 1;
6921
4
            }
6922
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6923
0
            return -1;
6924
4
        }
6925
38.0k
        ++num_recycled;
6926
6927
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6928
38.0k
        return 0;
6929
38.0k
    };
6930
6931
21
    auto loop_done = [&]() -> int {
6932
14
        DORIS_CLOUD_DEFER {
6933
14
            recycle_txn_keys_by_label.clear();
6934
14
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6932
14
        DORIS_CLOUD_DEFER {
6933
14
            recycle_txn_keys_by_label.clear();
6934
14
        };
6935
14
        TEST_SYNC_POINT_CALLBACK(
6936
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6937
14
                &recycle_txn_keys_by_label);
6938
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6939
38.0k
            int ret = delete_recycle_txn_kv(k);
6940
38.0k
            TEST_SYNC_POINT_CALLBACK(
6941
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6942
38.0k
                    &ret);
6943
38.0k
            if (ret == 1) {
6944
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6945
4
                for (int i = 1; i <= max_retry; ++i) {
6946
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6947
3
                    ret = delete_recycle_txn_kv(k);
6948
3
                    TEST_SYNC_POINT_CALLBACK(
6949
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6950
3
                            "error",
6951
3
                            &ret);
6952
3
                    if (ret != 1) {
6953
1
                        break;
6954
1
                    }
6955
                    // random sleep 0-100 ms to retry
6956
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6957
2
                }
6958
2
            }
6959
38.0k
            return ret;
6960
38.0k
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6938
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6939
38.0k
            int ret = delete_recycle_txn_kv(k);
6940
38.0k
            TEST_SYNC_POINT_CALLBACK(
6941
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6942
38.0k
                    &ret);
6943
38.0k
            if (ret == 1) {
6944
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6945
4
                for (int i = 1; i <= max_retry; ++i) {
6946
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6947
3
                    ret = delete_recycle_txn_kv(k);
6948
3
                    TEST_SYNC_POINT_CALLBACK(
6949
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6950
3
                            "error",
6951
3
                            &ret);
6952
3
                    if (ret != 1) {
6953
1
                        break;
6954
1
                    }
6955
                    // random sleep 0-100 ms to retry
6956
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6957
2
                }
6958
2
            }
6959
38.0k
            return ret;
6960
38.0k
        };
6961
6962
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6963
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6964
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6965
0
                           << " txn_count=" << txn_keys.size();
6966
38.0k
                for (const auto& k : txn_keys) {
6967
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6968
38.0k
                    if (ret != 0) {
6969
2
                        LOG_WARNING("failed to delete recycle txn kv")
6970
2
                                .tag("instance id", instance_id_)
6971
2
                                .tag("key", hex(k))
6972
2
                                .tag("label_key", hex(label_key));
6973
2
                        return -1;
6974
2
                    }
6975
38.0k
                }
6976
38.0k
                return 0;
6977
38.0k
            });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6963
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6964
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6965
0
                           << " txn_count=" << txn_keys.size();
6966
38.0k
                for (const auto& k : txn_keys) {
6967
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6968
38.0k
                    if (ret != 0) {
6969
2
                        LOG_WARNING("failed to delete recycle txn kv")
6970
2
                                .tag("instance id", instance_id_)
6971
2
                                .tag("key", hex(k))
6972
2
                                .tag("label_key", hex(label_key));
6973
2
                        return -1;
6974
2
                    }
6975
38.0k
                }
6976
38.0k
                return 0;
6977
38.0k
            });
6978
38.0k
        }
6979
14
        bool finished = true;
6980
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6981
38.0k
        for (int r : rets) {
6982
38.0k
            if (r != 0) {
6983
2
                ret = -1;
6984
2
            }
6985
38.0k
        }
6986
6987
14
        ret = finished ? ret : -1;
6988
6989
        // Update metrics after all concurrent tasks completed
6990
14
        metrics_context.total_recycled_num = num_recycled.load();
6991
14
        metrics_context.report();
6992
6993
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6994
6995
14
        if (ret != 0) {
6996
6
            LOG_WARNING("recycle txn kv ret!=0")
6997
6
                    .tag("finished", finished)
6998
6
                    .tag("ret", ret)
6999
6
                    .tag("instance_id", instance_id_);
7000
6
            return ret;
7001
6
        }
7002
8
        return ret;
7003
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6931
14
    auto loop_done = [&]() -> int {
6932
14
        DORIS_CLOUD_DEFER {
6933
14
            recycle_txn_keys_by_label.clear();
6934
14
        };
6935
14
        TEST_SYNC_POINT_CALLBACK(
6936
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6937
14
                &recycle_txn_keys_by_label);
6938
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6939
14
            int ret = delete_recycle_txn_kv(k);
6940
14
            TEST_SYNC_POINT_CALLBACK(
6941
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6942
14
                    &ret);
6943
14
            if (ret == 1) {
6944
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6945
14
                for (int i = 1; i <= max_retry; ++i) {
6946
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6947
14
                    ret = delete_recycle_txn_kv(k);
6948
14
                    TEST_SYNC_POINT_CALLBACK(
6949
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6950
14
                            "error",
6951
14
                            &ret);
6952
14
                    if (ret != 1) {
6953
14
                        break;
6954
14
                    }
6955
                    // random sleep 0-100 ms to retry
6956
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6957
14
                }
6958
14
            }
6959
14
            return ret;
6960
14
        };
6961
6962
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6963
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6964
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6965
38.0k
                           << " txn_count=" << txn_keys.size();
6966
38.0k
                for (const auto& k : txn_keys) {
6967
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6968
38.0k
                    if (ret != 0) {
6969
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
6970
38.0k
                                .tag("instance id", instance_id_)
6971
38.0k
                                .tag("key", hex(k))
6972
38.0k
                                .tag("label_key", hex(label_key));
6973
38.0k
                        return -1;
6974
38.0k
                    }
6975
38.0k
                }
6976
38.0k
                return 0;
6977
38.0k
            });
6978
38.0k
        }
6979
14
        bool finished = true;
6980
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6981
38.0k
        for (int r : rets) {
6982
38.0k
            if (r != 0) {
6983
2
                ret = -1;
6984
2
            }
6985
38.0k
        }
6986
6987
14
        ret = finished ? ret : -1;
6988
6989
        // Update metrics after all concurrent tasks completed
6990
14
        metrics_context.total_recycled_num = num_recycled.load();
6991
14
        metrics_context.report();
6992
6993
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
6994
6995
14
        if (ret != 0) {
6996
6
            LOG_WARNING("recycle txn kv ret!=0")
6997
6
                    .tag("finished", finished)
6998
6
                    .tag("ret", ret)
6999
6
                    .tag("instance_id", instance_id_);
7000
6
            return ret;
7001
6
        }
7002
8
        return ret;
7003
14
    };
7004
7005
21
    if (config::enable_recycler_stats_metrics) {
7006
0
        scan_and_statistics_expired_txn_label();
7007
0
    }
7008
    // recycle_func and loop_done for scan and recycle
7009
21
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7010
21
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7011
21
}
7012
7013
struct CopyJobIdTuple {
7014
    std::string instance_id;
7015
    std::string stage_id;
7016
    long table_id;
7017
    std::string copy_id;
7018
    std::string stage_path;
7019
};
7020
struct BatchObjStoreAccessor {
7021
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7022
                          TxnKv* txn_kv)
7023
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7024
3
    ~BatchObjStoreAccessor() {
7025
3
        if (!paths_.empty()) {
7026
3
            consume();
7027
3
        }
7028
3
    }
7029
7030
    /**
7031
    * To implicitely do batch work and submit the batch delete task to s3
7032
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7033
    *
7034
    * @param copy_job The protubuf struct consists of the copy job files.
7035
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7036
    *            it would last until we finish the delete task, here we need pass one string value
7037
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7038
    */
7039
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7040
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7041
5
        auto& file_keys = copy_file_keys_[key];
7042
5
        file_keys.log_trace =
7043
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7044
5
                            instance_id, stage_id, table_id, copy_id, path);
7045
5
        std::string_view log_trace = file_keys.log_trace;
7046
2.03k
        for (const auto& file : copy_job.object_files()) {
7047
2.03k
            auto relative_path = file.relative_path();
7048
2.03k
            paths_.push_back(relative_path);
7049
2.03k
            file_keys.keys.push_back(copy_file_key(
7050
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7051
2.03k
            LOG_INFO(log_trace)
7052
2.03k
                    .tag("relative_path", relative_path)
7053
2.03k
                    .tag("batch_count", batch_count_);
7054
2.03k
        }
7055
5
        LOG_INFO(log_trace)
7056
5
                .tag("objects_num", copy_job.object_files().size())
7057
5
                .tag("batch_count", batch_count_);
7058
        // 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
7059
        // recommend using delete objects when objects num is less than 10)
7060
5
        if (paths_.size() < 1000) {
7061
3
            return;
7062
3
        }
7063
2
        consume();
7064
2
    }
7065
7066
private:
7067
5
    void consume() {
7068
5
        DORIS_CLOUD_DEFER {
7069
5
            paths_.clear();
7070
5
            copy_file_keys_.clear();
7071
5
            batch_count_++;
7072
7073
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7074
5
                        batch_count_);
7075
5
        };
7076
7077
5
        StopWatch sw;
7078
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7079
5
        if (0 != accessor_->delete_files(paths_)) {
7080
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7081
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7082
2
            return;
7083
2
        }
7084
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7085
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7086
        // delete fdb's keys
7087
3
        for (auto& file_keys : copy_file_keys_) {
7088
3
            auto& [log_trace, keys] = file_keys.second;
7089
3
            std::unique_ptr<Transaction> txn;
7090
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7091
0
                LOG(WARNING) << "failed to create txn";
7092
0
                continue;
7093
0
            }
7094
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7095
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7096
            // limited, should not cause the txn commit failed.
7097
1.02k
            for (const auto& key : keys) {
7098
1.02k
                txn->remove(key);
7099
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7100
1.02k
            }
7101
3
            txn->remove(file_keys.first);
7102
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7103
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7104
0
                continue;
7105
0
            }
7106
3
        }
7107
3
    }
7108
    std::shared_ptr<StorageVaultAccessor> accessor_;
7109
    // the path of the s3 files to be deleted
7110
    std::vector<std::string> paths_;
7111
    struct CopyFiles {
7112
        std::string log_trace;
7113
        std::vector<std::string> keys;
7114
    };
7115
    // pair<std::string, std::vector<std::string>>
7116
    // first: instance_id_ stage_id table_id query_id
7117
    // second: keys to be deleted
7118
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7119
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7120
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7121
    // which can together uniquely identifies different tasks for tracing log
7122
    uint64_t& batch_count_;
7123
    TxnKv* txn_kv_;
7124
};
7125
7126
13
int InstanceRecycler::recycle_copy_jobs() {
7127
13
    int64_t num_scanned = 0;
7128
13
    int64_t num_finished = 0;
7129
13
    int64_t num_expired = 0;
7130
13
    int64_t num_recycled = 0;
7131
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7132
13
    uint64_t batch_count = 0;
7133
13
    const std::string task_name = "recycle_copy_jobs";
7134
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7135
7136
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7137
7138
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7139
13
    register_recycle_task(task_name, start_time);
7140
7141
13
    DORIS_CLOUD_DEFER {
7142
13
        unregister_recycle_task(task_name);
7143
13
        int64_t cost =
7144
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7145
13
        metrics_context.finish_report();
7146
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7147
13
                .tag("instance_id", instance_id_)
7148
13
                .tag("num_scanned", num_scanned)
7149
13
                .tag("num_finished", num_finished)
7150
13
                .tag("num_expired", num_expired)
7151
13
                .tag("num_recycled", num_recycled);
7152
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7141
13
    DORIS_CLOUD_DEFER {
7142
13
        unregister_recycle_task(task_name);
7143
13
        int64_t cost =
7144
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7145
13
        metrics_context.finish_report();
7146
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7147
13
                .tag("instance_id", instance_id_)
7148
13
                .tag("num_scanned", num_scanned)
7149
13
                .tag("num_finished", num_finished)
7150
13
                .tag("num_expired", num_expired)
7151
13
                .tag("num_recycled", num_recycled);
7152
13
    };
7153
7154
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7155
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7156
13
    std::string key0;
7157
13
    std::string key1;
7158
13
    copy_job_key(key_info0, &key0);
7159
13
    copy_job_key(key_info1, &key1);
7160
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7161
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7162
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7163
16
                         this](std::string_view k, std::string_view v) -> int {
7164
16
        ++num_scanned;
7165
16
        CopyJobPB copy_job;
7166
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7167
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7168
0
            return -1;
7169
0
        }
7170
7171
        // decode copy job key
7172
16
        auto k1 = k;
7173
16
        k1.remove_prefix(1);
7174
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7175
16
        decode_key(&k1, &out);
7176
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7177
        // -> CopyJobPB
7178
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7179
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7180
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7181
7182
16
        bool check_storage = true;
7183
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7184
12
            ++num_finished;
7185
7186
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7187
7
                auto it = stage_accessor_map.find(stage_id);
7188
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7189
7
                std::string_view path;
7190
7
                if (it != stage_accessor_map.end()) {
7191
2
                    accessor = it->second;
7192
5
                } else {
7193
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7194
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7195
5
                                                      &inner_accessor);
7196
5
                    if (ret < 0) { // error
7197
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7198
0
                        return -1;
7199
5
                    } else if (ret == 0) {
7200
3
                        path = inner_accessor->uri();
7201
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7202
3
                                inner_accessor, batch_count, txn_kv_.get());
7203
3
                        stage_accessor_map.emplace(stage_id, accessor);
7204
3
                    } else { // stage not found, skip check storage
7205
2
                        check_storage = false;
7206
2
                    }
7207
5
                }
7208
7
                if (check_storage) {
7209
                    // TODO delete objects with key and etag is not supported
7210
5
                    accessor->add(std::move(copy_job), std::string(k),
7211
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7212
5
                    return 0;
7213
5
                }
7214
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7215
5
                int64_t current_time =
7216
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7217
5
                if (copy_job.finish_time_ms() > 0) {
7218
2
                    if (!config::force_immediate_recycle &&
7219
2
                        current_time < copy_job.finish_time_ms() +
7220
2
                                               config::copy_job_max_retention_second * 1000) {
7221
1
                        return 0;
7222
1
                    }
7223
3
                } else {
7224
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7225
3
                    if (!config::force_immediate_recycle &&
7226
3
                        current_time < copy_job.start_time_ms() +
7227
3
                                               config::copy_job_max_retention_second * 1000) {
7228
1
                        return 0;
7229
1
                    }
7230
3
                }
7231
5
            }
7232
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7233
4
            int64_t current_time =
7234
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7235
            // if copy job is timeout: delete all copy file kvs and copy job kv
7236
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7237
2
                return 0;
7238
2
            }
7239
2
            ++num_expired;
7240
2
        }
7241
7242
        // delete all copy files
7243
7
        std::vector<std::string> copy_file_keys;
7244
70
        for (auto& file : copy_job.object_files()) {
7245
70
            copy_file_keys.push_back(copy_file_key(
7246
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7247
70
        }
7248
7
        std::unique_ptr<Transaction> txn;
7249
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7250
0
            LOG(WARNING) << "failed to create txn";
7251
0
            return -1;
7252
0
        }
7253
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7254
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7255
        // limited, should not cause the txn commit failed.
7256
70
        for (const auto& key : copy_file_keys) {
7257
70
            txn->remove(key);
7258
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7259
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7260
70
                      << ", query_id=" << copy_id;
7261
70
        }
7262
7
        txn->remove(k);
7263
7
        TxnErrorCode err = txn->commit();
7264
7
        if (err != TxnErrorCode::TXN_OK) {
7265
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7266
0
            return -1;
7267
0
        }
7268
7269
7
        metrics_context.total_recycled_num = ++num_recycled;
7270
7
        metrics_context.report();
7271
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7272
7
        return 0;
7273
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
7163
16
                         this](std::string_view k, std::string_view v) -> int {
7164
16
        ++num_scanned;
7165
16
        CopyJobPB copy_job;
7166
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7167
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7168
0
            return -1;
7169
0
        }
7170
7171
        // decode copy job key
7172
16
        auto k1 = k;
7173
16
        k1.remove_prefix(1);
7174
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7175
16
        decode_key(&k1, &out);
7176
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7177
        // -> CopyJobPB
7178
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7179
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7180
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7181
7182
16
        bool check_storage = true;
7183
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7184
12
            ++num_finished;
7185
7186
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7187
7
                auto it = stage_accessor_map.find(stage_id);
7188
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7189
7
                std::string_view path;
7190
7
                if (it != stage_accessor_map.end()) {
7191
2
                    accessor = it->second;
7192
5
                } else {
7193
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7194
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7195
5
                                                      &inner_accessor);
7196
5
                    if (ret < 0) { // error
7197
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7198
0
                        return -1;
7199
5
                    } else if (ret == 0) {
7200
3
                        path = inner_accessor->uri();
7201
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7202
3
                                inner_accessor, batch_count, txn_kv_.get());
7203
3
                        stage_accessor_map.emplace(stage_id, accessor);
7204
3
                    } else { // stage not found, skip check storage
7205
2
                        check_storage = false;
7206
2
                    }
7207
5
                }
7208
7
                if (check_storage) {
7209
                    // TODO delete objects with key and etag is not supported
7210
5
                    accessor->add(std::move(copy_job), std::string(k),
7211
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7212
5
                    return 0;
7213
5
                }
7214
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7215
5
                int64_t current_time =
7216
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7217
5
                if (copy_job.finish_time_ms() > 0) {
7218
2
                    if (!config::force_immediate_recycle &&
7219
2
                        current_time < copy_job.finish_time_ms() +
7220
2
                                               config::copy_job_max_retention_second * 1000) {
7221
1
                        return 0;
7222
1
                    }
7223
3
                } else {
7224
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7225
3
                    if (!config::force_immediate_recycle &&
7226
3
                        current_time < copy_job.start_time_ms() +
7227
3
                                               config::copy_job_max_retention_second * 1000) {
7228
1
                        return 0;
7229
1
                    }
7230
3
                }
7231
5
            }
7232
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7233
4
            int64_t current_time =
7234
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7235
            // if copy job is timeout: delete all copy file kvs and copy job kv
7236
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7237
2
                return 0;
7238
2
            }
7239
2
            ++num_expired;
7240
2
        }
7241
7242
        // delete all copy files
7243
7
        std::vector<std::string> copy_file_keys;
7244
70
        for (auto& file : copy_job.object_files()) {
7245
70
            copy_file_keys.push_back(copy_file_key(
7246
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7247
70
        }
7248
7
        std::unique_ptr<Transaction> txn;
7249
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7250
0
            LOG(WARNING) << "failed to create txn";
7251
0
            return -1;
7252
0
        }
7253
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7254
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7255
        // limited, should not cause the txn commit failed.
7256
70
        for (const auto& key : copy_file_keys) {
7257
70
            txn->remove(key);
7258
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7259
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7260
70
                      << ", query_id=" << copy_id;
7261
70
        }
7262
7
        txn->remove(k);
7263
7
        TxnErrorCode err = txn->commit();
7264
7
        if (err != TxnErrorCode::TXN_OK) {
7265
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7266
0
            return -1;
7267
0
        }
7268
7269
7
        metrics_context.total_recycled_num = ++num_recycled;
7270
7
        metrics_context.report();
7271
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7272
7
        return 0;
7273
7
    };
7274
7275
13
    if (config::enable_recycler_stats_metrics) {
7276
0
        scan_and_statistics_copy_jobs();
7277
0
    }
7278
    // recycle_func and loop_done for scan and recycle
7279
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7280
13
}
7281
7282
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7283
                                             const StagePB::StageType& stage_type,
7284
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7285
5
#ifdef UNIT_TEST
7286
    // In unit test, external use the same accessor as the internal stage
7287
5
    auto it = accessor_map_.find(stage_id);
7288
5
    if (it != accessor_map_.end()) {
7289
3
        *accessor = it->second;
7290
3
    } else {
7291
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7292
2
        return 1;
7293
2
    }
7294
#else
7295
    // init s3 accessor and add to accessor map
7296
    auto stage_it =
7297
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7298
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7299
7300
    if (stage_it == instance_info_.stages().end()) {
7301
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7302
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7303
        return 1;
7304
    }
7305
7306
    const auto& object_store_info = stage_it->obj_info();
7307
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7308
7309
    S3Conf s3_conf;
7310
    if (stage_type == StagePB::EXTERNAL) {
7311
        if (stage_access_type == StagePB::AKSK) {
7312
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7313
            if (!conf) {
7314
                return -1;
7315
            }
7316
7317
            s3_conf = std::move(*conf);
7318
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7319
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7320
            if (!conf) {
7321
                return -1;
7322
            }
7323
7324
            s3_conf = std::move(*conf);
7325
            if (instance_info_.ram_user().has_encryption_info()) {
7326
                AkSkPair plain_ak_sk_pair;
7327
                int ret = decrypt_ak_sk_helper(
7328
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7329
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7330
                if (ret != 0) {
7331
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7332
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7333
                    return -1;
7334
                }
7335
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7336
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7337
            } else {
7338
                s3_conf.ak = instance_info_.ram_user().ak();
7339
                s3_conf.sk = instance_info_.ram_user().sk();
7340
            }
7341
        } else {
7342
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7343
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7344
            return -1;
7345
        }
7346
    } else if (stage_type == StagePB::INTERNAL) {
7347
        int idx = stoi(object_store_info.id());
7348
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7349
            LOG(WARNING) << "invalid idx: " << idx;
7350
            return -1;
7351
        }
7352
7353
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7354
        auto conf = S3Conf::from_obj_store_info(old_obj);
7355
        if (!conf) {
7356
            return -1;
7357
        }
7358
7359
        s3_conf = std::move(*conf);
7360
        s3_conf.prefix = object_store_info.prefix();
7361
    } else {
7362
        LOG(WARNING) << "unknown stage type " << stage_type;
7363
        return -1;
7364
    }
7365
7366
    std::shared_ptr<S3Accessor> s3_accessor;
7367
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7368
    if (ret != 0) {
7369
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7370
        return -1;
7371
    }
7372
7373
    *accessor = std::move(s3_accessor);
7374
#endif
7375
3
    return 0;
7376
5
}
7377
7378
11
int InstanceRecycler::recycle_stage() {
7379
11
    int64_t num_scanned = 0;
7380
11
    int64_t num_recycled = 0;
7381
11
    const std::string task_name = "recycle_stage";
7382
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7383
7384
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7385
7386
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7387
11
    register_recycle_task(task_name, start_time);
7388
7389
11
    DORIS_CLOUD_DEFER {
7390
11
        unregister_recycle_task(task_name);
7391
11
        int64_t cost =
7392
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7393
11
        metrics_context.finish_report();
7394
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7395
11
                .tag("instance_id", instance_id_)
7396
11
                .tag("num_scanned", num_scanned)
7397
11
                .tag("num_recycled", num_recycled);
7398
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7389
11
    DORIS_CLOUD_DEFER {
7390
11
        unregister_recycle_task(task_name);
7391
11
        int64_t cost =
7392
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7393
11
        metrics_context.finish_report();
7394
        LOG_WARNING("recycle stage, cost={}s", cost)
7395
11
                .tag("instance_id", instance_id_)
7396
11
                .tag("num_scanned", num_scanned)
7397
11
                .tag("num_recycled", num_recycled);
7398
11
    };
7399
7400
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7401
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7402
11
    std::string key0 = recycle_stage_key(key_info0);
7403
11
    std::string key1 = recycle_stage_key(key_info1);
7404
7405
11
    std::vector<std::string_view> stage_keys;
7406
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7407
11
                         this](std::string_view k, std::string_view v) -> int {
7408
1
        ++num_scanned;
7409
1
        RecycleStagePB recycle_stage;
7410
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7411
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7412
0
            return -1;
7413
0
        }
7414
7415
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7416
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7417
0
            LOG(WARNING) << "invalid idx: " << idx;
7418
0
            return -1;
7419
0
        }
7420
7421
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7422
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7423
1
                [&] {
7424
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7425
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7426
1
                    if (!s3_conf) {
7427
1
                        return -1;
7428
1
                    }
7429
7430
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7431
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7432
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7433
1
                    if (ret != 0) {
7434
1
                        return -1;
7435
1
                    }
7436
7437
1
                    accessor = std::move(s3_accessor);
7438
1
                    return 0;
7439
1
                }(),
7440
1
                "recycle_stage:get_accessor", &accessor);
7441
7442
1
        if (ret != 0) {
7443
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7444
0
            return ret;
7445
0
        }
7446
7447
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7448
1
                .tag("instance_id", instance_id_)
7449
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7450
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7451
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7452
1
                .tag("obj_info_id", idx)
7453
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7454
1
        ret = accessor->delete_all();
7455
1
        if (ret != 0) {
7456
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7457
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7458
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7459
0
                         << ", ret=" << ret;
7460
0
            return -1;
7461
0
        }
7462
1
        metrics_context.total_recycled_num = ++num_recycled;
7463
1
        metrics_context.report();
7464
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7465
1
        stage_keys.push_back(k);
7466
1
        return 0;
7467
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7407
1
                         this](std::string_view k, std::string_view v) -> int {
7408
1
        ++num_scanned;
7409
1
        RecycleStagePB recycle_stage;
7410
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7411
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7412
0
            return -1;
7413
0
        }
7414
7415
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7416
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7417
0
            LOG(WARNING) << "invalid idx: " << idx;
7418
0
            return -1;
7419
0
        }
7420
7421
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7422
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7423
1
                [&] {
7424
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7425
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7426
1
                    if (!s3_conf) {
7427
1
                        return -1;
7428
1
                    }
7429
7430
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7431
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7432
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7433
1
                    if (ret != 0) {
7434
1
                        return -1;
7435
1
                    }
7436
7437
1
                    accessor = std::move(s3_accessor);
7438
1
                    return 0;
7439
1
                }(),
7440
1
                "recycle_stage:get_accessor", &accessor);
7441
7442
1
        if (ret != 0) {
7443
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7444
0
            return ret;
7445
0
        }
7446
7447
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7448
1
                .tag("instance_id", instance_id_)
7449
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7450
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7451
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7452
1
                .tag("obj_info_id", idx)
7453
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7454
1
        ret = accessor->delete_all();
7455
1
        if (ret != 0) {
7456
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7457
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7458
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7459
0
                         << ", ret=" << ret;
7460
0
            return -1;
7461
0
        }
7462
1
        metrics_context.total_recycled_num = ++num_recycled;
7463
1
        metrics_context.report();
7464
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7465
1
        stage_keys.push_back(k);
7466
1
        return 0;
7467
1
    };
7468
7469
11
    auto loop_done = [&stage_keys, this]() -> int {
7470
1
        if (stage_keys.empty()) return 0;
7471
1
        DORIS_CLOUD_DEFER {
7472
1
            stage_keys.clear();
7473
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7471
1
        DORIS_CLOUD_DEFER {
7472
1
            stage_keys.clear();
7473
1
        };
7474
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7475
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7476
0
            return -1;
7477
0
        }
7478
1
        return 0;
7479
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7469
1
    auto loop_done = [&stage_keys, this]() -> int {
7470
1
        if (stage_keys.empty()) return 0;
7471
1
        DORIS_CLOUD_DEFER {
7472
1
            stage_keys.clear();
7473
1
        };
7474
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7475
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7476
0
            return -1;
7477
0
        }
7478
1
        return 0;
7479
1
    };
7480
11
    if (config::enable_recycler_stats_metrics) {
7481
0
        scan_and_statistics_stage();
7482
0
    }
7483
    // recycle_func and loop_done for scan and recycle
7484
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7485
11
}
7486
7487
10
int InstanceRecycler::recycle_expired_stage_objects() {
7488
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7489
7490
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7491
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7492
7493
10
    DORIS_CLOUD_DEFER {
7494
10
        int64_t cost =
7495
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7496
10
        metrics_context.finish_report();
7497
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7498
10
                .tag("instance_id", instance_id_);
7499
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7493
10
    DORIS_CLOUD_DEFER {
7494
10
        int64_t cost =
7495
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7496
10
        metrics_context.finish_report();
7497
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7498
10
                .tag("instance_id", instance_id_);
7499
10
    };
7500
7501
10
    int ret = 0;
7502
7503
10
    if (config::enable_recycler_stats_metrics) {
7504
0
        scan_and_statistics_expired_stage_objects();
7505
0
    }
7506
7507
10
    for (const auto& stage : instance_info_.stages()) {
7508
0
        std::stringstream ss;
7509
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7510
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7511
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7512
0
           << ", prefix=" << stage.obj_info().prefix();
7513
7514
0
        if (stopped()) {
7515
0
            break;
7516
0
        }
7517
0
        if (stage.type() == StagePB::EXTERNAL) {
7518
0
            continue;
7519
0
        }
7520
0
        int idx = stoi(stage.obj_info().id());
7521
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7522
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7523
0
            continue;
7524
0
        }
7525
7526
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7527
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7528
0
        if (!s3_conf) {
7529
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7530
0
            continue;
7531
0
        }
7532
7533
0
        s3_conf->prefix = stage.obj_info().prefix();
7534
0
        std::shared_ptr<S3Accessor> accessor;
7535
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7536
0
        if (ret1 != 0) {
7537
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7538
0
            ret = -1;
7539
0
            continue;
7540
0
        }
7541
7542
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7543
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7544
0
            ret = -1;
7545
0
            continue;
7546
0
        }
7547
7548
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7549
0
        int64_t expiration_time =
7550
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7551
0
                config::internal_stage_objects_expire_time_second;
7552
0
        if (config::force_immediate_recycle) {
7553
0
            expiration_time = INT64_MAX;
7554
0
        }
7555
0
        ret1 = accessor->delete_all(expiration_time);
7556
0
        if (ret1 != 0) {
7557
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7558
0
                         << ss.str();
7559
0
            ret = -1;
7560
0
            continue;
7561
0
        }
7562
0
        metrics_context.total_recycled_num++;
7563
0
        metrics_context.report();
7564
0
    }
7565
10
    return ret;
7566
10
}
7567
7568
207
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7569
207
    std::lock_guard lock(recycle_tasks_mutex);
7570
207
    running_recycle_tasks[task_name] = start_time;
7571
207
}
7572
7573
207
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7574
207
    std::lock_guard lock(recycle_tasks_mutex);
7575
207
    DCHECK(running_recycle_tasks[task_name] > 0);
7576
207
    running_recycle_tasks.erase(task_name);
7577
207
}
7578
7579
21
bool InstanceRecycler::check_recycle_tasks() {
7580
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7581
21
    {
7582
21
        std::lock_guard lock(recycle_tasks_mutex);
7583
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7584
21
    }
7585
7586
21
    bool found = false;
7587
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7588
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7589
20
        int64_t cost = now - start_time;
7590
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7591
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7592
20
                    .tag("instance_id", instance_id_)
7593
20
                    .tag("task", task_name);
7594
20
            found = true;
7595
20
        }
7596
20
    }
7597
7598
21
    return found;
7599
21
}
7600
7601
// Scan and statistics indexes that need to be recycled
7602
0
int InstanceRecycler::scan_and_statistics_indexes() {
7603
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7604
7605
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7606
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7607
0
    std::string index_key0;
7608
0
    std::string index_key1;
7609
0
    recycle_index_key(index_key_info0, &index_key0);
7610
0
    recycle_index_key(index_key_info1, &index_key1);
7611
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7612
7613
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7614
0
        RecycleIndexPB index_pb;
7615
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7616
0
            return 0;
7617
0
        }
7618
0
        int64_t current_time = ::time(nullptr);
7619
0
        if (current_time <
7620
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7621
0
            return 0;
7622
0
        }
7623
        // decode index_id
7624
0
        auto k1 = k;
7625
0
        k1.remove_prefix(1);
7626
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7627
0
        decode_key(&k1, &out);
7628
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7629
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7630
0
        std::unique_ptr<Transaction> txn;
7631
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7632
0
        if (err != TxnErrorCode::TXN_OK) {
7633
0
            return 0;
7634
0
        }
7635
0
        std::string val;
7636
0
        err = txn->get(k, &val);
7637
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7638
0
            return 0;
7639
0
        }
7640
0
        if (err != TxnErrorCode::TXN_OK) {
7641
0
            return 0;
7642
0
        }
7643
0
        index_pb.Clear();
7644
0
        if (!index_pb.ParseFromString(val)) {
7645
0
            return 0;
7646
0
        }
7647
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7648
0
            return 0;
7649
0
        }
7650
0
        metrics_context.total_need_recycle_num++;
7651
0
        return 0;
7652
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7653
7654
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7655
0
    metrics_context.report(true);
7656
0
    segment_metrics_context_.report(true);
7657
0
    tablet_metrics_context_.report(true);
7658
0
    return ret;
7659
0
}
7660
7661
// Scan and statistics partitions that need to be recycled
7662
0
int InstanceRecycler::scan_and_statistics_partitions() {
7663
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7664
7665
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7666
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7667
0
    std::string part_key0;
7668
0
    std::string part_key1;
7669
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7670
7671
0
    recycle_partition_key(part_key_info0, &part_key0);
7672
0
    recycle_partition_key(part_key_info1, &part_key1);
7673
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7674
0
        RecyclePartitionPB part_pb;
7675
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7676
0
            return 0;
7677
0
        }
7678
0
        int64_t current_time = ::time(nullptr);
7679
0
        if (current_time <
7680
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7681
0
            return 0;
7682
0
        }
7683
        // decode partition_id
7684
0
        auto k1 = k;
7685
0
        k1.remove_prefix(1);
7686
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7687
0
        decode_key(&k1, &out);
7688
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7689
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7690
        // Change state to RECYCLING
7691
0
        std::unique_ptr<Transaction> txn;
7692
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7693
0
        if (err != TxnErrorCode::TXN_OK) {
7694
0
            return 0;
7695
0
        }
7696
0
        std::string val;
7697
0
        err = txn->get(k, &val);
7698
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7699
0
            return 0;
7700
0
        }
7701
0
        if (err != TxnErrorCode::TXN_OK) {
7702
0
            return 0;
7703
0
        }
7704
0
        part_pb.Clear();
7705
0
        if (!part_pb.ParseFromString(val)) {
7706
0
            return 0;
7707
0
        }
7708
        // Partitions with PREPARED state MUST have no data
7709
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7710
0
        int ret = 0;
7711
0
        for (int64_t index_id : part_pb.index_id()) {
7712
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7713
0
                                            partition_id, is_empty_tablet) != 0) {
7714
0
                ret = 0;
7715
0
            }
7716
0
        }
7717
0
        metrics_context.total_need_recycle_num++;
7718
0
        return ret;
7719
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_
7720
7721
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7722
0
    metrics_context.report(true);
7723
0
    segment_metrics_context_.report(true);
7724
0
    tablet_metrics_context_.report(true);
7725
0
    return ret;
7726
0
}
7727
7728
// Scan and statistics rowsets that need to be recycled
7729
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7730
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7731
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7732
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7733
0
    std::string recyc_rs_key0;
7734
0
    std::string recyc_rs_key1;
7735
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7736
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7737
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7738
7739
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7740
0
        RecycleRowsetPB rowset;
7741
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7742
0
            return 0;
7743
0
        }
7744
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7745
0
        int64_t current_time = ::time(nullptr);
7746
0
        if (current_time <
7747
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7748
0
            return 0;
7749
0
        }
7750
7751
0
        if (!rowset.has_type()) {
7752
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7753
0
                return 0;
7754
0
            }
7755
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7756
0
                return 0;
7757
0
            }
7758
0
            metrics_context.total_need_recycle_num++;
7759
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7760
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7761
0
            segment_metrics_context_.total_need_recycle_data_size +=
7762
0
                    rowset.rowset_meta().total_disk_size();
7763
0
            return 0;
7764
0
        }
7765
7766
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7767
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7768
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7769
0
            return 0;
7770
0
        }
7771
7772
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7773
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7774
0
                return 0;
7775
0
            }
7776
0
        }
7777
0
        metrics_context.total_need_recycle_num++;
7778
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7779
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7780
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7781
0
        return 0;
7782
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_
7783
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7784
0
    metrics_context.report(true);
7785
0
    segment_metrics_context_.report(true);
7786
0
    return ret;
7787
0
}
7788
7789
// Scan and statistics tmp_rowsets that need to be recycled
7790
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7791
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7792
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7793
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7794
0
    std::string tmp_rs_key0;
7795
0
    std::string tmp_rs_key1;
7796
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7797
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7798
7799
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7800
7801
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7802
0
        doris::RowsetMetaCloudPB rowset;
7803
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7804
0
            return 0;
7805
0
        }
7806
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7807
0
        int64_t current_time = ::time(nullptr);
7808
0
        if (current_time < expiration) {
7809
0
            return 0;
7810
0
        }
7811
7812
0
        DCHECK_GT(rowset.txn_id(), 0)
7813
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7814
7815
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
7816
0
            return 0;
7817
0
        }
7818
7819
0
        if (!rowset.has_resource_id()) {
7820
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7821
0
                return 0;
7822
0
            }
7823
0
            return 0;
7824
0
        }
7825
7826
0
        metrics_context.total_need_recycle_num++;
7827
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7828
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7829
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7830
0
        return 0;
7831
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_
7832
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7833
0
    metrics_context.report(true);
7834
0
    segment_metrics_context_.report(true);
7835
0
    return ret;
7836
0
}
7837
7838
// Scan and statistics abort_timeout_txn that need to be recycled
7839
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7840
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7841
7842
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7843
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7844
0
    std::string begin_txn_running_key;
7845
0
    std::string end_txn_running_key;
7846
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7847
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7848
7849
0
    int64_t current_time =
7850
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7851
7852
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7853
0
                                               std::string_view k, std::string_view v) -> int {
7854
0
        std::unique_ptr<Transaction> txn;
7855
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7856
0
        if (err != TxnErrorCode::TXN_OK) {
7857
0
            return 0;
7858
0
        }
7859
0
        std::string_view k1 = k;
7860
0
        k1.remove_prefix(1);
7861
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7862
0
        if (decode_key(&k1, &out) != 0) {
7863
0
            return 0;
7864
0
        }
7865
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7866
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7867
        // Update txn_info
7868
0
        std::string txn_inf_key, txn_inf_val;
7869
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7870
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7871
0
        if (err != TxnErrorCode::TXN_OK) {
7872
0
            return 0;
7873
0
        }
7874
0
        TxnInfoPB txn_info;
7875
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7876
0
            return 0;
7877
0
        }
7878
7879
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7880
0
            TxnRunningPB txn_running_pb;
7881
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7882
0
                return 0;
7883
0
            }
7884
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7885
0
                return 0;
7886
0
            }
7887
0
            metrics_context.total_need_recycle_num++;
7888
0
        }
7889
0
        return 0;
7890
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_
7891
7892
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7893
0
                               std::move(handle_abort_timeout_txn_kv));
7894
0
    metrics_context.report(true);
7895
0
    return ret;
7896
0
}
7897
7898
// Scan and statistics expired_txn_label that need to be recycled
7899
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7900
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7901
7902
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7903
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7904
0
    std::string begin_recycle_txn_key;
7905
0
    std::string end_recycle_txn_key;
7906
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7907
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7908
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7909
0
    int64_t current_time_ms =
7910
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7911
7912
    // for calculate the total num or bytes of recyled objects
7913
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7914
0
        RecycleTxnPB recycle_txn_pb;
7915
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7916
0
            return 0;
7917
0
        }
7918
0
        if ((config::force_immediate_recycle) ||
7919
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7920
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7921
0
             current_time_ms)) {
7922
0
            metrics_context.total_need_recycle_num++;
7923
0
        }
7924
0
        return 0;
7925
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_
7926
7927
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7928
0
                               std::move(handle_expired_txn_label_kv));
7929
0
    metrics_context.report(true);
7930
0
    return ret;
7931
0
}
7932
7933
// Scan and statistics copy_jobs that need to be recycled
7934
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7935
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7936
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7937
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7938
0
    std::string key0;
7939
0
    std::string key1;
7940
0
    copy_job_key(key_info0, &key0);
7941
0
    copy_job_key(key_info1, &key1);
7942
7943
    // for calculate the total num or bytes of recyled objects
7944
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7945
0
        CopyJobPB copy_job;
7946
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7947
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7948
0
            return 0;
7949
0
        }
7950
7951
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7952
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7953
0
                int64_t current_time =
7954
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7955
0
                if (copy_job.finish_time_ms() > 0) {
7956
0
                    if (!config::force_immediate_recycle &&
7957
0
                        current_time < copy_job.finish_time_ms() +
7958
0
                                               config::copy_job_max_retention_second * 1000) {
7959
0
                        return 0;
7960
0
                    }
7961
0
                } else {
7962
0
                    if (!config::force_immediate_recycle &&
7963
0
                        current_time < copy_job.start_time_ms() +
7964
0
                                               config::copy_job_max_retention_second * 1000) {
7965
0
                        return 0;
7966
0
                    }
7967
0
                }
7968
0
            }
7969
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7970
0
            int64_t current_time =
7971
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7972
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7973
0
                return 0;
7974
0
            }
7975
0
        }
7976
0
        metrics_context.total_need_recycle_num++;
7977
0
        return 0;
7978
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_
7979
7980
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7981
0
    metrics_context.report(true);
7982
0
    return ret;
7983
0
}
7984
7985
// Scan and statistics stage that need to be recycled
7986
0
int InstanceRecycler::scan_and_statistics_stage() {
7987
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
7988
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7989
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7990
0
    std::string key0 = recycle_stage_key(key_info0);
7991
0
    std::string key1 = recycle_stage_key(key_info1);
7992
7993
    // for calculate the total num or bytes of recyled objects
7994
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
7995
0
                                                        std::string_view v) -> int {
7996
0
        RecycleStagePB recycle_stage;
7997
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7998
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7999
0
            return 0;
8000
0
        }
8001
8002
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8003
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8004
0
            LOG(WARNING) << "invalid idx: " << idx;
8005
0
            return 0;
8006
0
        }
8007
8008
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8009
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8010
0
                [&] {
8011
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8012
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8013
0
                    if (!s3_conf) {
8014
0
                        return 0;
8015
0
                    }
8016
8017
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8018
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8019
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8020
0
                    if (ret != 0) {
8021
0
                        return 0;
8022
0
                    }
8023
8024
0
                    accessor = std::move(s3_accessor);
8025
0
                    return 0;
8026
0
                }(),
8027
0
                "recycle_stage:get_accessor", &accessor);
8028
8029
0
        if (ret != 0) {
8030
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8031
0
            return 0;
8032
0
        }
8033
8034
0
        metrics_context.total_need_recycle_num++;
8035
0
        return 0;
8036
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_
8037
8038
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8039
0
    metrics_context.report(true);
8040
0
    return ret;
8041
0
}
8042
8043
// Scan and statistics expired_stage_objects that need to be recycled
8044
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8045
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8046
8047
    // for calculate the total num or bytes of recyled objects
8048
0
    auto scan_and_statistics = [&metrics_context, this]() {
8049
0
        for (const auto& stage : instance_info_.stages()) {
8050
0
            if (stopped()) {
8051
0
                break;
8052
0
            }
8053
0
            if (stage.type() == StagePB::EXTERNAL) {
8054
0
                continue;
8055
0
            }
8056
0
            int idx = stoi(stage.obj_info().id());
8057
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8058
0
                continue;
8059
0
            }
8060
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8061
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8062
0
            if (!s3_conf) {
8063
0
                continue;
8064
0
            }
8065
0
            s3_conf->prefix = stage.obj_info().prefix();
8066
0
            std::shared_ptr<S3Accessor> accessor;
8067
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8068
0
            if (ret1 != 0) {
8069
0
                continue;
8070
0
            }
8071
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8072
0
                continue;
8073
0
            }
8074
0
            metrics_context.total_need_recycle_num++;
8075
0
        }
8076
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8077
8078
0
    scan_and_statistics();
8079
0
    metrics_context.report(true);
8080
0
    return 0;
8081
0
}
8082
8083
// Scan and statistics versions that need to be recycled
8084
0
int InstanceRecycler::scan_and_statistics_versions() {
8085
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8086
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8087
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8088
8089
0
    int64_t last_scanned_table_id = 0;
8090
0
    bool is_recycled = false; // Is last scanned kv recycled
8091
    // for calculate the total num or bytes of recyled objects
8092
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8093
0
                                       std::string_view k, std::string_view) {
8094
0
        auto k1 = k;
8095
0
        k1.remove_prefix(1);
8096
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8097
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8098
0
        decode_key(&k1, &out);
8099
0
        DCHECK_EQ(out.size(), 6) << k;
8100
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8101
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8102
0
            metrics_context.total_need_recycle_num +=
8103
0
                    is_recycled; // Version kv of this table has been recycled
8104
0
            return 0;
8105
0
        }
8106
0
        last_scanned_table_id = table_id;
8107
0
        is_recycled = false;
8108
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8109
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8110
0
        std::unique_ptr<Transaction> txn;
8111
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8112
0
        if (err != TxnErrorCode::TXN_OK) {
8113
0
            return 0;
8114
0
        }
8115
0
        std::unique_ptr<RangeGetIterator> iter;
8116
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8117
0
        if (err != TxnErrorCode::TXN_OK) {
8118
0
            return 0;
8119
0
        }
8120
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8121
0
            return 0;
8122
0
        }
8123
0
        metrics_context.total_need_recycle_num++;
8124
0
        is_recycled = true;
8125
0
        return 0;
8126
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_
8127
8128
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8129
0
    metrics_context.report(true);
8130
0
    return ret;
8131
0
}
8132
8133
// Scan and statistics restore jobs that need to be recycled
8134
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8135
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8136
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8137
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8138
0
    std::string restore_job_key0;
8139
0
    std::string restore_job_key1;
8140
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8141
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8142
8143
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8144
8145
    // for calculate the total num or bytes of recyled objects
8146
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8147
0
        RestoreJobCloudPB restore_job_pb;
8148
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8149
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8150
0
            return 0;
8151
0
        }
8152
0
        int64_t expiration =
8153
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8154
0
        int64_t current_time = ::time(nullptr);
8155
0
        if (current_time < expiration) { // not expired
8156
0
            return 0;
8157
0
        }
8158
0
        metrics_context.total_need_recycle_num++;
8159
0
        if (restore_job_pb.need_recycle_data()) {
8160
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8161
0
        }
8162
0
        return 0;
8163
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_
8164
8165
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8166
0
    metrics_context.report(true);
8167
0
    return ret;
8168
0
}
8169
8170
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8171
3
    if (!should_recycle_versioned_keys()) {
8172
0
        return;
8173
0
    }
8174
8175
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8176
8177
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8178
3
    if (recycle_checker.init() != 0) {
8179
0
        return;
8180
0
    }
8181
8182
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8183
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8184
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8185
8186
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8187
8
    for (; iter->valid(); iter->next()) {
8188
5
        OperationLogPB operation_log;
8189
5
        if (!iter->parse_value(&operation_log)) {
8190
0
            continue;
8191
0
        }
8192
8193
5
        std::string_view key = iter->key();
8194
5
        Versionstamp log_versionstamp;
8195
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8196
0
            continue;
8197
0
        }
8198
8199
5
        OperationLogReferenceInfo ref_info;
8200
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8201
5
                                        &ref_info)) {
8202
4
            metrics_context.total_need_recycle_num++;
8203
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8204
4
        }
8205
5
    }
8206
8207
3
    metrics_context.report(true);
8208
3
}
8209
8210
int InstanceRecycler::classify_rowset_task_by_ref_count(
8211
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8212
60
    constexpr int MAX_RETRY = 10;
8213
60
    const auto& rowset_meta = task.rowset_meta;
8214
60
    int64_t tablet_id = rowset_meta.tablet_id();
8215
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8216
60
    std::string_view reference_instance_id = instance_id_;
8217
60
    if (rowset_meta.has_reference_instance_id()) {
8218
5
        reference_instance_id = rowset_meta.reference_instance_id();
8219
5
    }
8220
8221
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8222
61
        std::unique_ptr<Transaction> txn;
8223
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8224
61
        if (err != TxnErrorCode::TXN_OK) {
8225
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8226
0
                    .tag("instance_id", instance_id_)
8227
0
                    .tag("tablet_id", tablet_id)
8228
0
                    .tag("rowset_id", rowset_id)
8229
0
                    .tag("err", err);
8230
0
            return -1;
8231
0
        }
8232
8233
61
        std::string rowset_ref_count_key =
8234
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8235
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8236
8237
61
        int64_t ref_count = 0;
8238
61
        {
8239
61
            std::string value;
8240
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8241
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8242
0
                ref_count = 1;
8243
61
            } else if (err != TxnErrorCode::TXN_OK) {
8244
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8245
0
                        .tag("instance_id", instance_id_)
8246
0
                        .tag("tablet_id", tablet_id)
8247
0
                        .tag("rowset_id", rowset_id)
8248
0
                        .tag("err", err);
8249
0
                return -1;
8250
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8251
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8252
0
                        .tag("instance_id", instance_id_)
8253
0
                        .tag("tablet_id", tablet_id)
8254
0
                        .tag("rowset_id", rowset_id)
8255
0
                        .tag("value", hex(value));
8256
0
                return -1;
8257
0
            }
8258
61
        }
8259
8260
61
        if (ref_count > 1) {
8261
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8262
12
            txn->atomic_add(rowset_ref_count_key, -1);
8263
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8264
12
                    .tag("instance_id", instance_id_)
8265
12
                    .tag("tablet_id", tablet_id)
8266
12
                    .tag("rowset_id", rowset_id)
8267
12
                    .tag("ref_count", ref_count - 1)
8268
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8269
8270
12
            if (!task.recycle_rowset_key.empty()) {
8271
0
                txn->remove(task.recycle_rowset_key);
8272
0
                LOG_INFO("remove recycle rowset key in classification phase")
8273
0
                        .tag("key", hex(task.recycle_rowset_key));
8274
0
            }
8275
12
            if (!task.non_versioned_rowset_key.empty()) {
8276
12
                txn->remove(task.non_versioned_rowset_key);
8277
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8278
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8279
12
            }
8280
8281
12
            err = txn->commit();
8282
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8283
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8284
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8285
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8286
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8287
1
                continue;
8288
11
            } else if (err != TxnErrorCode::TXN_OK) {
8289
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8290
0
                        .tag("instance_id", instance_id_)
8291
0
                        .tag("tablet_id", tablet_id)
8292
0
                        .tag("rowset_id", rowset_id)
8293
0
                        .tag("err", err);
8294
0
                return -1;
8295
0
            }
8296
11
            return 1; // handled, not added to batch delete
8297
49
        } else {
8298
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8299
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8300
49
            LOG_INFO("add rowset to batch delete plan")
8301
49
                    .tag("instance_id", instance_id_)
8302
49
                    .tag("tablet_id", tablet_id)
8303
49
                    .tag("rowset_id", rowset_id)
8304
49
                    .tag("resource_id", rowset_meta.resource_id())
8305
49
                    .tag("ref_count", ref_count);
8306
8307
49
            batch_delete_tasks.push_back(std::move(task));
8308
49
            return 0; // added to batch delete
8309
49
        }
8310
61
    }
8311
8312
0
    LOG_WARNING("failed to classify rowset task after retry")
8313
0
            .tag("instance_id", instance_id_)
8314
0
            .tag("tablet_id", tablet_id)
8315
0
            .tag("rowset_id", rowset_id)
8316
0
            .tag("retry", MAX_RETRY);
8317
0
    return -1;
8318
60
}
8319
8320
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8321
10
    int ret = 0;
8322
49
    for (const auto& task : tasks) {
8323
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8324
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8325
8326
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8327
        // so we don't need to call it again here.
8328
8329
        // Remove all metadata keys in one transaction
8330
49
        std::unique_ptr<Transaction> txn;
8331
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8332
49
        if (err != TxnErrorCode::TXN_OK) {
8333
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8334
0
                    .tag("instance_id", instance_id_)
8335
0
                    .tag("tablet_id", tablet_id)
8336
0
                    .tag("rowset_id", rowset_id)
8337
0
                    .tag("err", err);
8338
0
            ret = -1;
8339
0
            continue;
8340
0
        }
8341
8342
49
        std::string_view reference_instance_id = instance_id_;
8343
49
        if (task.rowset_meta.has_reference_instance_id()) {
8344
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8345
0
        }
8346
8347
49
        txn->remove(task.rowset_ref_count_key);
8348
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8349
49
                .tag("instance_id", instance_id_)
8350
49
                .tag("tablet_id", tablet_id)
8351
49
                .tag("rowset_id", rowset_id)
8352
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8353
8354
49
        std::string dbm_start_key =
8355
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8356
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8357
49
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8358
49
                 std::numeric_limits<int64_t>::max()});
8359
49
        txn->remove(dbm_start_key, dbm_end_key);
8360
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8361
49
                .tag("instance_id", instance_id_)
8362
49
                .tag("tablet_id", tablet_id)
8363
49
                .tag("rowset_id", rowset_id)
8364
49
                .tag("begin", hex(dbm_start_key))
8365
49
                .tag("end", hex(dbm_end_key));
8366
8367
49
        std::string versioned_dbm_start_key =
8368
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8369
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8370
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8371
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8372
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8373
49
                .tag("instance_id", instance_id_)
8374
49
                .tag("tablet_id", tablet_id)
8375
49
                .tag("rowset_id", rowset_id)
8376
49
                .tag("begin", hex(versioned_dbm_start_key))
8377
49
                .tag("end", hex(versioned_dbm_end_key));
8378
8379
        // Remove versioned meta rowset key
8380
49
        if (!task.versioned_rowset_key.empty()) {
8381
49
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8382
49
                                                          task.versionstamp);
8383
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8384
49
                    .tag("instance_id", instance_id_)
8385
49
                    .tag("tablet_id", tablet_id)
8386
49
                    .tag("rowset_id", rowset_id)
8387
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8388
49
        }
8389
8390
49
        if (!task.non_versioned_rowset_key.empty()) {
8391
49
            txn->remove(task.non_versioned_rowset_key);
8392
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8393
49
                    .tag("instance_id", instance_id_)
8394
49
                    .tag("tablet_id", tablet_id)
8395
49
                    .tag("rowset_id", rowset_id)
8396
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8397
49
        }
8398
8399
        // Remove recycle_rowset_key last to ensure retry safety:
8400
        // if cleanup fails, this key remains and triggers next round retry.
8401
49
        if (!task.recycle_rowset_key.empty()) {
8402
0
            txn->remove(task.recycle_rowset_key);
8403
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8404
0
                    .tag("instance_id", instance_id_)
8405
0
                    .tag("tablet_id", tablet_id)
8406
0
                    .tag("rowset_id", rowset_id)
8407
0
                    .tag("key", hex(task.recycle_rowset_key));
8408
0
        }
8409
8410
49
        err = txn->commit();
8411
49
        if (err != TxnErrorCode::TXN_OK) {
8412
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8413
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8414
0
                    .tag("instance_id", instance_id_)
8415
0
                    .tag("tablet_id", tablet_id)
8416
0
                    .tag("rowset_id", rowset_id)
8417
0
                    .tag("err", err);
8418
0
            ret = -1;
8419
0
            continue;
8420
0
        }
8421
8422
49
        LOG_INFO("cleanup rowset metadata success")
8423
49
                .tag("instance_id", instance_id_)
8424
49
                .tag("tablet_id", tablet_id)
8425
49
                .tag("rowset_id", rowset_id);
8426
49
    }
8427
10
    return ret;
8428
10
}
8429
8430
} // namespace doris::cloud