Coverage Report

Created: 2026-10-28 20:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/rowset_segment_id.h"
73
#include "common/simple_thread_pool.h"
74
#include "common/util.h"
75
#include "cpp/sync_point.h"
76
#include "meta-store/codec.h"
77
#include "meta-store/document_message.h"
78
#include "meta-store/keys.h"
79
#include "recycler/recycler_service.h"
80
#include "recycler/sync_executor.h"
81
#include "recycler/util.h"
82
#include "snapshot/snapshot_manager_factory.h"
83
84
namespace doris::cloud {
85
86
using namespace std::chrono;
87
88
namespace {
89
90
constexpr size_t kRowsetBatchGetSize = 256;
91
92
0
int64_t packed_file_retry_sleep_ms() {
93
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
94
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
95
0
    thread_local std::mt19937_64 gen(std::random_device {}());
96
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
97
0
    return dist(gen);
98
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
99
100
0
void sleep_for_packed_file_retry() {
101
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
102
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
103
104
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
948k
    const auto& locations = rowset.packed_slice_locations();
106
948k
    auto it = locations.find(path);
107
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
948k
           !it->second.packed_file_path().empty();
109
948k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
7
    const auto& locations = rowset.packed_slice_locations();
106
7
    auto it = locations.find(path);
107
7
    return it != locations.end() && it->second.has_packed_file_path() &&
108
7
           !it->second.packed_file_path().empty();
109
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
948k
    const auto& locations = rowset.packed_slice_locations();
106
948k
    auto it = locations.find(path);
107
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
948k
           !it->second.packed_file_path().empty();
109
948k
}
110
111
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
112
                                      const std::string& path,
113
949k
                                      std::vector<std::string>* file_paths) {
114
949k
    if (!is_packed_slice_path(rowset, path)) {
115
920k
        file_paths->push_back(path);
116
920k
    }
117
949k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
7
                                      std::vector<std::string>* file_paths) {
114
7
    if (!is_packed_slice_path(rowset, path)) {
115
7
        file_paths->push_back(path);
116
7
    }
117
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
949k
                                      std::vector<std::string>* file_paths) {
114
949k
    if (!is_packed_slice_path(rowset, path)) {
115
920k
        file_paths->push_back(path);
116
920k
    }
117
949k
}
118
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
127
128
} // namespace
129
130
// return 0 for success get a key, 1 for key not found, negative for error
131
2.59k
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
2.59k
    std::unique_ptr<Transaction> txn;
133
2.59k
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
2.59k
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
2.59k
    switch (txn->get(key, &val, true)) {
138
35
    case TxnErrorCode::TXN_OK:
139
35
        return 0;
140
2.56k
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
2.56k
        return 1;
142
0
    default:
143
0
        return -1;
144
2.59k
    };
145
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
16
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
16
    std::unique_ptr<Transaction> txn;
133
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
16
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
16
    switch (txn->get(key, &val, true)) {
138
3
    case TxnErrorCode::TXN_OK:
139
3
        return 0;
140
13
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
13
        return 1;
142
0
    default:
143
0
        return -1;
144
16
    };
145
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
2.57k
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
2.57k
    std::unique_ptr<Transaction> txn;
133
2.57k
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
2.57k
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
2.57k
    switch (txn->get(key, &val, true)) {
138
32
    case TxnErrorCode::TXN_OK:
139
32
        return 0;
140
2.54k
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
2.54k
        return 1;
142
0
    default:
143
0
        return -1;
144
2.57k
    };
145
0
}
146
147
// 0 for success, negative for error
148
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
149
730
                   std::unique_ptr<RangeGetIterator>& it) {
150
730
    std::unique_ptr<Transaction> txn;
151
730
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
730
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
730
    switch (txn->get(begin, end, &it, true)) {
156
730
    case TxnErrorCode::TXN_OK:
157
730
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
730
    };
163
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
39
                   std::unique_ptr<RangeGetIterator>& it) {
150
39
    std::unique_ptr<Transaction> txn;
151
39
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
39
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
39
    switch (txn->get(begin, end, &it, true)) {
156
39
    case TxnErrorCode::TXN_OK:
157
39
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
39
    };
163
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
691
                   std::unique_ptr<RangeGetIterator>& it) {
150
691
    std::unique_ptr<Transaction> txn;
151
691
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
691
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
691
    switch (txn->get(begin, end, &it, true)) {
156
691
    case TxnErrorCode::TXN_OK:
157
691
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
691
    };
163
0
}
164
165
// return 0 for success otherwise error
166
22
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
22
    std::unique_ptr<Transaction> txn;
168
22
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
22
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
22
    switch (txn->commit()) {
176
22
    case TxnErrorCode::TXN_OK:
177
22
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
22
    }
183
22
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
5
    std::unique_ptr<Transaction> txn;
168
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
5
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
5
    for (auto k : keys) {
173
5
        txn->remove(k);
174
5
    }
175
5
    switch (txn->commit()) {
176
5
    case TxnErrorCode::TXN_OK:
177
5
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
5
    }
183
5
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
17
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
17
    std::unique_ptr<Transaction> txn;
168
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
17
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
17
    switch (txn->commit()) {
176
17
    case TxnErrorCode::TXN_OK:
177
17
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
17
    }
183
17
}
184
185
// return 0 for success otherwise error
186
10.9k
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
10.9k
    std::unique_ptr<Transaction> txn;
188
10.9k
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
10.9k
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
206k
    for (auto& k : keys) {
193
206k
        txn->remove(k);
194
206k
    }
195
10.9k
    switch (txn->commit()) {
196
10.9k
    case TxnErrorCode::TXN_OK:
197
10.9k
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
10.9k
    }
203
10.9k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
40
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
40
    std::unique_ptr<Transaction> txn;
188
40
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
40
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
40
    for (auto& k : keys) {
193
17
        txn->remove(k);
194
17
    }
195
40
    switch (txn->commit()) {
196
40
    case TxnErrorCode::TXN_OK:
197
40
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
40
    }
203
40
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
10.9k
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
10.9k
    std::unique_ptr<Transaction> txn;
188
10.9k
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
10.9k
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
206k
    for (auto& k : keys) {
193
206k
        txn->remove(k);
194
206k
    }
195
10.9k
    switch (txn->commit()) {
196
10.9k
    case TxnErrorCode::TXN_OK:
197
10.9k
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
10.9k
    }
203
10.9k
}
204
205
// return 0 for success otherwise error
206
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
207
142k
                                       std::string_view end) {
208
142k
    std::unique_ptr<Transaction> txn;
209
142k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
142k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
142k
    txn->remove(begin, end);
214
142k
    switch (txn->commit()) {
215
142k
    case TxnErrorCode::TXN_OK:
216
142k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
142k
    }
222
142k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
14
                                       std::string_view end) {
208
14
    std::unique_ptr<Transaction> txn;
209
14
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
14
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
14
    txn->remove(begin, end);
214
14
    switch (txn->commit()) {
215
14
    case TxnErrorCode::TXN_OK:
216
14
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
14
    }
222
14
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
142k
                                       std::string_view end) {
208
142k
    std::unique_ptr<Transaction> txn;
209
142k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
142k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
142k
    txn->remove(begin, end);
214
142k
    switch (txn->commit()) {
215
142k
    case TxnErrorCode::TXN_OK:
216
142k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
142k
    }
222
142k
}
223
224
// Remove versioned delete bitmap keys grouped by rowset.
225
// Each inner vector represents all DBM shard keys for one rowset that MUST be deleted
226
// atomically in the same txn. Transaction splitting only occurs between rowsets, never
227
// within a rowset's shard keys.
228
//
229
// This ensures that a DBM blob with multiple shards is either fully deleted or not
230
// deleted at all, preventing partial deletion that would leave the blob unrecoverable.
231
//
232
// return 0 for success otherwise error
233
static int delete_versioned_delete_bitmap_by_rowset(
234
54
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
54
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
53
    size_t idx = 0;
239
107
    while (idx < rowset_dbm_key_groups.size()) {
240
54
        std::unique_ptr<Transaction> txn;
241
54
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
54
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
54
        bool has_keys = false;
247
11.6k
        while (idx < rowset_dbm_key_groups.size()) {
248
11.5k
            const auto& keys = rowset_dbm_key_groups[idx];
249
11.5k
            const auto keys_bytes =
250
11.5k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
11.6k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
recycler_test.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
Line
Count
Source
251
11.6k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
11.5k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
11.6k
            for (const auto& key : keys) {
258
11.6k
                txn->remove(key);
259
11.6k
            }
260
261
11.5k
            has_keys = true;
262
11.5k
            ++idx;
263
11.5k
        }
264
265
54
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
54
        err = txn->commit();
267
54
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
54
    }
272
53
    return 0;
273
53
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
recycler_test.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
Line
Count
Source
234
54
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
54
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
53
    size_t idx = 0;
239
107
    while (idx < rowset_dbm_key_groups.size()) {
240
54
        std::unique_ptr<Transaction> txn;
241
54
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
54
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
54
        bool has_keys = false;
247
11.6k
        while (idx < rowset_dbm_key_groups.size()) {
248
11.5k
            const auto& keys = rowset_dbm_key_groups[idx];
249
11.5k
            const auto keys_bytes =
250
11.5k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
11.5k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
11.5k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
11.6k
            for (const auto& key : keys) {
258
11.6k
                txn->remove(key);
259
11.6k
            }
260
261
11.5k
            has_keys = true;
262
11.5k
            ++idx;
263
11.5k
        }
264
265
54
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
54
        err = txn->commit();
267
54
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
54
    }
272
53
    return 0;
273
53
}
274
275
void scan_restore_job_rowset(
276
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
277
        std::string& msg,
278
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
279
280
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
281
                                      int64_t num_scanned, int64_t num_recycled,
282
335
                                      int64_t start_time) {
283
335
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
335
    return;
295
335
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
5
                                      int64_t start_time) {
283
5
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
5
    return;
295
5
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
330
                                      int64_t start_time) {
283
330
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
330
    return;
295
330
}
296
297
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
298
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
299
300
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
301
6
                                                               "s3_producer_pool");
302
6
    s3_producer_pool->start();
303
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
304
6
                                                                  "recycle_tablet_pool");
305
6
    recycle_tablet_pool->start();
306
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
307
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
308
6
    group_recycle_function_pool->start();
309
6
    _thread_pool_group =
310
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
311
6
                                    std::move(group_recycle_function_pool));
312
313
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
314
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
315
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
316
6
}
317
318
6
Recycler::~Recycler() {
319
6
    if (!stopped()) {
320
0
        stop();
321
0
    }
322
6
}
323
324
5
void Recycler::instance_scanner_callback() {
325
    // sleep 60 seconds before scheduling for the launch procedure to complete:
326
    // some bad hdfs connection may cause some log to stdout stderr
327
    // which may pollute .out file and affect the script to check success
328
5
    std::this_thread::sleep_for(
329
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
330
711
    while (!stopped()) {
331
706
        if (config::enable_recycler) {
332
3
            std::vector<InstanceInfoPB> instances;
333
3
            get_all_instances(txn_kv_.get(), instances);
334
            // TODO(plat1ko): delete job recycle kv of non-existent instances
335
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
3
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
3
                return ss.str();
339
3
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
335
3
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
3
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
3
                return ss.str();
339
3
            }();
340
3
            if (!instances.empty()) {
341
                // enqueue instances
342
3
                std::lock_guard lock(mtx_);
343
30
                for (auto& instance : instances) {
344
30
                    if (filter_out_instance(instance.instance_id())) continue;
345
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
346
                    // skip instance already in pending queue
347
30
                    if (success) {
348
30
                        pending_instance_queue_.push_back(std::move(instance));
349
30
                    }
350
30
                }
351
3
                pending_instance_cond_.notify_all();
352
3
            }
353
703
        } else {
354
703
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
355
703
        }
356
706
        {
357
706
            std::unique_lock lock(mtx_);
358
706
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
359
1.41k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
359
1.41k
                               [&]() { return stopped(); });
360
706
        }
361
706
    }
362
5
}
363
364
9
void Recycler::recycle_callback() {
365
40
    while (!stopped()) {
366
37
        InstanceInfoPB instance;
367
37
        {
368
37
            std::unique_lock lock(mtx_);
369
37
            pending_instance_cond_.wait(
370
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
370
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
371
37
            if (stopped()) {
372
6
                return;
373
6
            }
374
31
            instance = std::move(pending_instance_queue_.front());
375
31
            pending_instance_queue_.pop_front();
376
31
            pending_instance_set_.erase(instance.instance_id());
377
31
        }
378
0
        auto& instance_id = instance.instance_id();
379
31
        {
380
31
            std::lock_guard lock(mtx_);
381
            // skip instance in recycling
382
31
            if (recycling_instance_map_.count(instance_id)) continue;
383
31
        }
384
31
        if (!config::enable_recycler) {
385
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
386
1
                         << " since enable_recycler is false";
387
1
            continue;
388
1
        }
389
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
390
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
391
392
30
        if (int r = instance_recycler->init(); r != 0) {
393
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
394
0
                         << " ret=" << r;
395
0
            continue;
396
0
        }
397
30
        std::string recycle_job_key;
398
30
        job_recycle_key({instance_id}, &recycle_job_key);
399
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
400
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
401
30
        if (ret != 0) { // Prepare failed
402
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
403
20
                         << " ret=" << ret;
404
20
            continue;
405
20
        } else {
406
10
            std::lock_guard lock(mtx_);
407
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
408
10
        }
409
10
        if (stopped()) return;
410
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
411
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
412
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
413
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
414
10
        ret = instance_recycler->do_recycle();
415
        // If instance recycler has been aborted, don't finish this job
416
417
10
        if (!instance_recycler->stopped()) {
418
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
419
10
                                        ret == 0, ctime_ms);
420
10
        }
421
10
        if (instance_recycler->stopped() || ret != 0) {
422
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
423
0
        }
424
10
        {
425
10
            std::lock_guard lock(mtx_);
426
10
            recycling_instance_map_.erase(instance_id);
427
10
        }
428
429
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
430
10
        auto elpased_ms = now - ctime_ms;
431
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
432
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
433
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
434
10
                                             now + config::recycle_interval_seconds * 1000);
435
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
436
10
        LOG(INFO) << "recycle instance done, "
437
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
438
10
                  << " now: " << now;
439
440
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
441
442
10
        LOG_WARNING("finish recycle instance")
443
10
                .tag("instance_id", instance_id)
444
10
                .tag("cost_ms", elpased_ms);
445
10
    }
446
9
}
447
448
4
void Recycler::lease_recycle_jobs() {
449
54
    while (!stopped()) {
450
50
        std::vector<std::string> instances;
451
50
        instances.reserve(recycling_instance_map_.size());
452
50
        {
453
50
            std::lock_guard lock(mtx_);
454
50
            for (auto& [id, _] : recycling_instance_map_) {
455
30
                instances.push_back(id);
456
30
            }
457
50
        }
458
50
        for (auto& i : instances) {
459
30
            std::string recycle_job_key;
460
30
            job_recycle_key({i}, &recycle_job_key);
461
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
462
30
            if (ret == 1) {
463
0
                std::lock_guard lock(mtx_);
464
0
                if (auto it = recycling_instance_map_.find(i);
465
0
                    it != recycling_instance_map_.end()) {
466
0
                    it->second->stop();
467
0
                }
468
0
            }
469
30
        }
470
50
        {
471
50
            std::unique_lock lock(mtx_);
472
50
            notifier_.wait_for(lock,
473
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
474
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
474
100
                               [&]() { return stopped(); });
475
50
        }
476
50
    }
477
4
}
478
479
4
void Recycler::check_recycle_tasks() {
480
7
    while (!stopped()) {
481
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
482
3
        {
483
3
            std::lock_guard lock(mtx_);
484
3
            recycling_instance_map = recycling_instance_map_;
485
3
        }
486
3
        for (auto& entry : recycling_instance_map) {
487
0
            entry.second->check_recycle_tasks();
488
0
        }
489
490
3
        std::unique_lock lock(mtx_);
491
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
492
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
492
6
                           [&]() { return stopped(); });
493
3
    }
494
4
}
495
496
4
int Recycler::start(brpc::Server* server) {
497
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
498
4
    S3Environment::getInstance();
499
500
4
    if (config::enable_checker) {
501
0
        checker_ = std::make_unique<Checker>(txn_kv_);
502
0
        int ret = checker_->start();
503
0
        std::string msg;
504
0
        if (ret != 0) {
505
0
            msg = "failed to start checker";
506
0
            LOG(ERROR) << msg;
507
0
            std::cerr << msg << std::endl;
508
0
            return ret;
509
0
        }
510
0
        msg = "checker started";
511
0
        LOG(INFO) << msg;
512
0
        std::cout << msg << std::endl;
513
0
    }
514
515
4
    if (server) {
516
        // Add service
517
1
        auto recycler_service =
518
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
519
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
520
1
    }
521
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
523
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
524
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
524
8
        workers_.emplace_back([this] { recycle_callback(); });
525
8
    }
526
527
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
528
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
529
530
4
    if (config::enable_snapshot_data_migrator) {
531
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
532
0
        int ret = snapshot_data_migrator_->start();
533
0
        if (ret != 0) {
534
0
            LOG(ERROR) << "failed to start snapshot data migrator";
535
0
            return ret;
536
0
        }
537
0
        LOG(INFO) << "snapshot data migrator started";
538
0
    }
539
540
4
    if (config::enable_snapshot_chain_compactor) {
541
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
542
0
        int ret = snapshot_chain_compactor_->start();
543
0
        if (ret != 0) {
544
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
545
0
            return ret;
546
0
        }
547
0
        LOG(INFO) << "snapshot chain compactor started";
548
0
    }
549
550
4
    return 0;
551
4
}
552
553
4
void Recycler::stop() {
554
4
    stopped_ = true;
555
4
    notifier_.notify_all();
556
4
    pending_instance_cond_.notify_all();
557
4
    {
558
4
        std::lock_guard lock(mtx_);
559
4
        for (auto& [_, recycler] : recycling_instance_map_) {
560
0
            recycler->stop();
561
0
        }
562
4
    }
563
20
    for (auto& w : workers_) {
564
20
        if (w.joinable()) w.join();
565
20
    }
566
4
    if (checker_) {
567
0
        checker_->stop();
568
0
    }
569
4
    if (snapshot_data_migrator_) {
570
0
        snapshot_data_migrator_->stop();
571
0
    }
572
4
    if (snapshot_chain_compactor_) {
573
0
        snapshot_chain_compactor_->stop();
574
0
    }
575
4
}
576
577
class InstanceRecycler::InvertedIndexIdCache {
578
public:
579
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
580
189
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
581
582
    // Return 0 if success, 1 if schema kv not found, negative for error
583
    // For the same index_id, schema_version, res, since `get` is not completely atomic
584
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
585
    // resulting in repeated addition and inaccuracy.
586
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
587
    // repeated addition does not affect correctness.
588
68.3k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
589
68.3k
        {
590
68.3k
            std::lock_guard lock(mtx_);
591
68.3k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
592
4.67k
                return 0;
593
4.67k
            }
594
63.6k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
595
63.6k
                it != inverted_index_id_map_.end()) {
596
53.1k
                res = it->second;
597
53.1k
                return 0;
598
53.1k
            }
599
63.6k
        }
600
        // Get schema from kv
601
        // TODO(plat1ko): Single flight
602
10.4k
        std::unique_ptr<Transaction> txn;
603
10.4k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
604
10.4k
        if (err != TxnErrorCode::TXN_OK) {
605
0
            LOG(WARNING) << "failed to create txn, err=" << err;
606
0
            return -1;
607
0
        }
608
10.4k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
609
10.4k
        ValueBuf val_buf;
610
10.4k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
611
10.4k
        if (err != TxnErrorCode::TXN_OK) {
612
5.49k
            LOG(WARNING) << "failed to get schema, err=" << err;
613
5.49k
            return static_cast<int>(err);
614
5.49k
        }
615
4.99k
        doris::TabletSchemaCloudPB schema;
616
4.99k
        if (!parse_schema_value(val_buf, &schema)) {
617
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
618
0
            return -1;
619
0
        }
620
4.99k
        if (schema.index_size() > 0) {
621
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
622
4.01k
            if (schema.has_inverted_index_storage_format()) {
623
4.00k
                index_format = schema.inverted_index_storage_format();
624
4.00k
            }
625
4.01k
            res.first = index_format;
626
4.01k
            res.second.reserve(schema.index_size());
627
10.0k
            for (auto& i : schema.index()) {
628
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
629
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
630
10.0k
                }
631
10.0k
            }
632
4.01k
        }
633
4.99k
        insert(index_id, schema_version, res);
634
4.99k
        return 0;
635
4.99k
    }
636
637
    // Empty `ids` means this schema has no inverted index
638
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
639
5.04k
        if (index_info.second.empty()) {
640
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
641
1.02k
            std::lock_guard lock(mtx_);
642
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
643
4.01k
        } else {
644
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
645
4.01k
            std::lock_guard lock(mtx_);
646
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
647
4.01k
        }
648
5.04k
    }
649
650
private:
651
    std::string instance_id_;
652
    std::shared_ptr<TxnKv> txn_kv_;
653
654
    std::mutex mtx_;
655
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
656
    struct HashOfKey {
657
137k
        size_t operator()(const Key& key) const {
658
137k
            size_t seed = 0;
659
137k
            seed = std::hash<int64_t> {}(key.first);
660
137k
            seed = std::hash<int32_t> {}(key.second);
661
137k
            return seed;
662
137k
        }
663
    };
664
    // <index_id, schema_version> -> inverted_index_ids
665
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
666
    // Store <index_id, schema_version> of schema which doesn't have inverted index
667
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
668
};
669
670
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
671
                                   RecyclerThreadPoolGroup thread_pool_group,
672
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
673
189
        : txn_kv_(std::move(txn_kv)),
674
189
          instance_id_(instance.instance_id()),
675
189
          instance_info_(instance),
676
189
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
677
189
          _thread_pool_group(std::move(thread_pool_group)),
678
189
          txn_lazy_committer_(std::move(txn_lazy_committer)),
679
189
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
680
189
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
681
189
    delete_bitmap_lock_white_list_->init();
682
189
    resource_mgr_->init();
683
684
189
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
685
686
    // Since the recycler's resource manager could not be notified when instance info changes,
687
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
688
189
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
689
189
};
690
691
189
InstanceRecycler::~InstanceRecycler() = default;
692
693
155
int InstanceRecycler::init_obj_store_accessors() {
694
155
    for (const auto& obj_info : instance_info_.obj_info()) {
695
107
#ifdef UNIT_TEST
696
107
        auto accessor = std::make_shared<MockAccessor>();
697
#else
698
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
699
        if (!s3_conf) {
700
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
701
            return -1;
702
        }
703
704
        std::shared_ptr<S3Accessor> accessor;
705
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
706
        if (ret != 0) {
707
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
708
                         << " resource_id=" << obj_info.id();
709
            return ret;
710
        }
711
#endif
712
107
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
713
107
    }
714
715
155
    return 0;
716
155
}
717
718
155
int InstanceRecycler::init_storage_vault_accessors() {
719
155
    if (instance_info_.resource_ids().empty()) {
720
148
        return 0;
721
148
    }
722
723
7
    FullRangeGetOptions opts(txn_kv_);
724
7
    opts.prefetch = true;
725
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
726
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
727
728
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
729
18
        auto [k, v] = *kv;
730
18
        StorageVaultPB vault;
731
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
732
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
733
0
            return -1;
734
0
        }
735
18
        std::string recycler_storage_vault_white_list = accumulate(
736
18
                config::recycler_storage_vault_white_list.begin(),
737
18
                config::recycler_storage_vault_white_list.end(), std::string(),
738
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
738
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
739
18
        LOG_INFO("config::recycler_storage_vault_white_list")
740
18
                .tag("", recycler_storage_vault_white_list);
741
18
        if (!config::recycler_storage_vault_white_list.empty()) {
742
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
743
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
744
8
                it == config::recycler_storage_vault_white_list.end()) {
745
2
                LOG_WARNING(
746
2
                        "failed to init accessor for vault because this vault is not in "
747
2
                        "config::recycler_storage_vault_white_list. ")
748
2
                        .tag(" vault name:", vault.name())
749
2
                        .tag(" config::recycler_storage_vault_white_list:",
750
2
                             recycler_storage_vault_white_list);
751
2
                continue;
752
2
            }
753
8
        }
754
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
755
16
                                 &accessor_map_, &vault);
756
16
        if (vault.has_hdfs_info()) {
757
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
758
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
759
9
            int ret = accessor->init();
760
9
            if (ret != 0) {
761
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
762
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
763
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
764
4
                continue;
765
4
            }
766
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
767
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
768
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
769
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
770
#else
771
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
772
                       << "but HDFS storage vaults were detected";
773
#endif
774
7
        } else if (vault.has_obj_info()) {
775
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
776
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
777
7
            if (!s3_conf) {
778
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
779
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
780
1
                continue;
781
1
            }
782
783
6
            std::shared_ptr<S3Accessor> accessor;
784
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
785
6
            if (ret != 0) {
786
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
787
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
788
0
                             << " ret=" << ret
789
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
790
0
                continue;
791
0
            }
792
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
793
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
794
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
795
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
796
6
        }
797
16
    }
798
799
7
    if (!it->is_valid()) {
800
0
        LOG_WARNING("failed to get storage vault kv");
801
0
        return -1;
802
0
    }
803
804
7
    if (accessor_map_.empty()) {
805
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
806
1
        return -2;
807
1
    }
808
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
809
6
             instance_id_);
810
811
6
    return 0;
812
7
}
813
814
156
int InstanceRecycler::init() {
815
156
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
816
156
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
817
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
818
1
        return 0;
819
1
    }
820
821
155
    int ret = init_obj_store_accessors();
822
155
    if (ret != 0) {
823
0
        return ret;
824
0
    }
825
826
155
    return init_storage_vault_accessors();
827
155
}
828
829
template <typename... Func>
830
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
120
    return [funcs...]() {
832
120
        return [](std::initializer_list<int> ret_vals) {
833
120
            int i = 0;
834
140
            for (int ret : ret_vals) {
835
140
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
140
            }
839
120
            return i;
840
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
843
844
11
int InstanceRecycler::do_recycle() {
845
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
846
11
    tablet_metrics_context_.reset();
847
11
    segment_metrics_context_.reset();
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
852
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
853
1
        int res = recycle_cluster_snapshots();
854
1
        if (res != 0) {
855
0
            return -1;
856
0
        }
857
1
        return recycle_deleted_instance();
858
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
859
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
860
10
                                        fmt::format("instance id {}", instance_id_),
861
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
861
120
                                        [](int r) { return r != 0; });
862
10
        sync_executor
863
10
                .add(task_wrapper(
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
865
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
865
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
866
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
867
                                   // becase they may both recycle the same set of tablets
868
                        // recycle dropped table or idexes(mv, rollup)
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
870
                        // recycle dropped partitions
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
872
10
                .add(task_wrapper(
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
874
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
874
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
877
10
                .add(task_wrapper(
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
880
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
880
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
882
10
                .add(task_wrapper(
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
885
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
885
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
886
10
        bool finished = true;
887
10
        std::vector<int> rets = sync_executor.when_all(&finished);
888
120
        for (int ret : rets) {
889
120
            if (ret != 0) {
890
0
                return ret;
891
0
            }
892
120
        }
893
10
        return finished ? 0 : -1;
894
10
    } else {
895
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
896
0
                     << " instance_id=" << instance_id_;
897
0
        return -1;
898
0
    }
899
11
}
900
901
/**
902
* 1. delete all remote data
903
* 2. delete all kv
904
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
905
*/
906
13
int InstanceRecycler::recycle_deleted_instance() {
907
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
908
909
13
    int ret = 0;
910
13
    auto start_time = steady_clock::now();
911
13
    const auto recycle_state = instance_info_.recycle_state();
912
913
13
    if (config::retain_deleted_instance_tombstone &&
914
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
915
4
        return 0;
916
4
    }
917
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
934
935
9
    switch (recycle_state) {
936
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
937
6
        ret = recycle_deleted_instance_data();
938
6
        break;
939
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
940
3
        ret = recycle_deleted_instance_metadata();
941
3
        break;
942
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
943
0
        ret = remove_instance_key();
944
0
        break;
945
0
    default:
946
0
        LOG_WARNING("invalid instance recycle state")
947
0
                .tag("instance_id", instance_id_)
948
0
                .tag("recycle_state", instance_info_.recycle_state());
949
0
        ret = -1;
950
0
        break;
951
9
    }
952
953
9
    return ret;
954
9
}
955
956
6
int InstanceRecycler::recycle_deleted_instance_data() {
957
6
    int ret = 0;
958
959
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
971
972
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
973
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
974
0
        return -1;
975
0
    }
976
977
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
978
6
    if (recycle_versioned_rowsets() != 0) {
979
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
980
0
        return -1;
981
0
    }
982
983
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
984
6
    if (recycle_operation_logs() != 0) {
985
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
986
0
        return -1;
987
0
    }
988
989
    // Step 4: Check if there are still cluster snapshots
990
6
    bool has_snapshots = false;
991
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
992
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
993
0
        return -1;
994
6
    } else if (has_snapshots) {
995
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
996
1
        return 0;
997
1
    }
998
999
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
1000
5
                            instance_info().snapshot_switch_status() !=
1001
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1002
5
    if (snapshot_enabled) {
1003
1
        bool has_unrecycled_rowsets = false;
1004
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1005
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1006
0
            return -1;
1007
1
        } else if (has_unrecycled_rowsets) {
1008
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1009
0
                    .tag("instance_id", instance_id_);
1010
0
            return ret;
1011
0
        }
1012
4
    } else { // delete all remote data if snapshot is disabled
1013
4
        for (auto& [_, accessor] : accessor_map_) {
1014
4
            if (stopped()) {
1015
0
                return ret;
1016
0
            }
1017
1018
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1019
4
            int del_ret = accessor->delete_all();
1020
4
            if (del_ret == 0) {
1021
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1022
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1023
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1024
                // so the recycling has been successful.
1025
0
                ret = -1;
1026
0
            }
1027
4
        }
1028
1029
4
        if (ret != 0) {
1030
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1031
0
            return ret;
1032
0
        }
1033
4
    }
1034
1035
5
    if (update_instance_recycle_state(
1036
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1037
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1038
0
        return -1;
1039
0
    }
1040
1041
5
    return 0;
1042
5
}
1043
1044
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1045
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1046
7
    if (instance_info_.has_successor_instance_id() &&
1047
7
        !instance_info_.successor_instance_id().empty()) {
1048
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1049
4
        std::unique_ptr<Transaction> txn;
1050
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1051
4
        if (err != TxnErrorCode::TXN_OK) {
1052
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1053
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1054
0
                         << " err=" << err;
1055
0
            return -1;
1056
0
        }
1057
1058
4
        InstanceInfoPB successor_instance;
1059
4
        std::string value;
1060
4
        err = txn->get(key, &value);
1061
4
        if (err == TxnErrorCode::TXN_OK) {
1062
3
            InstanceInfoPB successor_instance;
1063
3
            if (!successor_instance.ParseFromString(value)) {
1064
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1065
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1066
0
                return -1;
1067
0
            }
1068
3
            if (!successor_instance.has_recycle_state() ||
1069
3
                successor_instance.recycle_state() !=
1070
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1071
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1072
2
                          << " instance_id=" << instance_id_
1073
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1074
2
                          << " successor_status=" << successor_instance.status()
1075
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1076
2
                return 0;
1077
2
            }
1078
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1079
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1080
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1081
0
                         << " err=" << err;
1082
0
            return -1;
1083
0
        }
1084
4
    }
1085
1086
    // delete all kv
1087
5
    std::unique_ptr<Transaction> txn;
1088
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1089
5
    if (err != TxnErrorCode::TXN_OK) {
1090
0
        LOG(WARNING) << "failed to create txn";
1091
0
        return -1;
1092
0
    }
1093
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1094
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1095
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1096
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1097
5
    txn->remove(start_txn_key, end_txn_key);
1098
5
    std::string start_version_key = version_key_prefix(instance_id_);
1099
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_version_key, end_version_key);
1101
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1102
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_meta_key, end_meta_key);
1104
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1105
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1106
5
    txn->remove(start_recycle_key, end_recycle_key);
1107
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1108
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1109
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1110
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1111
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1112
5
    txn->remove(start_copy_key, end_copy_key);
1113
    // should not remove job key range, because we need to reserve job recycle kv
1114
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1115
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1116
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1117
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1118
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1119
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1120
5
    std::string start_vault_key = storage_vault_key(key_info0);
1121
5
    std::string end_vault_key = storage_vault_key(key_info1);
1122
5
    txn->remove(start_vault_key, end_vault_key);
1123
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1124
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1125
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1126
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1127
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1129
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1130
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1132
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1133
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1135
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1136
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1138
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1139
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1140
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1141
1142
    // Updating the recycle state also commits this transaction, making the metadata deletions
1143
    // and state transition atomic.
1144
5
    if (update_instance_recycle_state(
1145
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1146
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1147
0
        return -1;
1148
0
    }
1149
1150
5
    return 0;
1151
5
}
1152
1153
0
int InstanceRecycler::remove_instance_key() {
1154
0
    std::unique_ptr<Transaction> txn;
1155
0
    std::string key = instance_key(instance_info_.instance_id());
1156
0
    std::string value;
1157
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1158
0
    if (err != TxnErrorCode::TXN_OK) {
1159
0
        LOG(WARNING) << "failed to create txn";
1160
0
        return -1;
1161
0
    }
1162
1163
0
    err = txn->get(key, &value);
1164
0
    if (err != TxnErrorCode::TXN_OK) {
1165
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1166
0
                     << ", err=" << err;
1167
0
        return -1;
1168
0
    }
1169
1170
0
    InstanceInfoPB instance;
1171
0
    if (!instance.ParseFromString(value)) {
1172
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1173
0
        return -1;
1174
0
    }
1175
1176
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1177
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1178
0
                     << instance_id_ << ", status=" << instance.status();
1179
0
        return -1;
1180
0
    }
1181
1182
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1183
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1184
0
                     << instance_id_
1185
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1186
0
                     << ", expected_state="
1187
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1188
0
        return -1;
1189
0
    }
1190
1191
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1192
0
    txn->remove(key);
1193
0
    err = txn->commit();
1194
0
    if (err != TxnErrorCode::TXN_OK) {
1195
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1196
0
                     << " err=" << err;
1197
0
        return -1;
1198
0
    }
1199
0
    return 0;
1200
0
}
1201
1202
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1203
7
                                                    InstanceRecycleState target_state) {
1204
7
    std::unique_ptr<Transaction> txn;
1205
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1206
7
    if (err != TxnErrorCode::TXN_OK) {
1207
0
        LOG(WARNING) << "failed to create txn";
1208
0
        return -1;
1209
0
    }
1210
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1211
7
}
1212
1213
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1214
                                                    InstanceRecycleState target_state,
1215
12
                                                    Transaction* txn) {
1216
12
    const bool valid_transition =
1217
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1218
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1219
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1220
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1221
1222
12
    if (!valid_transition) {
1223
1
        LOG_WARNING("invalid instance recycled state transition")
1224
1
                .tag("instance_id", instance_id_)
1225
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1226
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1227
1
        return -1;
1228
1
    }
1229
1230
11
    std::string key = instance_key({instance_id_});
1231
11
    std::string value;
1232
11
    TxnErrorCode err = txn->get(key, &value);
1233
11
    if (err != TxnErrorCode::TXN_OK) {
1234
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1235
0
                .tag("instance_id", instance_id_)
1236
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1237
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1238
0
                .tag("err", err);
1239
0
        return -1;
1240
0
    }
1241
1242
11
    InstanceInfoPB instance;
1243
11
    if (!instance.ParseFromString(value)) {
1244
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1245
0
                .tag("instance_id", instance_id_)
1246
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1247
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1248
0
        return -1;
1249
0
    }
1250
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1251
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1252
0
                .tag("instance_id", instance_id_)
1253
0
                .tag("status", instance.status())
1254
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1255
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1256
0
        return -1;
1257
0
    }
1258
11
    if (instance.recycle_state() != current_state) {
1259
1
        LOG_WARNING("instance recycled state changed before update")
1260
1
                .tag("instance_id", instance_id_)
1261
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1262
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1263
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1264
1
        return -1;
1265
1
    }
1266
1267
10
    instance.set_recycle_state(target_state);
1268
10
    instance.set_recycle_state_update_time_ms(
1269
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1270
10
    if (!instance.SerializeToString(&value)) {
1271
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1272
0
                .tag("instance_id", instance_id_)
1273
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1274
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1275
0
        return -1;
1276
0
    }
1277
1278
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1279
10
    txn->put(key, value);
1280
10
    err = txn->commit();
1281
10
    if (err != TxnErrorCode::TXN_OK) {
1282
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1283
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1284
0
        return -1;
1285
0
    }
1286
1287
10
    instance_info_.Swap(&instance);
1288
10
    LOG_INFO("updated instance recycled state")
1289
10
            .tag("instance_id", instance_id_)
1290
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1291
10
    return 0;
1292
10
}
1293
1294
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1295
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1296
9
    if (exists == nullptr) {
1297
0
        return -1;
1298
0
    }
1299
9
    *exists = false;
1300
1301
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1302
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1303
9
    std::string scan_begin = begin;
1304
1305
9
    while (true) {
1306
9
        std::unique_ptr<RangeGetIterator> it_range;
1307
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1308
9
        if (get_ret < 0) {
1309
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1310
0
                    .tag("instance_id", instance_id_)
1311
0
                    .tag("tablet_id", tablet_id)
1312
0
                    .tag("ret", get_ret);
1313
0
            return -1;
1314
0
        }
1315
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1316
6
            return 0;
1317
6
        }
1318
1319
3
        std::string last_key;
1320
3
        while (it_range->has_next()) {
1321
3
            auto [k, v] = it_range->next();
1322
3
            last_key.assign(k.data(), k.size());
1323
3
            doris::RowsetMetaCloudPB rowset_meta;
1324
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1325
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1326
0
                        .tag("instance_id", instance_id_)
1327
0
                        .tag("tablet_id", tablet_id)
1328
0
                        .tag("key", hex(k));
1329
0
                continue;
1330
0
            }
1331
3
            if (stats) {
1332
3
                ++stats->rowset_scan_count;
1333
3
            }
1334
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1335
3
                *exists = true;
1336
3
                return 0;
1337
3
            }
1338
3
        }
1339
1340
0
        if (!it_range->more()) {
1341
0
            return 0;
1342
0
        }
1343
1344
        // Continue scanning from the next key to keep each transaction short.
1345
0
        scan_begin = std::move(last_key);
1346
0
        scan_begin.push_back('\x00');
1347
0
    }
1348
9
}
1349
1350
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1351
                                                          const std::string& rowset_id,
1352
                                                          int64_t txn_id, bool* recycle_exists,
1353
11
                                                          bool* tmp_exists) {
1354
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1355
0
        return -1;
1356
0
    }
1357
11
    *recycle_exists = false;
1358
11
    *tmp_exists = false;
1359
1360
11
    if (txn_id <= 0) {
1361
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1362
0
                .tag("instance_id", instance_id_)
1363
0
                .tag("tablet_id", tablet_id)
1364
0
                .tag("rowset_id", rowset_id)
1365
0
                .tag("txn_id", txn_id);
1366
0
        return -1;
1367
0
    }
1368
1369
11
    std::unique_ptr<Transaction> txn;
1370
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
11
    if (err != TxnErrorCode::TXN_OK) {
1372
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1373
0
                .tag("instance_id", instance_id_)
1374
0
                .tag("tablet_id", tablet_id)
1375
0
                .tag("rowset_id", rowset_id)
1376
0
                .tag("txn_id", txn_id)
1377
0
                .tag("err", err);
1378
0
        return -1;
1379
0
    }
1380
1381
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1382
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1383
11
    if (ret == TxnErrorCode::TXN_OK) {
1384
1
        *recycle_exists = true;
1385
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1386
0
        LOG_WARNING("failed to check recycle rowset existence")
1387
0
                .tag("instance_id", instance_id_)
1388
0
                .tag("tablet_id", tablet_id)
1389
0
                .tag("rowset_id", rowset_id)
1390
0
                .tag("key", hex(recycle_key))
1391
0
                .tag("err", ret);
1392
0
        return -1;
1393
0
    }
1394
1395
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1396
11
    ret = key_exists(txn.get(), tmp_key, true);
1397
11
    if (ret == TxnErrorCode::TXN_OK) {
1398
1
        *tmp_exists = true;
1399
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1400
0
        LOG_WARNING("failed to check tmp rowset existence")
1401
0
                .tag("instance_id", instance_id_)
1402
0
                .tag("tablet_id", tablet_id)
1403
0
                .tag("txn_id", txn_id)
1404
0
                .tag("key", hex(tmp_key))
1405
0
                .tag("err", ret);
1406
0
        return -1;
1407
0
    }
1408
1409
11
    return 0;
1410
11
}
1411
1412
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1413
7.50k
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1414
7.50k
    if (!hint.empty()) {
1415
7.49k
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1416
7.49k
            return {hint, it->second};
1417
7.49k
        }
1418
7.49k
    }
1419
1420
1
    return {"", nullptr};
1421
7.50k
}
1422
1423
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1424
                                               const std::string& packed_file_path,
1425
3
                                               PackedFileRecycleStats* stats) {
1426
3
    bool local_changed = false;
1427
3
    int64_t left_num = 0;
1428
3
    int64_t left_bytes = 0;
1429
3
    bool all_small_files_confirmed = true;
1430
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1431
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
14
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
14
    };
1448
1449
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1450
14
        auto* small_file = packed_info->mutable_slices(i);
1451
14
        if (small_file->deleted()) {
1452
3
            log_small_file_status(*small_file, small_file->corrected());
1453
3
            continue;
1454
3
        }
1455
1456
11
        if (small_file->corrected()) {
1457
0
            left_num++;
1458
0
            left_bytes += small_file->size();
1459
0
            log_small_file_status(*small_file, true);
1460
0
            continue;
1461
0
        }
1462
1463
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1464
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1465
0
                    .tag("instance_id", instance_id_)
1466
0
                    .tag("small_file_path", small_file->path())
1467
0
                    .tag("index", i);
1468
0
            return -1;
1469
0
        }
1470
1471
11
        int64_t tablet_id = small_file->tablet_id();
1472
11
        const std::string& rowset_id = small_file->rowset_id();
1473
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1474
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1475
0
                    .tag("instance_id", instance_id_)
1476
0
                    .tag("small_file_path", small_file->path())
1477
0
                    .tag("index", i)
1478
0
                    .tag("tablet_id", tablet_id)
1479
0
                    .tag("rowset_id", rowset_id)
1480
0
                    .tag("has_txn_id", small_file->has_txn_id())
1481
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1482
0
            return -1;
1483
0
        }
1484
11
        int64_t txn_id = small_file->txn_id();
1485
11
        bool recycle_exists = false;
1486
11
        bool tmp_exists = false;
1487
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1488
11
                                                &tmp_exists) != 0) {
1489
0
            return -1;
1490
0
        }
1491
1492
11
        bool small_file_confirmed = false;
1493
11
        if (tmp_exists) {
1494
1
            left_num++;
1495
1
            left_bytes += small_file->size();
1496
1
            small_file_confirmed = true;
1497
10
        } else if (recycle_exists) {
1498
1
            left_num++;
1499
1
            left_bytes += small_file->size();
1500
            // keep small_file_confirmed=false so the packed file remains uncorrected
1501
9
        } else {
1502
9
            bool rowset_exists = false;
1503
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1504
0
                return -1;
1505
0
            }
1506
1507
9
            if (!rowset_exists) {
1508
6
                if (!small_file->deleted()) {
1509
6
                    small_file->set_deleted(true);
1510
6
                    local_changed = true;
1511
6
                }
1512
6
                if (!small_file->corrected()) {
1513
6
                    small_file->set_corrected(true);
1514
6
                    local_changed = true;
1515
6
                }
1516
6
                small_file_confirmed = true;
1517
6
            } else {
1518
3
                left_num++;
1519
3
                left_bytes += small_file->size();
1520
3
                small_file_confirmed = true;
1521
3
            }
1522
9
        }
1523
1524
11
        if (!small_file_confirmed) {
1525
1
            all_small_files_confirmed = false;
1526
1
        }
1527
1528
11
        if (small_file->corrected() != small_file_confirmed) {
1529
4
            small_file->set_corrected(small_file_confirmed);
1530
4
            local_changed = true;
1531
4
        }
1532
1533
11
        log_small_file_status(*small_file, small_file_confirmed);
1534
11
    }
1535
1536
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1537
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1538
3
        local_changed = true;
1539
3
    }
1540
3
    if (packed_info->ref_cnt() != left_num) {
1541
3
        auto old_ref_cnt = packed_info->ref_cnt();
1542
3
        packed_info->set_ref_cnt(left_num);
1543
3
        LOG_INFO("corrected packed file ref count")
1544
3
                .tag("instance_id", instance_id_)
1545
3
                .tag("resource_id", packed_info->resource_id())
1546
3
                .tag("packed_file_path", packed_file_path)
1547
3
                .tag("old_ref_cnt", old_ref_cnt)
1548
3
                .tag("new_ref_cnt", left_num);
1549
3
        local_changed = true;
1550
3
    }
1551
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1552
2
        packed_info->set_corrected(all_small_files_confirmed);
1553
2
        local_changed = true;
1554
2
    }
1555
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1556
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1557
1
        local_changed = true;
1558
1
    }
1559
1560
3
    if (changed != nullptr) {
1561
3
        *changed = local_changed;
1562
3
    }
1563
3
    return 0;
1564
3
}
1565
1566
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1567
                                                 const std::string& packed_file_path,
1568
3
                                                 PackedFileRecycleStats* stats) {
1569
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1570
3
    bool correction_ok = false;
1571
3
    cloud::PackedFileInfoPB packed_info;
1572
1573
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1574
3
        if (stopped()) {
1575
0
            LOG_WARNING("recycler stopped before processing packed file")
1576
0
                    .tag("instance_id", instance_id_)
1577
0
                    .tag("packed_file_path", packed_file_path)
1578
0
                    .tag("attempt", attempt);
1579
0
            return -1;
1580
0
        }
1581
1582
3
        std::unique_ptr<Transaction> txn;
1583
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1584
3
        if (err != TxnErrorCode::TXN_OK) {
1585
0
            LOG_WARNING("failed to create txn when processing packed file")
1586
0
                    .tag("instance_id", instance_id_)
1587
0
                    .tag("packed_file_path", packed_file_path)
1588
0
                    .tag("attempt", attempt)
1589
0
                    .tag("err", err);
1590
0
            return -1;
1591
0
        }
1592
1593
3
        std::string packed_val;
1594
3
        err = txn->get(packed_key, &packed_val);
1595
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1596
0
            return 0;
1597
0
        }
1598
3
        if (err != TxnErrorCode::TXN_OK) {
1599
0
            LOG_WARNING("failed to get packed file kv")
1600
0
                    .tag("instance_id", instance_id_)
1601
0
                    .tag("packed_file_path", packed_file_path)
1602
0
                    .tag("attempt", attempt)
1603
0
                    .tag("err", err);
1604
0
            return -1;
1605
0
        }
1606
1607
3
        if (!packed_info.ParseFromString(packed_val)) {
1608
0
            LOG_WARNING("failed to parse packed file info")
1609
0
                    .tag("instance_id", instance_id_)
1610
0
                    .tag("packed_file_path", packed_file_path)
1611
0
                    .tag("attempt", attempt);
1612
0
            return -1;
1613
0
        }
1614
1615
3
        int64_t now_sec = ::time(nullptr);
1616
3
        bool corrected = packed_info.corrected();
1617
3
        bool due = config::force_immediate_recycle ||
1618
3
                   now_sec - packed_info.created_at_sec() >=
1619
3
                           config::packed_file_correction_delay_seconds;
1620
1621
3
        if (!corrected && due) {
1622
3
            bool changed = false;
1623
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1624
0
                LOG_WARNING("correct_packed_file_info failed")
1625
0
                        .tag("instance_id", instance_id_)
1626
0
                        .tag("packed_file_path", packed_file_path)
1627
0
                        .tag("attempt", attempt);
1628
0
                return -1;
1629
0
            }
1630
3
            if (changed) {
1631
3
                std::string updated;
1632
3
                if (!packed_info.SerializeToString(&updated)) {
1633
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1634
0
                            .tag("instance_id", instance_id_)
1635
0
                            .tag("packed_file_path", packed_file_path)
1636
0
                            .tag("attempt", attempt);
1637
0
                    return -1;
1638
0
                }
1639
3
                txn->put(packed_key, updated);
1640
3
                err = txn->commit();
1641
3
                if (err == TxnErrorCode::TXN_OK) {
1642
3
                    if (stats) {
1643
3
                        ++stats->num_corrected;
1644
3
                    }
1645
3
                } else {
1646
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1647
0
                        LOG_WARNING(
1648
0
                                "failed to commit correction for packed file due to conflict, "
1649
0
                                "retrying")
1650
0
                                .tag("instance_id", instance_id_)
1651
0
                                .tag("packed_file_path", packed_file_path)
1652
0
                                .tag("attempt", attempt);
1653
0
                        sleep_for_packed_file_retry();
1654
0
                        packed_info.Clear();
1655
0
                        continue;
1656
0
                    }
1657
0
                    LOG_WARNING("failed to commit correction for packed file")
1658
0
                            .tag("instance_id", instance_id_)
1659
0
                            .tag("packed_file_path", packed_file_path)
1660
0
                            .tag("attempt", attempt)
1661
0
                            .tag("err", err);
1662
0
                    return -1;
1663
0
                }
1664
3
            }
1665
3
        }
1666
1667
3
        correction_ok = true;
1668
3
        break;
1669
3
    }
1670
1671
3
    if (!correction_ok) {
1672
0
        return -1;
1673
0
    }
1674
1675
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1676
3
          packed_info.ref_cnt() == 0)) {
1677
2
        return 0;
1678
2
    }
1679
1680
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1681
0
        LOG_WARNING("packed file missing resource id when recycling")
1682
0
                .tag("instance_id", instance_id_)
1683
0
                .tag("packed_file_path", packed_file_path);
1684
0
        return -1;
1685
0
    }
1686
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1687
1
    if (!accessor) {
1688
0
        LOG_WARNING("no accessor available to delete packed file")
1689
0
                .tag("instance_id", instance_id_)
1690
0
                .tag("packed_file_path", packed_file_path)
1691
0
                .tag("resource_id", packed_info.resource_id());
1692
0
        return -1;
1693
0
    }
1694
1
    int del_ret = accessor->delete_file(packed_file_path);
1695
1
    if (del_ret != 0 && del_ret != 1) {
1696
0
        LOG_WARNING("failed to delete packed file")
1697
0
                .tag("instance_id", instance_id_)
1698
0
                .tag("packed_file_path", packed_file_path)
1699
0
                .tag("resource_id", resource_id)
1700
0
                .tag("ret", del_ret);
1701
0
        return -1;
1702
0
    }
1703
1
    if (del_ret == 1) {
1704
0
        LOG_INFO("packed file already removed")
1705
0
                .tag("instance_id", instance_id_)
1706
0
                .tag("packed_file_path", packed_file_path)
1707
0
                .tag("resource_id", resource_id);
1708
1
    } else {
1709
1
        LOG_INFO("deleted packed file")
1710
1
                .tag("instance_id", instance_id_)
1711
1
                .tag("packed_file_path", packed_file_path)
1712
1
                .tag("resource_id", resource_id);
1713
1
    }
1714
1715
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1716
1
        std::unique_ptr<Transaction> del_txn;
1717
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1718
1
        if (err != TxnErrorCode::TXN_OK) {
1719
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1720
0
                    .tag("instance_id", instance_id_)
1721
0
                    .tag("packed_file_path", packed_file_path)
1722
0
                    .tag("del_attempt", del_attempt)
1723
0
                    .tag("err", err);
1724
0
            return -1;
1725
0
        }
1726
1727
1
        std::string latest_val;
1728
1
        err = del_txn->get(packed_key, &latest_val);
1729
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1730
0
            return 0;
1731
0
        }
1732
1
        if (err != TxnErrorCode::TXN_OK) {
1733
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1734
0
                    .tag("instance_id", instance_id_)
1735
0
                    .tag("packed_file_path", packed_file_path)
1736
0
                    .tag("del_attempt", del_attempt)
1737
0
                    .tag("err", err);
1738
0
            return -1;
1739
0
        }
1740
1741
1
        cloud::PackedFileInfoPB latest_info;
1742
1
        if (!latest_info.ParseFromString(latest_val)) {
1743
0
            LOG_WARNING("failed to parse packed file info before removal")
1744
0
                    .tag("instance_id", instance_id_)
1745
0
                    .tag("packed_file_path", packed_file_path)
1746
0
                    .tag("del_attempt", del_attempt);
1747
0
            return -1;
1748
0
        }
1749
1750
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1751
1
              latest_info.ref_cnt() == 0)) {
1752
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1753
0
                    .tag("instance_id", instance_id_)
1754
0
                    .tag("packed_file_path", packed_file_path)
1755
0
                    .tag("del_attempt", del_attempt);
1756
0
            return 0;
1757
0
        }
1758
1759
1
        del_txn->remove(packed_key);
1760
1
        err = del_txn->commit();
1761
1
        if (err == TxnErrorCode::TXN_OK) {
1762
1
            if (stats) {
1763
1
                ++stats->num_deleted;
1764
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1765
1
                                        static_cast<int64_t>(latest_val.size());
1766
1
                if (del_ret == 0 || del_ret == 1) {
1767
1
                    ++stats->num_object_deleted;
1768
1
                    int64_t object_size = latest_info.total_slice_bytes();
1769
1
                    if (object_size <= 0) {
1770
0
                        object_size = packed_info.total_slice_bytes();
1771
0
                    }
1772
1
                    stats->bytes_object_deleted += object_size;
1773
1
                }
1774
1
            }
1775
1
            LOG_INFO("removed packed file metadata")
1776
1
                    .tag("instance_id", instance_id_)
1777
1
                    .tag("packed_file_path", packed_file_path);
1778
1
            return 0;
1779
1
        }
1780
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1781
0
            if (del_attempt >= max_retry_times) {
1782
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1783
0
                        .tag("instance_id", instance_id_)
1784
0
                        .tag("packed_file_path", packed_file_path)
1785
0
                        .tag("del_attempt", del_attempt);
1786
0
                return -1;
1787
0
            }
1788
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1789
0
                    .tag("instance_id", instance_id_)
1790
0
                    .tag("packed_file_path", packed_file_path)
1791
0
                    .tag("del_attempt", del_attempt);
1792
0
            sleep_for_packed_file_retry();
1793
0
            continue;
1794
0
        }
1795
0
        LOG_WARNING("failed to remove packed file kv")
1796
0
                .tag("instance_id", instance_id_)
1797
0
                .tag("packed_file_path", packed_file_path)
1798
0
                .tag("del_attempt", del_attempt)
1799
0
                .tag("err", err);
1800
0
        return -1;
1801
0
    }
1802
1803
0
    return -1;
1804
1
}
1805
1806
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1807
4
                                            PackedFileRecycleStats* stats, int* ret) {
1808
4
    if (stats) {
1809
4
        ++stats->num_scanned;
1810
4
    }
1811
4
    std::string packed_file_path;
1812
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1813
0
        LOG_WARNING("failed to decode packed file key")
1814
0
                .tag("instance_id", instance_id_)
1815
0
                .tag("key", hex(key));
1816
0
        if (stats) {
1817
0
            ++stats->num_failed;
1818
0
        }
1819
0
        if (ret) {
1820
0
            *ret = -1;
1821
0
        }
1822
0
        return 0;
1823
0
    }
1824
1825
4
    cloud::PackedFileInfoPB packed_info;
1826
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1827
0
        LOG_WARNING("failed to parse packed file info from scan")
1828
0
                .tag("instance_id", instance_id_)
1829
0
                .tag("packed_file_path", packed_file_path);
1830
0
        if (stats) {
1831
0
            ++stats->num_failed;
1832
0
        }
1833
0
        if (ret) {
1834
0
            *ret = -1;
1835
0
        }
1836
0
        return 0;
1837
0
    }
1838
1839
4
    const int64_t now_sec = ::time(nullptr);
1840
4
    const bool due =
1841
4
            config::force_immediate_recycle ||
1842
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1843
4
    const bool need_correction = !packed_info.corrected() && due;
1844
4
    const bool need_recycle =
1845
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1846
4
    if (!need_correction && !need_recycle) {
1847
1
        return 0;
1848
1
    }
1849
1850
3
    std::string packed_key(key);
1851
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1852
3
    if (process_ret != 0) {
1853
0
        if (stats) {
1854
0
            ++stats->num_failed;
1855
0
        }
1856
0
        if (ret) {
1857
0
            *ret = -1;
1858
0
        }
1859
0
    }
1860
3
    return 0;
1861
4
}
1862
1863
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1864
126k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1865
126k
    if (config::force_immediate_recycle) {
1866
120k
        return 0L;
1867
120k
    }
1868
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1869
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1870
6.00k
    int64_t retention_seconds = config::retention_seconds;
1871
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1872
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1873
4.70k
    }
1874
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1875
6.00k
    if (*earlest_ts > final_expiration) {
1876
6
        *earlest_ts = final_expiration;
1877
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1878
6
    }
1879
6.00k
    return final_expiration;
1880
126k
}
1881
1882
int64_t calculate_partition_expired_time(
1883
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1884
13
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1885
13
    if (config::force_immediate_recycle) {
1886
7
        return 0L;
1887
7
    }
1888
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1889
6
                                                            : partition_meta_pb.creation_time();
1890
6
    int64_t retention_seconds = config::retention_seconds;
1891
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1892
6
        retention_seconds =
1893
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1894
6
    }
1895
6
    int64_t final_expiration = expiration + retention_seconds;
1896
6
    if (*earlest_ts > final_expiration) {
1897
2
        *earlest_ts = final_expiration;
1898
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1899
2
    }
1900
6
    return final_expiration;
1901
13
}
1902
1903
int64_t calculate_index_expired_time(const std::string& instance_id_,
1904
                                     const RecycleIndexPB& index_meta_pb,
1905
19
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1906
19
    if (config::force_immediate_recycle) {
1907
13
        return 0L;
1908
13
    }
1909
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1910
6
                                                        : index_meta_pb.creation_time();
1911
6
    int64_t retention_seconds = config::retention_seconds;
1912
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1913
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1914
6
    }
1915
6
    int64_t final_expiration = expiration + retention_seconds;
1916
6
    if (*earlest_ts > final_expiration) {
1917
2
        *earlest_ts = final_expiration;
1918
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1919
2
    }
1920
6
    return final_expiration;
1921
19
}
1922
1923
int64_t calculate_tmp_rowset_expired_time(
1924
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1925
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1926
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1927
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1928
    //  duration or timeout always < `retention_time` in practice.
1929
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1930
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1931
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1932
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1933
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1934
53.2k
    if (*earlest_ts > final_expiration) {
1935
20
        *earlest_ts = final_expiration;
1936
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1937
20
    }
1938
53.2k
    return final_expiration;
1939
53.2k
}
1940
1941
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1942
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1943
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1944
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1945
11
        *earlest_ts = final_expiration / 1000;
1946
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1947
11
    }
1948
50.0k
    return final_expiration;
1949
50.0k
}
1950
1951
int64_t calculate_restore_job_expired_time(
1952
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1953
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1954
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1955
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1956
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1957
        // final state, recycle immediately
1958
41
        return 0L;
1959
41
    }
1960
    // not final state, wait much longer than the FE's timeout(1 day)
1961
0
    int64_t last_modified_s =
1962
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1963
0
    int64_t expiration = restore_job.expired_at_s() > 0
1964
0
                                 ? last_modified_s + restore_job.expired_at_s()
1965
0
                                 : last_modified_s;
1966
0
    int64_t final_expiration = expiration + config::retention_seconds;
1967
0
    if (*earlest_ts > final_expiration) {
1968
0
        *earlest_ts = final_expiration;
1969
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1970
0
    }
1971
0
    return final_expiration;
1972
41
}
1973
1974
10.5k
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1975
10.5k
    AbortTxnRequest req;
1976
10.5k
    TxnInfoPB txn_info;
1977
10.5k
    MetaServiceCode code = MetaServiceCode::OK;
1978
10.5k
    std::string msg;
1979
10.5k
    std::stringstream ss;
1980
10.5k
    std::unique_ptr<Transaction> txn;
1981
10.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1982
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1983
0
        LOG_WARNING("failed to create txn").tag("err", err);
1984
0
        return -1;
1985
0
    }
1986
1987
    // get txn index
1988
10.5k
    TxnIndexPB txn_idx_pb;
1989
10.5k
    auto index_key = txn_index_key({instance_id_, txn_id});
1990
10.5k
    std::string index_val;
1991
10.5k
    err = txn->get(index_key, &index_val);
1992
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1993
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1994
            // maybe recycled
1995
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1996
2
                    .tag("key", hex(index_key))
1997
2
                    .tag("txn_id", txn_id);
1998
2
            return 0;
1999
2
        }
2000
0
        LOG_WARNING("failed to get txn index")
2001
0
                .tag("err", err)
2002
0
                .tag("key", hex(index_key))
2003
0
                .tag("txn_id", txn_id);
2004
0
        return -1;
2005
2
    }
2006
10.5k
    if (!txn_idx_pb.ParseFromString(index_val)) {
2007
1
        LOG_WARNING("failed to parse txn index")
2008
1
                .tag("err", err)
2009
1
                .tag("key", hex(index_key))
2010
1
                .tag("txn_id", txn_id);
2011
1
        return -1;
2012
1
    }
2013
10.5k
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
2014
10.5k
        txn_idx_pb.tablet_index().db_id() <= 0) {
2015
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
2016
3
                .tag("key", hex(index_key))
2017
3
                .tag("txn_id", txn_id)
2018
3
                .tag("db_id",
2019
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
2020
3
        return -1;
2021
3
    }
2022
2023
10.5k
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
2024
10.5k
    const int64_t owner_txn_id =
2025
10.5k
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
2026
10.5k
    if (owner_txn_id <= 0) {
2027
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2028
1
                .tag("key", hex(index_key))
2029
1
                .tag("txn_id", txn_id)
2030
1
                .tag("owner_txn_id", owner_txn_id);
2031
1
        return -1;
2032
1
    }
2033
2034
10.5k
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2035
10.5k
    std::string info_val;
2036
10.5k
    err = txn->get(info_key, &info_val);
2037
10.5k
    if (err != TxnErrorCode::TXN_OK) {
2038
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2039
            // maybe recycled
2040
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2041
1
                        owner_txn_id, instance_id_)
2042
1
                    .tag("key", hex(info_key))
2043
1
                    .tag("txn_id", txn_id)
2044
1
                    .tag("owner_txn_id", owner_txn_id);
2045
1
            return 0;
2046
1
        }
2047
0
        LOG_WARNING("failed to get txn info")
2048
0
                .tag("err", err)
2049
0
                .tag("key", hex(info_key))
2050
0
                .tag("txn_id", txn_id)
2051
0
                .tag("owner_txn_id", owner_txn_id);
2052
0
        return -1;
2053
1
    }
2054
10.5k
    if (!txn_info.ParseFromString(info_val)) {
2055
1
        LOG_WARNING("failed to parse txn info")
2056
1
                .tag("err", err)
2057
1
                .tag("key", hex(info_key))
2058
1
                .tag("txn_id", txn_id)
2059
1
                .tag("owner_txn_id", owner_txn_id);
2060
1
        return -1;
2061
1
    }
2062
10.5k
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2063
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2064
1
                .tag("key", hex(info_key))
2065
1
                .tag("txn_id", txn_id)
2066
1
                .tag("owner_txn_id", owner_txn_id)
2067
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2068
1
        return -1;
2069
1
    }
2070
2071
10.5k
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2072
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2073
514
                .tag("key", hex(info_key))
2074
514
                .tag("txn_id", txn_id)
2075
514
                .tag("owner_txn_id", owner_txn_id);
2076
514
        return 0;
2077
514
    }
2078
9.99k
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2079
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2080
4
                    owner_txn_id, txn_info.status())
2081
4
                .tag("key", hex(info_key))
2082
4
                .tag("txn_id", txn_id)
2083
4
                .tag("owner_txn_id", owner_txn_id);
2084
4
        return -1;
2085
4
    }
2086
2087
9.99k
    req.set_txn_id(owner_txn_id);
2088
9.99k
    req.set_db_id(db_id);
2089
2090
9.99k
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2091
9.99k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2092
9.99k
                 << " txn_info=" << txn_info.ShortDebugString();
2093
2094
9.99k
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2095
9.99k
    if (code != MetaServiceCode::OK) {
2096
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2097
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2098
0
                     << " code=" << code << " msg=" << msg;
2099
0
        return -1;
2100
0
    }
2101
2102
9.99k
    err = txn->commit();
2103
9.99k
    if (err != TxnErrorCode::TXN_OK) {
2104
0
        code = cast_as<ErrCategory::COMMIT>(err);
2105
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2106
0
        msg = ss.str();
2107
0
        return -1;
2108
0
    }
2109
2110
9.99k
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2111
9.99k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2112
9.99k
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2113
9.99k
                 << " msg=" << msg;
2114
2115
9.99k
    return 0;
2116
9.99k
}
2117
2118
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2119
11
                                                   const std::string& job_id) {
2120
11
    FinishTabletJobRequest req;
2121
11
    FinishTabletJobResponse res;
2122
11
    req.set_action(FinishTabletJobRequest::ABORT);
2123
11
    MetaServiceCode code = MetaServiceCode::OK;
2124
11
    std::string msg;
2125
11
    std::stringstream ss;
2126
2127
11
    TabletIndexPB tablet_idx;
2128
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2129
11
    if (ret == 1) {
2130
        // tablet maybe recycled, directly return 0
2131
1
        return 0;
2132
10
    } else if (ret != 0) {
2133
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2134
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2135
0
        return ret;
2136
0
    }
2137
2138
10
    std::unique_ptr<Transaction> txn;
2139
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2140
10
    if (err != TxnErrorCode::TXN_OK) {
2141
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2142
0
        return -1;
2143
0
    }
2144
2145
10
    std::string job_key =
2146
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2147
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2148
10
    std::string job_val;
2149
10
    err = txn->get(job_key, &job_val);
2150
10
    if (err != TxnErrorCode::TXN_OK) {
2151
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2152
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2153
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2154
            // A previous recycler round may have aborted the job. The caller must recheck the
2155
            // recycle key before deleting object data.
2156
1
            return 0;
2157
1
        }
2158
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2159
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2160
0
                     << " key=" << hex(job_key);
2161
0
        return -1;
2162
1
    }
2163
2164
9
    TabletJobInfoPB job_pb;
2165
9
    if (!job_pb.ParseFromString(job_val)) {
2166
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2167
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2168
0
        return -1;
2169
0
    }
2170
2171
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2172
9
    for (const auto& compaction : job_pb.compaction()) {
2173
9
        if (compaction.id() == job_id) {
2174
5
            matched_compaction = &compaction;
2175
5
            break;
2176
5
        }
2177
9
    }
2178
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2179
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2180
9
        job_pb.schema_change().id() == job_id) {
2181
3
        matched_schema_change = &job_pb.schema_change();
2182
3
    }
2183
2184
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2185
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2186
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2187
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2188
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2189
        // both the base and mirrored schema-change records.
2190
8
        if (matched_compaction != nullptr) {
2191
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2192
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2193
5
        } else {
2194
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2195
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2196
3
        }
2197
8
        req.set_action(FinishTabletJobRequest::ABORT);
2198
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2199
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2200
8
                           ss);
2201
8
        if (code != MetaServiceCode::OK) {
2202
            // These two codes mean that the job cannot be aborted anymore.
2203
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2204
            // There is no running job that still owns the PREPARE rowset, so the caller may
2205
            // recheck the recycle key.
2206
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2207
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2208
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2209
            // job again and continue recycling only when the target job id no longer exists.
2210
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2211
0
                std::unique_ptr<Transaction> check_txn;
2212
0
                err = txn_kv_->create_txn(&check_txn);
2213
0
                if (err != TxnErrorCode::TXN_OK) {
2214
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2215
0
                                 << instance_id_ << " err=" << err;
2216
0
                    return -1;
2217
0
                }
2218
2219
0
                const auto& idx = req.job().idx();
2220
0
                std::string current_job_key =
2221
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2222
0
                                        idx.partition_id(), idx.tablet_id()});
2223
0
                std::string current_job_val;
2224
0
                err = check_txn->get(current_job_key, &current_job_val);
2225
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
0
                    no_job_to_abort = true;
2227
0
                } else if (err != TxnErrorCode::TXN_OK) {
2228
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2229
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2230
0
                                 << " key=" << hex(current_job_key);
2231
0
                    return -1;
2232
0
                } else {
2233
0
                    TabletJobInfoPB current_job;
2234
0
                    if (!current_job.ParseFromString(current_job_val)) {
2235
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2236
0
                                     << " tablet_id=" << idx.tablet_id()
2237
0
                                     << " key=" << hex(current_job_key);
2238
0
                        return -1;
2239
0
                    }
2240
0
                    if (matched_compaction != nullptr) {
2241
0
                        no_job_to_abort = true;
2242
0
                        for (const auto& compaction : current_job.compaction()) {
2243
0
                            if (compaction.id() == job_id) {
2244
0
                                no_job_to_abort = false;
2245
0
                                break;
2246
0
                            }
2247
0
                        }
2248
0
                    } else {
2249
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2250
0
                                          current_job.schema_change().id() != job_id;
2251
0
                    }
2252
0
                }
2253
0
            }
2254
0
            if (no_job_to_abort) {
2255
0
                return 0;
2256
0
            }
2257
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2258
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2259
0
                         << " msg=" << msg;
2260
0
            return -1;
2261
0
        }
2262
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2263
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2264
8
                     << " code=" << code << " msg=" << msg;
2265
8
    } else {
2266
        // clang-format off
2267
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2268
1
                  << ", instance_id=" << instance_id_ 
2269
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2270
1
                  << ", job_id=" << job_id
2271
1
                  << ", rowset_id=" << rowset_id;
2272
        // clang-format on
2273
1
    }
2274
2275
9
    return 0;
2276
9
}
2277
2278
template <typename T>
2279
19.9k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
19.9k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2282
19.8k
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
19.9k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2279
19.8k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
19.8k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2282
    } else {
2283
        return &rowset_meta_pb;
2284
    }
2285
19.8k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2279
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
        return rowset_meta_pb.mutable_rowset_meta();
2282
9
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
9
}
2286
2287
template <typename T>
2288
81.5k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
81.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
80.7k
        return rowset_meta_pb.rowset_meta();
2291
80.7k
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
81.5k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2288
80.7k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
80.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
80.7k
        return rowset_meta_pb.rowset_meta();
2291
    } else {
2292
        return rowset_meta_pb;
2293
    }
2294
80.7k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2288
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
        return rowset_meta_pb.rowset_meta();
2291
799
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
799
}
2295
2296
template <typename T>
2297
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2298
41.0k
        const T& rowset_meta_pb) {
2299
41.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
40.5k
    }
2304
2305
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
41.0k
    RelatedTxnOrJobAbortTask task;
2307
41.0k
    task.tablet_id = rs_meta.tablet_id();
2308
41.0k
    task.start_version = rs_meta.start_version();
2309
41.0k
    task.end_version = rs_meta.end_version();
2310
41.0k
    task.rowset_id = rs_meta.rowset_id_v2();
2311
41.0k
    if (rs_meta.has_load_id()) {
2312
21.0k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
21.0k
        task.txn_id = rs_meta.txn_id();
2314
21.0k
        return task;
2315
21.0k
    }
2316
20.0k
    if (rs_meta.has_job_id()) {
2317
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
14
        task.job_id = rs_meta.job_id();
2319
14
        return task;
2320
14
    }
2321
19.9k
    return std::nullopt;
2322
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
40.5k
        const T& rowset_meta_pb) {
2299
40.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
40.5k
    }
2304
2305
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
40.5k
    RelatedTxnOrJobAbortTask task;
2307
40.5k
    task.tablet_id = rs_meta.tablet_id();
2308
40.5k
    task.start_version = rs_meta.start_version();
2309
40.5k
    task.end_version = rs_meta.end_version();
2310
40.5k
    task.rowset_id = rs_meta.rowset_id_v2();
2311
40.5k
    if (rs_meta.has_load_id()) {
2312
20.5k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
20.5k
        task.txn_id = rs_meta.txn_id();
2314
20.5k
        return task;
2315
20.5k
    }
2316
20.0k
    if (rs_meta.has_job_id()) {
2317
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
10
        task.job_id = rs_meta.job_id();
2319
10
        return task;
2320
10
    }
2321
19.9k
    return std::nullopt;
2322
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
526
        const T& rowset_meta_pb) {
2299
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
            return std::nullopt;
2302
        }
2303
    }
2304
2305
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
526
    RelatedTxnOrJobAbortTask task;
2307
526
    task.tablet_id = rs_meta.tablet_id();
2308
526
    task.start_version = rs_meta.start_version();
2309
526
    task.end_version = rs_meta.end_version();
2310
526
    task.rowset_id = rs_meta.rowset_id_v2();
2311
526
    if (rs_meta.has_load_id()) {
2312
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
518
        task.txn_id = rs_meta.txn_id();
2314
518
        return task;
2315
518
    }
2316
8
    if (rs_meta.has_job_id()) {
2317
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
4
        task.job_id = rs_meta.job_id();
2319
4
        return task;
2320
4
    }
2321
4
    return std::nullopt;
2322
8
}
2323
2324
template <typename T>
2325
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2326
10.5k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
10.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
10.2k
    }
2332
2333
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
10.5k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
10.5k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
10.5k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
10.5k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
10.5k
    }
2341
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
10.5k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
10.2k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
10.2k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
10.2k
    }
2332
2333
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
10.2k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
10.2k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
10.2k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
10.2k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
10.2k
    }
2341
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
10.2k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
            return false;
2330
        }
2331
    }
2332
2333
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
259
    }
2341
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
261
}
2343
2344
79.8k
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2345
79.8k
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2346
79.8k
}
2347
2348
template <typename T>
2349
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2350
76
                                   const std::vector<std::string>& keys) {
2351
204
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
129
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
129
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
129
        std::unique_ptr<Transaction> txn;
2355
129
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
129
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
129
        std::vector<std::optional<std::string>> values;
2361
129
        err = txn->batch_get(&values, batch_keys);
2362
129
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
129
        DCHECK_EQ(values.size(), batch_keys.size());
2368
20.1k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
19.9k
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
19.9k
            const auto& key = batch_keys[i];
2374
19.9k
            auto val = values[i].value();
2375
19.9k
            T rowset_meta_pb;
2376
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
19.9k
            }
2389
19.9k
            val.clear();
2390
19.9k
            rowset_meta_pb.SerializeToString(&val);
2391
19.9k
            txn->put(key, val);
2392
19.9k
        }
2393
129
        err = txn->commit();
2394
129
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
129
    }
2399
2400
75
    return 0;
2401
76
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
69
                                   const std::vector<std::string>& keys) {
2351
190
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
122
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
122
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
122
        std::unique_ptr<Transaction> txn;
2355
122
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
122
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
122
        std::vector<std::optional<std::string>> values;
2361
122
        err = txn->batch_get(&values, batch_keys);
2362
122
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
122
        DCHECK_EQ(values.size(), batch_keys.size());
2368
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
19.9k
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
19.9k
            const auto& key = batch_keys[i];
2374
19.9k
            auto val = values[i].value();
2375
19.9k
            T rowset_meta_pb;
2376
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
19.9k
            }
2389
19.9k
            val.clear();
2390
19.9k
            rowset_meta_pb.SerializeToString(&val);
2391
19.9k
            txn->put(key, val);
2392
19.9k
        }
2393
122
        err = txn->commit();
2394
122
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
122
    }
2399
2400
68
    return 0;
2401
69
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
7
                                   const std::vector<std::string>& keys) {
2351
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
7
        std::unique_ptr<Transaction> txn;
2355
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
7
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
7
        std::vector<std::optional<std::string>> values;
2361
7
        err = txn->batch_get(&values, batch_keys);
2362
7
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
7
        DCHECK_EQ(values.size(), batch_keys.size());
2368
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
9
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
9
            const auto& key = batch_keys[i];
2374
9
            auto val = values[i].value();
2375
9
            T rowset_meta_pb;
2376
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
            }
2389
9
            val.clear();
2390
9
            rowset_meta_pb.SerializeToString(&val);
2391
9
            txn->put(key, val);
2392
9
        }
2393
7
        err = txn->commit();
2394
7
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
0
            return -1;
2397
0
        }
2398
7
    }
2399
2400
7
    return 0;
2401
7
}
2402
2403
template <typename T>
2404
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2405
76
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
76
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
76
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
76
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
69
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
0
        }
2411
7
    });
2412
76
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
69
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
69
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
69
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
69
        }
2411
69
    });
2412
69
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
7
        }
2411
7
    });
2412
7
}
2413
2414
template <typename T>
2415
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2416
                                 const std::vector<std::string>& keys,
2417
51
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
132
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
81
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
81
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
81
        std::unique_ptr<Transaction> txn;
2422
81
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
81
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
81
        std::vector<std::optional<std::string>> values;
2428
81
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
81
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
81
        DCHECK_EQ(values.size(), batch_keys.size());
2435
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
10.5k
            const std::string& key = batch_keys[idx];
2437
10.5k
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
10.5k
            T rowset_meta_pb;
2442
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
10.5k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
10.5k
                abort_task.has_value()) {
2449
10.5k
                abort_task->key = key;
2450
10.5k
                abort_tasks->emplace_back(std::move(*abort_task));
2451
10.5k
            }
2452
10.5k
        }
2453
81
    }
2454
51
    return 0;
2455
51
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
46
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
121
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
75
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
75
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
75
        std::unique_ptr<Transaction> txn;
2422
75
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
75
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
75
        std::vector<std::optional<std::string>> values;
2428
75
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
75
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
75
        DCHECK_EQ(values.size(), batch_keys.size());
2435
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
10.2k
            const std::string& key = batch_keys[idx];
2437
10.2k
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
10.2k
            T rowset_meta_pb;
2442
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
10.2k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
10.2k
                abort_task.has_value()) {
2449
10.2k
                abort_task->key = key;
2450
10.2k
                abort_tasks->emplace_back(std::move(*abort_task));
2451
10.2k
            }
2452
10.2k
        }
2453
75
    }
2454
46
    return 0;
2455
46
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
6
        std::unique_ptr<Transaction> txn;
2422
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
6
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
6
        std::vector<std::optional<std::string>> values;
2428
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
6
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
6
        DCHECK_EQ(values.size(), batch_keys.size());
2435
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
261
            const std::string& key = batch_keys[idx];
2437
261
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
261
            T rowset_meta_pb;
2442
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
261
                abort_task.has_value()) {
2449
261
                abort_task->key = key;
2450
261
                abort_tasks->emplace_back(std::move(*abort_task));
2451
261
            }
2452
261
        }
2453
6
    }
2454
5
    return 0;
2455
5
}
2456
2457
template <typename T>
2458
int batch_recheck_rowsets_after_abort(
2459
        TxnKv* txn_kv, const std::string& instance_id,
2460
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2461
49
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
49
    int ret = 0;
2463
128
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
79
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
79
        std::vector<std::string> batch_keys;
2466
79
        batch_keys.reserve(limit - offset);
2467
10.6k
        for (size_t idx = offset; idx < limit; ++idx) {
2468
10.5k
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
10.5k
        }
2470
2471
79
        std::unique_ptr<Transaction> txn;
2472
79
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
79
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
79
        std::vector<std::optional<std::string>> values;
2481
79
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
79
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
79
        DCHECK_EQ(values.size(), batch_keys.size());
2489
79
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
79
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
79
                                 &batch_size);
2492
2493
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
10.5k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
10.5k
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
10.5k
            T rowset_meta_pb;
2500
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
10.5k
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
10.5k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
10.5k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
10.5k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
10.5k
        }
2519
79
    }
2520
49
    return ret;
2521
49
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
44
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
44
    int ret = 0;
2463
117
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
73
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
73
        std::vector<std::string> batch_keys;
2466
73
        batch_keys.reserve(limit - offset);
2467
10.3k
        for (size_t idx = offset; idx < limit; ++idx) {
2468
10.2k
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
10.2k
        }
2470
2471
73
        std::unique_ptr<Transaction> txn;
2472
73
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
73
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
73
        std::vector<std::optional<std::string>> values;
2481
73
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
73
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
73
        DCHECK_EQ(values.size(), batch_keys.size());
2489
73
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
73
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
73
                                 &batch_size);
2492
2493
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
10.2k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
10.2k
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
10.2k
            T rowset_meta_pb;
2500
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
10.2k
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
10.2k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
10.2k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
10.2k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
10.2k
        }
2519
73
    }
2520
44
    return ret;
2521
44
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
5
    int ret = 0;
2463
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
6
        std::vector<std::string> batch_keys;
2466
6
        batch_keys.reserve(limit - offset);
2467
267
        for (size_t idx = offset; idx < limit; ++idx) {
2468
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
261
        }
2470
2471
6
        std::unique_ptr<Transaction> txn;
2472
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
6
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
6
        std::vector<std::optional<std::string>> values;
2481
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
6
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
6
        DCHECK_EQ(values.size(), batch_keys.size());
2489
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
6
                                 &batch_size);
2492
2493
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
261
            if (!values[idx].has_value()) {
2496
0
                continue;
2497
0
            }
2498
2499
261
            T rowset_meta_pb;
2500
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
0
                             << instance_id << " key=" << hex(key);
2515
0
                continue;
2516
0
            }
2517
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
261
        }
2519
6
    }
2520
5
    return ret;
2521
5
}
2522
2523
template <typename T>
2524
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2525
        const std::vector<std::string>& keys,
2526
51
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
51
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
51
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
51
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
51
    int ret = 0;
2534
10.5k
    for (const auto& abort_task : abort_tasks) {
2535
10.5k
        int abort_ret = 0;
2536
10.5k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
10.5k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
10.5k
        } else {
2539
0
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
0
                                                     abort_task.job_id);
2541
0
        }
2542
10.5k
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
10.5k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
10.5k
    }
2551
51
    return ret;
2552
51
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
46
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
46
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
46
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
46
    int ret = 0;
2534
10.2k
    for (const auto& abort_task : abort_tasks) {
2535
10.2k
        int abort_ret = 0;
2536
10.2k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
10.2k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
18.4E
        } else {
2539
18.4E
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
18.4E
                                                     abort_task.job_id);
2541
18.4E
        }
2542
10.2k
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
10.2k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
10.2k
    }
2551
46
    return ret;
2552
46
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
5
    int ret = 0;
2534
261
    for (const auto& abort_task : abort_tasks) {
2535
261
        int abort_ret = 0;
2536
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
259
        } else {
2539
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
2
                                                     abort_task.job_id);
2541
2
        }
2542
261
        if (abort_ret != 0) {
2543
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
0
            ret = abort_ret;
2547
0
            continue;
2548
0
        }
2549
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
261
    }
2551
5
    return ret;
2552
5
}
2553
2554
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2555
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2556
46
        std::atomic_long* num_recycled) {
2557
46
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2558
46
                                  num_recycled]() mutable {
2559
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
46
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
46
                                                                            keys_to_recheck);
2562
46
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
46
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
44
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
44
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
44
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
44
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2580
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
10.2k
                                                   current_meta.tablet_id(),
2587
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
10.2k
            std::vector<std::string> keys {key};
2591
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
10.2k
        }
2597
44
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
2
                                  num_recycled]() mutable {
2559
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
2
                                                                            keys_to_recheck);
2562
2
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2
        if (keys_to_recheck.empty()) {
2568
0
            return;
2569
0
        }
2570
2571
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
2
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
2
            const auto& current_meta = current_rowset.rowset_meta();
2580
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
2
                                   current_meta.rowset_id_v2()) != 0) {
2582
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
0
                continue;
2584
0
            }
2585
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
2
                                                   current_meta.tablet_id(),
2587
2
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
2
            std::vector<std::string> keys {key};
2591
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
2
        }
2597
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
44
                                  num_recycled]() mutable {
2559
44
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
44
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
44
                                                                            keys_to_recheck);
2562
44
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
44
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
42
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
42
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
42
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
42
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2580
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
10.2k
                                                   current_meta.tablet_id(),
2587
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
10.2k
            std::vector<std::string> keys {key};
2591
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
10.2k
        }
2597
42
    });
2598
46
    if (ret != 0) {
2599
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2600
0
    }
2601
46
}
2602
2603
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2604
                                                      std::vector<std::string> rowset_keys_to_abort,
2605
                                                      std::atomic_long* num_recycled,
2606
5
                                                      RecyclerMetricsContext* metrics_context) {
2607
5
    if (rowset_keys_to_abort.empty()) {
2608
0
        return;
2609
0
    }
2610
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2611
5
                        metrics_context]() mutable {
2612
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
5
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
5
        std::vector<std::string> keys_to_delete;
2623
5
        std::vector<std::string> ref_count_keys_to_delete;
2624
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
5
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
261
            keys_to_delete.push_back(key);
2633
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
261
        }
2637
2638
5
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
5
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
261
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
261
        }
2655
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
3
                        metrics_context]() mutable {
2612
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
3
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
3
        std::vector<std::string> keys_to_delete;
2623
3
        std::vector<std::string> ref_count_keys_to_delete;
2624
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
3
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
3
            keys_to_delete.push_back(key);
2633
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
3
        }
2637
2638
3
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
3
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
3
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
3
        }
2655
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
2
                        metrics_context]() mutable {
2612
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
2
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
2
        std::vector<std::string> keys_to_delete;
2623
2
        std::vector<std::string> ref_count_keys_to_delete;
2624
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
2
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
258
            keys_to_delete.push_back(key);
2633
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
258
        }
2637
2638
2
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
2
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
258
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
258
        }
2655
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
2
    });
2666
5
}
2667
2668
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2669
1
    const std::string task_name = "recycle_ref_rowsets";
2670
1
    *has_unrecycled_rowsets = false;
2671
2672
1
    std::string data_rowset_ref_count_key_start =
2673
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2674
1
    std::string data_rowset_ref_count_key_end =
2675
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2676
2677
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2678
2679
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2680
1
    register_recycle_task(task_name, start_time);
2681
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
2689
2690
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2691
1
    std::set<int64_t> tablets_with_refs;
2692
1
    int64_t num_scanned = 0;
2693
2694
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2695
0
        ++num_scanned;
2696
0
        int64_t tablet_id;
2697
0
        std::string rowset_id;
2698
0
        std::string_view key(k);
2699
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2700
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2701
0
            return 0; // Continue scanning
2702
0
        }
2703
2704
0
        tablets_with_refs.insert(tablet_id);
2705
0
        return 0;
2706
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2707
2708
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2709
1
                         std::move(scan_func)) != 0) {
2710
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2711
0
        return -1;
2712
0
    }
2713
2714
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2715
1
             tablets_with_refs.size(), num_scanned)
2716
1
            .tag("instance_id", instance_id_);
2717
2718
    // Phase 2: Recycle each tablet
2719
1
    int64_t num_recycled_tablets = 0;
2720
1
    for (int64_t tablet_id : tablets_with_refs) {
2721
0
        if (stopped()) {
2722
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2723
0
                    .tag("instance_id", instance_id_)
2724
0
                    .tag("tablets_processed", num_recycled_tablets)
2725
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2726
0
            break;
2727
0
        }
2728
2729
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2730
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2731
0
            LOG_WARNING("failed to recycle tablet")
2732
0
                    .tag("instance_id", instance_id_)
2733
0
                    .tag("tablet_id", tablet_id);
2734
0
            return -1;
2735
0
        }
2736
0
        ++num_recycled_tablets;
2737
0
    }
2738
2739
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2740
1
            .tag("instance_id", instance_id_)
2741
1
            .tag("total_tablets", tablets_with_refs.size());
2742
2743
    // Phase 3: Scan again to check if any ref count keys still exist
2744
1
    std::unique_ptr<Transaction> txn;
2745
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2746
1
    if (err != TxnErrorCode::TXN_OK) {
2747
0
        LOG_WARNING("failed to create txn for final check")
2748
0
                .tag("instance_id", instance_id_)
2749
0
                .tag("err", err);
2750
0
        return -1;
2751
0
    }
2752
2753
1
    std::unique_ptr<RangeGetIterator> iter;
2754
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2755
1
    if (err != TxnErrorCode::TXN_OK) {
2756
0
        LOG_WARNING("failed to create range iterator for final check")
2757
0
                .tag("instance_id", instance_id_)
2758
0
                .tag("err", err);
2759
0
        return -1;
2760
0
    }
2761
2762
1
    *has_unrecycled_rowsets = iter->has_next();
2763
1
    if (*has_unrecycled_rowsets) {
2764
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2765
0
                .tag("instance_id", instance_id_);
2766
0
    }
2767
2768
1
    return 0;
2769
1
}
2770
2771
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2772
16
                                                         RecyclerMetricsContext* metrics_context) {
2773
16
    std::string end = prefix;
2774
16
    end.push_back('\xff');
2775
16
    std::vector<std::string_view> keys;
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
4
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
4
        keys.push_back(key);
2778
4
        return 0;
2779
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
2780
16
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
16
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
16
        DORIS_CLOUD_DEFER {
2785
16
            keys.clear();
2786
16
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
16
        const size_t num_keys = keys.size();
2788
16
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
16
        metrics_context->total_recycled_num += num_keys;
2795
16
        metrics_context->report();
2796
16
        return 0;
2797
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
4
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
4
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
2787
4
        const size_t num_keys = keys.size();
2788
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
4
        metrics_context->total_recycled_num += num_keys;
2795
4
        metrics_context->report();
2796
4
        return 0;
2797
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
12
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
12
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
12
        const size_t num_keys = keys.size();
2788
12
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
12
        metrics_context->total_recycled_num += num_keys;
2795
12
        metrics_context->report();
2796
12
        return 0;
2797
12
    };
2798
16
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2799
16
}
2800
2801
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2802
                                              const RecycleIndexPB& recycle_index,
2803
8
                                              std::string_view recycle_key) {
2804
8
    std::unique_ptr<Transaction> txn;
2805
8
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2806
8
    if (err != TxnErrorCode::TXN_OK) {
2807
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2808
0
                .tag("instance_id", instance_id_)
2809
0
                .tag("stream_id", stream_id)
2810
0
                .tag("err", err);
2811
0
        return -1;
2812
0
    }
2813
2814
8
    std::string current_recycle_value;
2815
8
    err = txn->get(recycle_key, &current_recycle_value);
2816
8
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2817
0
        return 0;
2818
0
    }
2819
8
    if (err != TxnErrorCode::TXN_OK) {
2820
0
        LOG_WARNING("failed to read table stream recycle index")
2821
0
                .tag("instance_id", instance_id_)
2822
0
                .tag("stream_id", stream_id)
2823
0
                .tag("err", err);
2824
0
        return -1;
2825
0
    }
2826
8
    RecycleIndexPB current_recycle_index;
2827
8
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2828
8
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2829
8
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2830
8
        current_recycle_index.db_id() != recycle_index.db_id() ||
2831
8
        current_recycle_index.table_id() != recycle_index.table_id() ||
2832
8
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2833
0
        LOG_WARNING("table stream recycle index changed during recycling")
2834
0
                .tag("instance_id", instance_id_)
2835
0
                .tag("stream_id", stream_id);
2836
0
        return -1;
2837
0
    }
2838
2839
8
    txn->remove(recycle_key);
2840
8
    err = txn->commit();
2841
8
    if (err != TxnErrorCode::TXN_OK) {
2842
0
        LOG_WARNING("failed to commit final table stream cleanup")
2843
0
                .tag("instance_id", instance_id_)
2844
0
                .tag("stream_id", stream_id)
2845
0
                .tag("err", err);
2846
0
        return -1;
2847
0
    }
2848
8
    return 0;
2849
8
}
2850
2851
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2852
8
                                     std::string_view recycle_key) {
2853
8
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2854
0
        LOG_WARNING("table stream recycle index is missing binding")
2855
0
                .tag("instance_id", instance_id_)
2856
0
                .tag("stream_id", stream_id);
2857
0
        return -1;
2858
0
    }
2859
2860
8
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2861
8
    DORIS_CLOUD_DEFER {
2862
8
        metrics_context.finish_report();
2863
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
3
    DORIS_CLOUD_DEFER {
2862
3
        metrics_context.finish_report();
2863
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
5
    DORIS_CLOUD_DEFER {
2862
5
        metrics_context.finish_report();
2863
5
    };
2864
8
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2865
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2866
8
            recycle_index.stream_db_id(), stream_id);
2867
8
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2868
0
        return -1;
2869
0
    }
2870
8
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2871
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2872
8
            recycle_index.stream_db_id(), stream_id);
2873
8
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2874
8
        stopped()) {
2875
0
        return -1;
2876
0
    }
2877
8
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2878
8
}
2879
2880
int InstanceRecycler::recycle_partition_table_stream_offsets(
2881
        int64_t db_id, int64_t table_id, int64_t partition_id,
2882
12
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2883
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2884
12
    DORIS_CLOUD_DEFER {
2885
12
        metrics_context.finish_report();
2886
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
1
    DORIS_CLOUD_DEFER {
2885
1
        metrics_context.finish_report();
2886
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
11
    DORIS_CLOUD_DEFER {
2885
11
        metrics_context.finish_report();
2886
11
    };
2887
12
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2888
17
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2889
5
        const size_t end_index =
2890
5
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2891
5
        std::unique_ptr<Transaction> txn;
2892
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2893
5
        if (err != TxnErrorCode::TXN_OK) {
2894
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2895
0
                    .tag("instance_id", instance_id_)
2896
0
                    .tag("partition_id", partition_id)
2897
0
                    .tag("err", err);
2898
0
            return -1;
2899
0
        }
2900
12
        for (size_t i = begin_index; i < end_index; ++i) {
2901
7
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2902
7
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2903
7
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2904
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2905
0
                        .tag("instance_id", instance_id_)
2906
0
                        .tag("partition_id", partition_id)
2907
0
                        .tag("stream_id", stream.stream_id());
2908
0
                return -1;
2909
0
            }
2910
7
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2911
7
                                                 stream.base_table_id(), stream.stream_db_id(),
2912
7
                                                 stream.stream_id(), partition_id}));
2913
7
            versioned_remove_all(
2914
7
                    txn.get(), versioned::table_stream_offset_key(
2915
7
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2916
7
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2917
7
        }
2918
5
        err = txn->commit();
2919
5
        if (err != TxnErrorCode::TXN_OK) {
2920
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2921
0
                    .tag("instance_id", instance_id_)
2922
0
                    .tag("partition_id", partition_id)
2923
0
                    .tag("err", err);
2924
0
            return -1;
2925
0
        }
2926
5
        metrics_context.total_recycled_num += end_index - begin_index;
2927
5
        metrics_context.report();
2928
5
    }
2929
12
    return 0;
2930
12
}
2931
2932
25
int InstanceRecycler::recycle_indexes() {
2933
25
    const std::string task_name = "recycle_indexes";
2934
25
    int64_t num_scanned = 0;
2935
25
    int64_t num_expired = 0;
2936
25
    int64_t num_recycled = 0;
2937
25
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2938
2939
25
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2940
25
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2941
25
    std::string index_key0;
2942
25
    std::string index_key1;
2943
25
    recycle_index_key(index_key_info0, &index_key0);
2944
25
    recycle_index_key(index_key_info1, &index_key1);
2945
2946
25
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2947
2948
25
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2949
25
    register_recycle_task(task_name, start_time);
2950
2951
25
    DORIS_CLOUD_DEFER {
2952
25
        unregister_recycle_task(task_name);
2953
25
        int64_t cost =
2954
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
25
        metrics_context.finish_report();
2956
25
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
25
                .tag("instance_id", instance_id_)
2958
25
                .tag("num_scanned", num_scanned)
2959
25
                .tag("num_expired", num_expired)
2960
25
                .tag("num_recycled", num_recycled);
2961
25
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
4
    DORIS_CLOUD_DEFER {
2952
4
        unregister_recycle_task(task_name);
2953
4
        int64_t cost =
2954
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
4
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
4
                .tag("instance_id", instance_id_)
2958
4
                .tag("num_scanned", num_scanned)
2959
4
                .tag("num_expired", num_expired)
2960
4
                .tag("num_recycled", num_recycled);
2961
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
21
    DORIS_CLOUD_DEFER {
2952
21
        unregister_recycle_task(task_name);
2953
21
        int64_t cost =
2954
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
21
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
21
                .tag("instance_id", instance_id_)
2958
21
                .tag("num_scanned", num_scanned)
2959
21
                .tag("num_expired", num_expired)
2960
21
                .tag("num_recycled", num_recycled);
2961
21
    };
2962
2963
25
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2964
2965
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2966
25
    std::vector<std::string_view> index_keys;
2967
25
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
18
        ++num_scanned;
2969
18
        RecycleIndexPB index_pb;
2970
18
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
18
        int64_t current_time = ::time(nullptr);
2975
18
        if (current_time <
2976
18
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
18
        ++num_expired;
2980
        // decode index_id
2981
18
        auto k1 = k;
2982
18
        k1.remove_prefix(1);
2983
18
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
18
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
18
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
18
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
18
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
18
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
18
        std::unique_ptr<Transaction> txn;
2992
18
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
18
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
18
        std::string val;
2998
18
        err = txn->get(k, &val);
2999
18
        if (err ==
3000
18
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
18
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
18
        index_pb.Clear();
3009
18
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
18
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
16
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
16
            txn->put(k, index_pb.SerializeAsString());
3016
16
            err = txn->commit();
3017
16
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
16
        }
3022
18
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
8
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
8
            metrics_context.total_recycled_num = ++num_recycled;
3030
8
            metrics_context.report();
3031
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
8
            return 0;
3033
8
        }
3034
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
9
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
3
            std::unique_ptr<Transaction> txn;
3045
3
            err = txn_kv_->create_txn(&txn);
3046
3
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
3
            std::string index_inverted_key = versioned::index_inverted_key(
3053
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
3
            versioned_remove_all(txn.get(), meta_key);
3055
3
            txn->remove(index_key);
3056
3
            txn->remove(index_inverted_key);
3057
3
            err = txn->commit();
3058
3
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
3
        }
3063
3064
9
        metrics_context.total_recycled_num = ++num_recycled;
3065
9
        metrics_context.report();
3066
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
9
        index_keys.push_back(k);
3068
9
        return 0;
3069
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
5
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
5
        ++num_scanned;
2969
5
        RecycleIndexPB index_pb;
2970
5
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
5
        int64_t current_time = ::time(nullptr);
2975
5
        if (current_time <
2976
5
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
5
        ++num_expired;
2980
        // decode index_id
2981
5
        auto k1 = k;
2982
5
        k1.remove_prefix(1);
2983
5
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
5
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
5
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
5
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
5
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
5
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
5
        std::unique_ptr<Transaction> txn;
2992
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
5
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
5
        std::string val;
2998
5
        err = txn->get(k, &val);
2999
5
        if (err ==
3000
5
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
5
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
5
        index_pb.Clear();
3009
5
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
5
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
4
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
4
            txn->put(k, index_pb.SerializeAsString());
3016
4
            err = txn->commit();
3017
4
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
4
        }
3022
5
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
3
            metrics_context.total_recycled_num = ++num_recycled;
3030
3
            metrics_context.report();
3031
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
3
            return 0;
3033
3
        }
3034
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
1
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
1
            std::unique_ptr<Transaction> txn;
3045
1
            err = txn_kv_->create_txn(&txn);
3046
1
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
1
            std::string index_inverted_key = versioned::index_inverted_key(
3053
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
1
            versioned_remove_all(txn.get(), meta_key);
3055
1
            txn->remove(index_key);
3056
1
            txn->remove(index_inverted_key);
3057
1
            err = txn->commit();
3058
1
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
1
        }
3063
3064
1
        metrics_context.total_recycled_num = ++num_recycled;
3065
1
        metrics_context.report();
3066
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
1
        index_keys.push_back(k);
3068
1
        return 0;
3069
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
13
        ++num_scanned;
2969
13
        RecycleIndexPB index_pb;
2970
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
13
        int64_t current_time = ::time(nullptr);
2975
13
        if (current_time <
2976
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
13
        ++num_expired;
2980
        // decode index_id
2981
13
        auto k1 = k;
2982
13
        k1.remove_prefix(1);
2983
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
13
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
13
        std::unique_ptr<Transaction> txn;
2992
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
13
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
13
        std::string val;
2998
13
        err = txn->get(k, &val);
2999
13
        if (err ==
3000
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
13
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
13
        index_pb.Clear();
3009
13
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
12
            txn->put(k, index_pb.SerializeAsString());
3016
12
            err = txn->commit();
3017
12
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
12
        }
3022
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
5
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
5
            metrics_context.total_recycled_num = ++num_recycled;
3030
5
            metrics_context.report();
3031
5
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
5
            return 0;
3033
5
        }
3034
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
0
            LOG_WARNING("failed to recycle tablets under index")
3036
0
                    .tag("table_id", index_pb.table_id())
3037
0
                    .tag("instance_id", instance_id_)
3038
0
                    .tag("index_id", index_id);
3039
0
            return -1;
3040
0
        }
3041
3042
8
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
2
            std::unique_ptr<Transaction> txn;
3045
2
            err = txn_kv_->create_txn(&txn);
3046
2
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
2
            std::string index_inverted_key = versioned::index_inverted_key(
3053
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
2
            versioned_remove_all(txn.get(), meta_key);
3055
2
            txn->remove(index_key);
3056
2
            txn->remove(index_inverted_key);
3057
2
            err = txn->commit();
3058
2
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
2
        }
3063
3064
8
        metrics_context.total_recycled_num = ++num_recycled;
3065
8
        metrics_context.report();
3066
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
8
        index_keys.push_back(k);
3068
8
        return 0;
3069
8
    };
3070
3071
25
    auto loop_done = [&index_keys, this]() -> int {
3072
13
        if (index_keys.empty()) return 0;
3073
5
        DORIS_CLOUD_DEFER {
3074
5
            index_keys.clear();
3075
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
5
        return 0;
3081
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
4
    auto loop_done = [&index_keys, this]() -> int {
3072
4
        if (index_keys.empty()) return 0;
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
3076
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
1
        return 0;
3081
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
9
    auto loop_done = [&index_keys, this]() -> int {
3072
9
        if (index_keys.empty()) return 0;
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
4
        return 0;
3081
4
    };
3082
3083
25
    if (config::enable_recycler_stats_metrics) {
3084
0
        scan_and_statistics_indexes();
3085
0
    }
3086
    // recycle_func and loop_done for scan and recycle
3087
25
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3088
25
}
3089
3090
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3091
8.25k
                             int64_t tablet_id) {
3092
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3093
3094
8.25k
    std::unique_ptr<Transaction> txn;
3095
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3096
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3097
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3098
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3099
0
        return false;
3100
0
    }
3101
3102
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3103
8.25k
    std::string tablet_idx_val;
3104
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3105
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3106
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3107
0
                     << " tablet_id=" << tablet_id << " err=" << err
3108
0
                     << " key=" << hex(tablet_idx_key);
3109
0
        return false;
3110
0
    }
3111
3112
8.25k
    TabletIndexPB tablet_idx_pb;
3113
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3114
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3115
0
                     << " tablet_id=" << tablet_id;
3116
0
        return false;
3117
0
    }
3118
3119
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3120
        // In the previous version, the db_id was not set in the index_pb.
3121
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3122
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3123
0
                  << " instance_id=" << instance_id
3124
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3125
0
        return true;
3126
0
    }
3127
3128
8.25k
    std::string ver_val;
3129
8.25k
    std::string ver_key =
3130
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3131
8.25k
                                   tablet_idx_pb.partition_id()});
3132
8.25k
    err = txn->get(ver_key, &ver_val);
3133
3134
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3135
216
        LOG(INFO) << ""
3136
216
                     "partition version not found, instance_id="
3137
216
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3138
216
                  << " table_id=" << tablet_idx_pb.table_id()
3139
216
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3140
216
                  << " key=" << hex(ver_key);
3141
216
        return true;
3142
216
    }
3143
3144
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3145
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3146
0
                     << " db_id=" << tablet_idx_pb.db_id()
3147
0
                     << " table_id=" << tablet_idx_pb.table_id()
3148
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3149
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3150
0
        return false;
3151
0
    }
3152
3153
8.03k
    VersionPB version_pb;
3154
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3155
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3156
0
                     << " db_id=" << tablet_idx_pb.db_id()
3157
0
                     << " table_id=" << tablet_idx_pb.table_id()
3158
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3159
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3160
0
        return false;
3161
0
    }
3162
3163
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3164
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3165
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3166
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3167
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3168
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3169
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3170
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3171
4.00k
                     << " key=" << hex(ver_key);
3172
4.00k
        return false;
3173
4.00k
    }
3174
4.03k
    return true;
3175
8.03k
}
3176
3177
20
int InstanceRecycler::recycle_partitions() {
3178
20
    const std::string task_name = "recycle_partitions";
3179
20
    int64_t num_scanned = 0;
3180
20
    int64_t num_expired = 0;
3181
20
    int64_t num_recycled = 0;
3182
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3183
3184
20
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3185
20
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3186
20
    std::string part_key0;
3187
20
    std::string part_key1;
3188
20
    recycle_partition_key(part_key_info0, &part_key0);
3189
20
    recycle_partition_key(part_key_info1, &part_key1);
3190
3191
20
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3192
3193
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3194
20
    register_recycle_task(task_name, start_time);
3195
3196
20
    DORIS_CLOUD_DEFER {
3197
20
        unregister_recycle_task(task_name);
3198
20
        int64_t cost =
3199
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
20
        metrics_context.finish_report();
3201
20
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
20
                .tag("instance_id", instance_id_)
3203
20
                .tag("num_scanned", num_scanned)
3204
20
                .tag("num_expired", num_expired)
3205
20
                .tag("num_recycled", num_recycled);
3206
20
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
2
    DORIS_CLOUD_DEFER {
3197
2
        unregister_recycle_task(task_name);
3198
2
        int64_t cost =
3199
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
2
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
2
                .tag("instance_id", instance_id_)
3203
2
                .tag("num_scanned", num_scanned)
3204
2
                .tag("num_expired", num_expired)
3205
2
                .tag("num_recycled", num_recycled);
3206
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
18
    DORIS_CLOUD_DEFER {
3197
18
        unregister_recycle_task(task_name);
3198
18
        int64_t cost =
3199
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
18
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
18
                .tag("instance_id", instance_id_)
3203
18
                .tag("num_scanned", num_scanned)
3204
18
                .tag("num_expired", num_expired)
3205
18
                .tag("num_recycled", num_recycled);
3206
18
    };
3207
3208
20
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3209
3210
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3211
20
    std::vector<std::string_view> partition_keys;
3212
20
    std::vector<std::string> partition_version_keys;
3213
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
13
        ++num_scanned;
3215
13
        RecyclePartitionPB part_pb;
3216
13
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
13
        int64_t current_time = ::time(nullptr);
3221
13
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
13
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
13
        ++num_expired;
3226
        // decode partition_id
3227
13
        auto k1 = k;
3228
13
        k1.remove_prefix(1);
3229
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
13
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
13
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
13
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
13
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
13
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
13
        std::unique_ptr<Transaction> txn;
3238
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
13
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
13
        std::string val;
3244
13
        err = txn->get(k, &val);
3245
13
        if (err ==
3246
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
13
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
13
        part_pb.Clear();
3255
13
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
13
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
11
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
11
            txn->put(k, part_pb.SerializeAsString());
3263
11
            err = txn->commit();
3264
11
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
11
        }
3269
3270
13
        int ret = 0;
3271
37
        for (int64_t index_id : part_pb.index_id()) {
3272
37
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
37
        }
3281
13
        if (ret == 0 && part_pb.has_db_id() &&
3282
13
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
12
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
13
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
12
            std::unique_ptr<Transaction> txn;
3293
12
            err = txn_kv_->create_txn(&txn);
3294
12
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
12
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
12
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
12
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
12
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
12
            std::string partition_version_key =
3303
12
                    versioned::partition_version_key({instance_id_, partition_id});
3304
12
            versioned_remove_all(txn.get(), meta_key);
3305
12
            txn->remove(index_key);
3306
12
            txn->remove(inverted_index_key);
3307
12
            versioned_remove_all(txn.get(), partition_version_key);
3308
12
            err = txn->commit();
3309
12
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
12
        }
3314
3315
13
        if (ret == 0) {
3316
12
            ++num_recycled;
3317
12
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
12
            partition_keys.push_back(k);
3319
12
            if (part_pb.db_id() > 0) {
3320
12
                partition_version_keys.push_back(partition_version_key(
3321
12
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
12
            }
3323
12
            metrics_context.total_recycled_num = num_recycled;
3324
12
            metrics_context.report();
3325
12
        }
3326
13
        return ret;
3327
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
2
        ++num_scanned;
3215
2
        RecyclePartitionPB part_pb;
3216
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
2
        int64_t current_time = ::time(nullptr);
3221
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
2
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
2
        ++num_expired;
3226
        // decode partition_id
3227
2
        auto k1 = k;
3228
2
        k1.remove_prefix(1);
3229
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
2
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
2
        std::unique_ptr<Transaction> txn;
3238
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
2
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
2
        std::string val;
3244
2
        err = txn->get(k, &val);
3245
2
        if (err ==
3246
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
2
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
2
        part_pb.Clear();
3255
2
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
1
            txn->put(k, part_pb.SerializeAsString());
3263
1
            err = txn->commit();
3264
1
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
1
        }
3269
3270
2
        int ret = 0;
3271
2
        for (int64_t index_id : part_pb.index_id()) {
3272
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
2
        }
3281
2
        if (ret == 0 && part_pb.has_db_id() &&
3282
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
2
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
1
            std::unique_ptr<Transaction> txn;
3293
1
            err = txn_kv_->create_txn(&txn);
3294
1
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
1
            std::string partition_version_key =
3303
1
                    versioned::partition_version_key({instance_id_, partition_id});
3304
1
            versioned_remove_all(txn.get(), meta_key);
3305
1
            txn->remove(index_key);
3306
1
            txn->remove(inverted_index_key);
3307
1
            versioned_remove_all(txn.get(), partition_version_key);
3308
1
            err = txn->commit();
3309
1
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
1
        }
3314
3315
2
        if (ret == 0) {
3316
1
            ++num_recycled;
3317
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
1
            partition_keys.push_back(k);
3319
1
            if (part_pb.db_id() > 0) {
3320
1
                partition_version_keys.push_back(partition_version_key(
3321
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
1
            }
3323
1
            metrics_context.total_recycled_num = num_recycled;
3324
1
            metrics_context.report();
3325
1
        }
3326
2
        return ret;
3327
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
11
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
11
        ++num_scanned;
3215
11
        RecyclePartitionPB part_pb;
3216
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
11
        int64_t current_time = ::time(nullptr);
3221
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
11
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
11
        ++num_expired;
3226
        // decode partition_id
3227
11
        auto k1 = k;
3228
11
        k1.remove_prefix(1);
3229
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
11
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
11
        std::unique_ptr<Transaction> txn;
3238
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
11
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
11
        std::string val;
3244
11
        err = txn->get(k, &val);
3245
11
        if (err ==
3246
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
11
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
11
        part_pb.Clear();
3255
11
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
10
            txn->put(k, part_pb.SerializeAsString());
3263
10
            err = txn->commit();
3264
10
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
10
        }
3269
3270
11
        int ret = 0;
3271
35
        for (int64_t index_id : part_pb.index_id()) {
3272
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
0
                LOG_WARNING("failed to recycle tablets under partition")
3274
0
                        .tag("table_id", part_pb.table_id())
3275
0
                        .tag("instance_id", instance_id_)
3276
0
                        .tag("index_id", index_id)
3277
0
                        .tag("partition_id", partition_id);
3278
0
                ret = -1;
3279
0
            }
3280
35
        }
3281
11
        if (ret == 0 && part_pb.has_db_id() &&
3282
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
11
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
11
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
11
            std::unique_ptr<Transaction> txn;
3293
11
            err = txn_kv_->create_txn(&txn);
3294
11
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
11
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
11
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
11
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
11
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
11
            std::string partition_version_key =
3303
11
                    versioned::partition_version_key({instance_id_, partition_id});
3304
11
            versioned_remove_all(txn.get(), meta_key);
3305
11
            txn->remove(index_key);
3306
11
            txn->remove(inverted_index_key);
3307
11
            versioned_remove_all(txn.get(), partition_version_key);
3308
11
            err = txn->commit();
3309
11
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
11
        }
3314
3315
11
        if (ret == 0) {
3316
11
            ++num_recycled;
3317
11
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
11
            partition_keys.push_back(k);
3319
11
            if (part_pb.db_id() > 0) {
3320
11
                partition_version_keys.push_back(partition_version_key(
3321
11
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
11
            }
3323
11
            metrics_context.total_recycled_num = num_recycled;
3324
11
            metrics_context.report();
3325
11
        }
3326
11
        return ret;
3327
11
    };
3328
3329
20
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
9
        if (partition_keys.empty()) return 0;
3331
8
        DORIS_CLOUD_DEFER {
3332
8
            partition_keys.clear();
3333
8
            partition_version_keys.clear();
3334
8
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
8
        std::unique_ptr<Transaction> txn;
3336
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
8
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
12
        for (auto& k : partition_keys) {
3342
12
            txn->remove(k);
3343
12
        }
3344
12
        for (auto& k : partition_version_keys) {
3345
12
            txn->remove(k);
3346
12
        }
3347
8
        err = txn->commit();
3348
8
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
8
        return 0;
3354
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
2
        if (partition_keys.empty()) return 0;
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
3335
1
        std::unique_ptr<Transaction> txn;
3336
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
1
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
1
        for (auto& k : partition_keys) {
3342
1
            txn->remove(k);
3343
1
        }
3344
1
        for (auto& k : partition_version_keys) {
3345
1
            txn->remove(k);
3346
1
        }
3347
1
        err = txn->commit();
3348
1
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
1
        return 0;
3354
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
7
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
7
        if (partition_keys.empty()) return 0;
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
7
        std::unique_ptr<Transaction> txn;
3336
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
7
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
11
        for (auto& k : partition_keys) {
3342
11
            txn->remove(k);
3343
11
        }
3344
11
        for (auto& k : partition_version_keys) {
3345
11
            txn->remove(k);
3346
11
        }
3347
7
        err = txn->commit();
3348
7
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
7
        return 0;
3354
7
    };
3355
3356
20
    if (config::enable_recycler_stats_metrics) {
3357
0
        scan_and_statistics_partitions();
3358
0
    }
3359
    // recycle_func and loop_done for scan and recycle
3360
20
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3361
20
}
3362
3363
14
int InstanceRecycler::recycle_versions() {
3364
14
    if (should_recycle_versioned_keys()) {
3365
2
        return recycle_orphan_partitions();
3366
2
    }
3367
3368
12
    int64_t num_scanned = 0;
3369
12
    int64_t num_recycled = 0;
3370
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3371
3372
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3373
3374
12
    auto start_time = steady_clock::now();
3375
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
3384
3385
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3386
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3387
12
    int64_t last_scanned_table_id = 0;
3388
12
    bool is_recycled = false; // Is last scanned kv recycled
3389
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3390
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3390
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
3453
3454
12
    if (config::enable_recycler_stats_metrics) {
3455
0
        scan_and_statistics_versions();
3456
0
    }
3457
    // recycle_func and loop_done for scan and recycle
3458
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3459
14
}
3460
3461
3
int InstanceRecycler::recycle_orphan_partitions() {
3462
3
    int64_t num_scanned = 0;
3463
3
    int64_t num_recycled = 0;
3464
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3465
3466
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3467
3
            .tag("instance_id", instance_id_);
3468
3469
3
    auto start_time = steady_clock::now();
3470
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
3479
3480
3
    bool is_empty_table = false;        // whether the table has no indexes
3481
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3482
3
    int64_t current_table_id = 0;       // current scanning table id
3483
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3484
3
                         &current_table_id, &is_table_kvs_recycled,
3485
3
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3485
2
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
1
    };
3563
3564
    // recycle_func and loop_done for scan and recycle
3565
3
    return scan_and_recycle(
3566
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3567
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3568
3
            std::move(recycle_func));
3569
3
}
3570
3571
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3572
                                      RecyclerMetricsContext& metrics_context,
3573
58
                                      int64_t partition_id) {
3574
58
    int64_t num_scanned = 0;
3575
58
    std::atomic_long num_recycled = 0;
3576
3577
58
    std::string tablet_key_begin, tablet_key_end;
3578
58
    std::string stats_key_begin, stats_key_end;
3579
58
    std::string job_key_begin, job_key_end;
3580
3581
58
    std::string tablet_belongs;
3582
58
    if (partition_id > 0) {
3583
        // recycle tablets in a partition belonging to the index
3584
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3585
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3586
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3587
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3588
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3589
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3590
37
        tablet_belongs = "partition";
3591
37
    } else {
3592
        // recycle tablets in the index
3593
21
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3594
21
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3595
21
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3596
21
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3597
21
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3598
21
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3599
21
        tablet_belongs = "index";
3600
21
    }
3601
3602
58
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3603
58
            .tag("table_id", table_id)
3604
58
            .tag("index_id", index_id)
3605
58
            .tag("partition_id", partition_id);
3606
3607
58
    auto start_time = steady_clock::now();
3608
3609
58
    DORIS_CLOUD_DEFER {
3610
58
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3611
58
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3612
58
                .tag("instance_id", instance_id_)
3613
58
                .tag("table_id", table_id)
3614
58
                .tag("index_id", index_id)
3615
58
                .tag("partition_id", partition_id)
3616
58
                .tag("num_scanned", num_scanned)
3617
58
                .tag("num_recycled", num_recycled);
3618
58
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3609
4
    DORIS_CLOUD_DEFER {
3610
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3611
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3612
4
                .tag("instance_id", instance_id_)
3613
4
                .tag("table_id", table_id)
3614
4
                .tag("index_id", index_id)
3615
4
                .tag("partition_id", partition_id)
3616
4
                .tag("num_scanned", num_scanned)
3617
4
                .tag("num_recycled", num_recycled);
3618
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3609
54
    DORIS_CLOUD_DEFER {
3610
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3611
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3612
54
                .tag("instance_id", instance_id_)
3613
54
                .tag("table_id", table_id)
3614
54
                .tag("index_id", index_id)
3615
54
                .tag("partition_id", partition_id)
3616
54
                .tag("num_scanned", num_scanned)
3617
54
                .tag("num_recycled", num_recycled);
3618
54
    };
3619
3620
    // The tablet key and id which have been recycled.
3621
58
    struct TabletInfo {
3622
58
        std::string_view tablet_meta_key;
3623
58
        int64_t tablet_id;
3624
58
    };
3625
58
    SyncExecutor<TabletInfo> sync_executor(
3626
58
            _thread_pool_group.recycle_tablet_pool,
3627
58
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3628
58
                        index_id, partition_id),
3629
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3629
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3629
243
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3630
3631
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3632
58
    std::vector<std::string> init_rs_keys;
3633
58
    bool has_failure = false;
3634
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3635
8.25k
        ++num_scanned;
3636
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3637
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3638
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3639
0
            has_failure = true;
3640
0
            return -1;
3641
0
        }
3642
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3643
3644
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3645
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3646
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3647
4.00k
            has_failure = true;
3648
4.00k
            return -1;
3649
4.00k
        }
3650
3651
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3652
4.25k
        sync_executor.add(
3653
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3654
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3655
2
                        LOG_WARNING("failed to recycle tablet")
3656
2
                                .tag("instance_id", instance_id_)
3657
2
                                .tag("tablet_id", tid);
3658
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3659
2
                    }
3660
4.25k
                    ++num_recycled;
3661
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3662
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3663
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3653
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3654
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3655
0
                        LOG_WARNING("failed to recycle tablet")
3656
0
                                .tag("instance_id", instance_id_)
3657
0
                                .tag("tablet_id", tid);
3658
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3659
0
                    }
3660
4.00k
                    ++num_recycled;
3661
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3662
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3663
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3653
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3654
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3655
2
                        LOG_WARNING("failed to recycle tablet")
3656
2
                                .tag("instance_id", instance_id_)
3657
2
                                .tag("tablet_id", tid);
3658
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3659
2
                    }
3660
250
                    ++num_recycled;
3661
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3662
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3663
252
                });
3664
4.25k
        return 0;
3665
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3634
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3635
8.00k
        ++num_scanned;
3636
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3637
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3638
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3639
0
            has_failure = true;
3640
0
            return -1;
3641
0
        }
3642
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3643
3644
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3645
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3646
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3647
4.00k
            has_failure = true;
3648
4.00k
            return -1;
3649
4.00k
        }
3650
3651
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3652
4.00k
        sync_executor.add(
3653
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3654
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3655
4.00k
                        LOG_WARNING("failed to recycle tablet")
3656
4.00k
                                .tag("instance_id", instance_id_)
3657
4.00k
                                .tag("tablet_id", tid);
3658
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3659
4.00k
                    }
3660
4.00k
                    ++num_recycled;
3661
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3662
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3663
4.00k
                });
3664
4.00k
        return 0;
3665
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3634
253
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3635
253
        ++num_scanned;
3636
253
        doris::TabletMetaCloudPB tablet_meta_pb;
3637
253
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3638
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3639
0
            has_failure = true;
3640
0
            return -1;
3641
0
        }
3642
253
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3643
3644
253
        if (config::enable_recycler_check_lazy_txn_finished &&
3645
253
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3646
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3647
1
            has_failure = true;
3648
1
            return -1;
3649
1
        }
3650
3651
253
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3652
252
        sync_executor.add(
3653
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3654
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3655
252
                        LOG_WARNING("failed to recycle tablet")
3656
252
                                .tag("instance_id", instance_id_)
3657
252
                                .tag("tablet_id", tid);
3658
252
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3659
252
                    }
3660
252
                    ++num_recycled;
3661
252
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3662
252
                    return {.tablet_meta_key = k, .tablet_id = tid};
3663
252
                });
3664
252
        return 0;
3665
252
    };
3666
3667
58
    auto loop_done = [&, this]() -> int {
3668
54
        int ret = 0;
3669
54
        bool finished = true;
3670
54
        bool has_empty_key = false;
3671
54
        DORIS_CLOUD_DEFER {
3672
54
            init_rs_keys.clear();
3673
54
            has_failure = false;
3674
54
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3671
4
        DORIS_CLOUD_DEFER {
3672
4
            init_rs_keys.clear();
3673
4
            has_failure = false;
3674
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3671
50
        DORIS_CLOUD_DEFER {
3672
50
            init_rs_keys.clear();
3673
50
            has_failure = false;
3674
50
        };
3675
54
        auto tablets_info = sync_executor.when_all(&finished);
3676
54
        if (!finished) {
3677
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3678
1
            return -1;
3679
1
        }
3680
3681
53
        size_t size_before_erase = tablets_info.size();
3682
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3682
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3682
251
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3683
53
        if (tablets_info.empty()) {
3684
2
            return size_before_erase == 0 ? 0 : -1;
3685
51
        } else if (size_before_erase != tablets_info.size()) {
3686
1
            has_empty_key = true;
3687
1
        }
3688
3689
51
        ret = has_empty_key ? -1 : 0;
3690
        // sort the vector using key's order
3691
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3692
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3693
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3691
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3692
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3693
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3691
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3692
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3693
958
        });
3694
51
        std::unique_ptr<Transaction> txn;
3695
51
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3697
0
            return -1;
3698
0
        }
3699
51
        std::string tablet_key_end;
3700
51
        if (!tablets_info.empty()) {
3701
51
            if (!has_empty_key && !has_failure) {
3702
49
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3703
49
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3704
49
            } else {
3705
8
                for (auto& tablet_info : tablets_info) {
3706
8
                    txn->remove(tablet_info.tablet_meta_key);
3707
8
                }
3708
2
            }
3709
51
        }
3710
51
        if (should_recycle_versioned_keys()) {
3711
            // Remove tablet indexes in the same transaction as tablet metadata.
3712
7
            std::vector<std::string> versioned_idx_keys;
3713
7
            versioned_idx_keys.reserve(tablets_info.size());
3714
8
            for (const auto& tablet_info : tablets_info) {
3715
8
                versioned_idx_keys.push_back(
3716
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3717
8
            }
3718
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3719
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3720
7
            if (err != TxnErrorCode::TXN_OK) {
3721
0
                LOG_WARNING("failed to batch get tablet index kv")
3722
0
                        .tag("instance_id", instance_id_)
3723
0
                        .tag("num_tablets", tablets_info.size())
3724
0
                        .tag("err", err);
3725
0
                return -1;
3726
0
            }
3727
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3728
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3729
8
                if (!tablet_index_vals[i].has_value()) {
3730
0
                    continue;
3731
0
                }
3732
8
                const auto& tablet_info = tablets_info[i];
3733
8
                TabletIndexPB tablet_index_pb;
3734
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3735
0
                    LOG_WARNING("failed to parse tablet index pb")
3736
0
                            .tag("instance_id", instance_id_)
3737
0
                            .tag("tablet_id", tablet_info.tablet_id);
3738
0
                    return -1;
3739
0
                }
3740
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3741
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3742
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3743
8
                         tablet_info.tablet_id});
3744
8
                txn->remove(versioned_inverted_idx_key);
3745
8
                txn->remove(versioned_idx_keys[i]);
3746
8
            }
3747
8
            for (auto& tablet_info : tablets_info) {
3748
                // Remove all versions of tablet compact stats for recycled tablet
3749
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3750
8
                LOG_INFO("remove versioned tablet compact stats key")
3751
8
                        .tag("compact_stats_key", hex(k));
3752
8
                versioned_remove_all(txn.get(), k);
3753
8
            }
3754
8
            for (auto& tablet_info : tablets_info) {
3755
                // Remove all versions of tablet load stats for recycled tablet
3756
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3757
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3758
8
                versioned_remove_all(txn.get(), k);
3759
8
            }
3760
8
            for (auto& tablet_info : tablets_info) {
3761
                // Remove all versions of meta tablet for recycled tablet
3762
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3763
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3764
8
                versioned_remove_all(txn.get(), k);
3765
8
            }
3766
7
        }
3767
4.25k
        for (auto& tablet_info : tablets_info) {
3768
4.25k
            std::string k;
3769
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3770
4.25k
            txn->remove(k);
3771
4.25k
        }
3772
4.25k
        for (auto& tablet_info : tablets_info) {
3773
4.25k
            std::string k;
3774
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3775
4.25k
            txn->remove(k);
3776
4.25k
        }
3777
51
        for (auto& k : init_rs_keys) {
3778
0
            txn->remove(k);
3779
0
        }
3780
51
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3781
51
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3782
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3783
1
                         << ", err=" << err;
3784
1
            return -1;
3785
1
        }
3786
50
        return ret;
3787
51
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3667
4
    auto loop_done = [&, this]() -> int {
3668
4
        int ret = 0;
3669
4
        bool finished = true;
3670
4
        bool has_empty_key = false;
3671
4
        DORIS_CLOUD_DEFER {
3672
4
            init_rs_keys.clear();
3673
4
            has_failure = false;
3674
4
        };
3675
4
        auto tablets_info = sync_executor.when_all(&finished);
3676
4
        if (!finished) {
3677
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3678
0
            return -1;
3679
0
        }
3680
3681
4
        size_t size_before_erase = tablets_info.size();
3682
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3683
4
        if (tablets_info.empty()) {
3684
2
            return size_before_erase == 0 ? 0 : -1;
3685
2
        } else if (size_before_erase != tablets_info.size()) {
3686
0
            has_empty_key = true;
3687
0
        }
3688
3689
2
        ret = has_empty_key ? -1 : 0;
3690
        // sort the vector using key's order
3691
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3692
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3693
2
        });
3694
2
        std::unique_ptr<Transaction> txn;
3695
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3697
0
            return -1;
3698
0
        }
3699
2
        std::string tablet_key_end;
3700
2
        if (!tablets_info.empty()) {
3701
2
            if (!has_empty_key && !has_failure) {
3702
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3703
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3704
2
            } else {
3705
0
                for (auto& tablet_info : tablets_info) {
3706
0
                    txn->remove(tablet_info.tablet_meta_key);
3707
0
                }
3708
0
            }
3709
2
        }
3710
2
        if (should_recycle_versioned_keys()) {
3711
            // Remove tablet indexes in the same transaction as tablet metadata.
3712
0
            std::vector<std::string> versioned_idx_keys;
3713
0
            versioned_idx_keys.reserve(tablets_info.size());
3714
0
            for (const auto& tablet_info : tablets_info) {
3715
0
                versioned_idx_keys.push_back(
3716
0
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3717
0
            }
3718
0
            std::vector<std::optional<std::string>> tablet_index_vals;
3719
0
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3720
0
            if (err != TxnErrorCode::TXN_OK) {
3721
0
                LOG_WARNING("failed to batch get tablet index kv")
3722
0
                        .tag("instance_id", instance_id_)
3723
0
                        .tag("num_tablets", tablets_info.size())
3724
0
                        .tag("err", err);
3725
0
                return -1;
3726
0
            }
3727
0
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3728
0
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3729
0
                if (!tablet_index_vals[i].has_value()) {
3730
0
                    continue;
3731
0
                }
3732
0
                const auto& tablet_info = tablets_info[i];
3733
0
                TabletIndexPB tablet_index_pb;
3734
0
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3735
0
                    LOG_WARNING("failed to parse tablet index pb")
3736
0
                            .tag("instance_id", instance_id_)
3737
0
                            .tag("tablet_id", tablet_info.tablet_id);
3738
0
                    return -1;
3739
0
                }
3740
0
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3741
0
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3742
0
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3743
0
                         tablet_info.tablet_id});
3744
0
                txn->remove(versioned_inverted_idx_key);
3745
0
                txn->remove(versioned_idx_keys[i]);
3746
0
            }
3747
0
            for (auto& tablet_info : tablets_info) {
3748
                // Remove all versions of tablet compact stats for recycled tablet
3749
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3750
0
                LOG_INFO("remove versioned tablet compact stats key")
3751
0
                        .tag("compact_stats_key", hex(k));
3752
0
                versioned_remove_all(txn.get(), k);
3753
0
            }
3754
0
            for (auto& tablet_info : tablets_info) {
3755
                // Remove all versions of tablet load stats for recycled tablet
3756
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3757
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3758
0
                versioned_remove_all(txn.get(), k);
3759
0
            }
3760
0
            for (auto& tablet_info : tablets_info) {
3761
                // Remove all versions of meta tablet for recycled tablet
3762
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3763
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3764
0
                versioned_remove_all(txn.get(), k);
3765
0
            }
3766
0
        }
3767
4.00k
        for (auto& tablet_info : tablets_info) {
3768
4.00k
            std::string k;
3769
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3770
4.00k
            txn->remove(k);
3771
4.00k
        }
3772
4.00k
        for (auto& tablet_info : tablets_info) {
3773
4.00k
            std::string k;
3774
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3775
4.00k
            txn->remove(k);
3776
4.00k
        }
3777
2
        for (auto& k : init_rs_keys) {
3778
0
            txn->remove(k);
3779
0
        }
3780
2
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3781
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3782
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3783
0
                         << ", err=" << err;
3784
0
            return -1;
3785
0
        }
3786
2
        return ret;
3787
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3667
50
    auto loop_done = [&, this]() -> int {
3668
50
        int ret = 0;
3669
50
        bool finished = true;
3670
50
        bool has_empty_key = false;
3671
50
        DORIS_CLOUD_DEFER {
3672
50
            init_rs_keys.clear();
3673
50
            has_failure = false;
3674
50
        };
3675
50
        auto tablets_info = sync_executor.when_all(&finished);
3676
50
        if (!finished) {
3677
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3678
1
            return -1;
3679
1
        }
3680
3681
49
        size_t size_before_erase = tablets_info.size();
3682
49
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3683
49
        if (tablets_info.empty()) {
3684
0
            return size_before_erase == 0 ? 0 : -1;
3685
49
        } else if (size_before_erase != tablets_info.size()) {
3686
1
            has_empty_key = true;
3687
1
        }
3688
3689
49
        ret = has_empty_key ? -1 : 0;
3690
        // sort the vector using key's order
3691
49
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3692
49
            return prev.tablet_meta_key < last.tablet_meta_key;
3693
49
        });
3694
49
        std::unique_ptr<Transaction> txn;
3695
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3696
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3697
0
            return -1;
3698
0
        }
3699
49
        std::string tablet_key_end;
3700
49
        if (!tablets_info.empty()) {
3701
49
            if (!has_empty_key && !has_failure) {
3702
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3703
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3704
47
            } else {
3705
8
                for (auto& tablet_info : tablets_info) {
3706
8
                    txn->remove(tablet_info.tablet_meta_key);
3707
8
                }
3708
2
            }
3709
49
        }
3710
49
        if (should_recycle_versioned_keys()) {
3711
            // Remove tablet indexes in the same transaction as tablet metadata.
3712
7
            std::vector<std::string> versioned_idx_keys;
3713
7
            versioned_idx_keys.reserve(tablets_info.size());
3714
8
            for (const auto& tablet_info : tablets_info) {
3715
8
                versioned_idx_keys.push_back(
3716
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3717
8
            }
3718
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3719
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3720
7
            if (err != TxnErrorCode::TXN_OK) {
3721
0
                LOG_WARNING("failed to batch get tablet index kv")
3722
0
                        .tag("instance_id", instance_id_)
3723
0
                        .tag("num_tablets", tablets_info.size())
3724
0
                        .tag("err", err);
3725
0
                return -1;
3726
0
            }
3727
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3728
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3729
8
                if (!tablet_index_vals[i].has_value()) {
3730
0
                    continue;
3731
0
                }
3732
8
                const auto& tablet_info = tablets_info[i];
3733
8
                TabletIndexPB tablet_index_pb;
3734
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3735
0
                    LOG_WARNING("failed to parse tablet index pb")
3736
0
                            .tag("instance_id", instance_id_)
3737
0
                            .tag("tablet_id", tablet_info.tablet_id);
3738
0
                    return -1;
3739
0
                }
3740
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3741
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3742
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3743
8
                         tablet_info.tablet_id});
3744
8
                txn->remove(versioned_inverted_idx_key);
3745
8
                txn->remove(versioned_idx_keys[i]);
3746
8
            }
3747
8
            for (auto& tablet_info : tablets_info) {
3748
                // Remove all versions of tablet compact stats for recycled tablet
3749
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3750
8
                LOG_INFO("remove versioned tablet compact stats key")
3751
8
                        .tag("compact_stats_key", hex(k));
3752
8
                versioned_remove_all(txn.get(), k);
3753
8
            }
3754
8
            for (auto& tablet_info : tablets_info) {
3755
                // Remove all versions of tablet load stats for recycled tablet
3756
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3757
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3758
8
                versioned_remove_all(txn.get(), k);
3759
8
            }
3760
8
            for (auto& tablet_info : tablets_info) {
3761
                // Remove all versions of meta tablet for recycled tablet
3762
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3763
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3764
8
                versioned_remove_all(txn.get(), k);
3765
8
            }
3766
7
        }
3767
250
        for (auto& tablet_info : tablets_info) {
3768
250
            std::string k;
3769
250
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3770
250
            txn->remove(k);
3771
250
        }
3772
250
        for (auto& tablet_info : tablets_info) {
3773
250
            std::string k;
3774
250
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3775
250
            txn->remove(k);
3776
250
        }
3777
49
        for (auto& k : init_rs_keys) {
3778
0
            txn->remove(k);
3779
0
        }
3780
49
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3781
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3782
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3783
1
                         << ", err=" << err;
3784
1
            return -1;
3785
1
        }
3786
48
        return ret;
3787
49
    };
3788
3789
58
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3790
58
                               std::move(loop_done));
3791
58
    if (ret != 0) {
3792
6
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3793
6
        return ret;
3794
6
    }
3795
3796
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3797
52
    std::unique_ptr<Transaction> txn;
3798
52
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3799
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3800
0
        return -1;
3801
0
    }
3802
52
    txn->remove(stats_key_begin, stats_key_end);
3803
52
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3804
52
                 << " end=" << hex(stats_key_end);
3805
52
    txn->remove(job_key_begin, job_key_end);
3806
52
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3807
52
    std::string schema_key_begin, schema_key_end;
3808
52
    std::string schema_dict_key;
3809
52
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3810
52
    if (partition_id <= 0) {
3811
        // Delete schema kv of this index
3812
16
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3813
16
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3814
16
        txn->remove(schema_key_begin, schema_key_end);
3815
16
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3816
16
                     << " end=" << hex(schema_key_end);
3817
16
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3818
16
        txn->remove(schema_dict_key);
3819
16
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3820
16
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3821
16
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3822
16
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3823
16
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3824
16
                     << " end=" << hex(versioned_schema_key_end);
3825
16
    }
3826
3827
52
    TxnErrorCode err = txn->commit();
3828
52
    if (err != TxnErrorCode::TXN_OK) {
3829
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3830
0
                     << " err=" << err;
3831
0
        return -1;
3832
0
    }
3833
3834
52
    return ret;
3835
52
}
3836
3837
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3838
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3839
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3840
5.61k
    if (num_segments <= 0) return 0;
3841
3842
5.61k
    std::vector<std::string> file_paths;
3843
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3844
0
        return -1;
3845
0
    }
3846
3847
    // Process inverted indexes
3848
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3849
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3850
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3851
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3852
5.61k
    bool delete_rowset_data_by_prefix = false;
3853
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3854
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3855
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3856
0
        delete_rowset_data_by_prefix = true;
3857
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3858
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3859
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3860
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3861
10.0k
            }
3862
10.0k
        }
3863
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3864
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3865
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3866
2.00k
        }
3867
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3868
        // schema version and index id are not found, delete rowset data by prefix directly.
3869
0
        delete_rowset_data_by_prefix = true;
3870
809
    } else {
3871
        // otherwise, try to get schema kv
3872
809
        InvertedIndexInfo index_info;
3873
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3874
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3875
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3876
809
                                 &inverted_index_get_ret);
3877
809
        if (inverted_index_get_ret == 0) {
3878
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3879
809
                index_format = index_info.first;
3880
809
            }
3881
809
            index_ids = index_info.second;
3882
809
        } else if (inverted_index_get_ret == 1) {
3883
            // 1. Schema kv not found means tablet has been recycled
3884
            // Maybe some tablet recycle failed by some bugs
3885
            // We need to delete again to double check
3886
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3887
            // because we are uncertain about the inverted index information.
3888
            // If there are inverted indexes, some data might not be deleted,
3889
            // but this is acceptable as we have made our best effort to delete the data.
3890
0
            LOG_INFO(
3891
0
                    "delete rowset data schema kv not found, need to delete again to double "
3892
0
                    "check")
3893
0
                    .tag("instance_id", instance_id_)
3894
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3895
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3896
            // Currently index_ids is guaranteed to be empty,
3897
            // but we clear it again here as a safeguard against future code changes
3898
            // that might cause index_ids to no longer be empty
3899
0
            index_format = InvertedIndexStorageFormatPB::V2;
3900
0
            index_ids.clear();
3901
0
        } else {
3902
            // failed to get schema kv, delete rowset data by prefix directly.
3903
0
            delete_rowset_data_by_prefix = true;
3904
0
        }
3905
809
    }
3906
3907
5.61k
    if (delete_rowset_data_by_prefix) {
3908
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3909
0
                                  rs_meta_pb.rowset_id_v2());
3910
0
    }
3911
3912
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3913
5.61k
    if (it == accessor_map_.end()) {
3914
1.59k
        LOG_WARNING("instance has no such resource id")
3915
1.59k
                .tag("instance_id", instance_id_)
3916
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3917
1.59k
        return -1;
3918
1.59k
    }
3919
4.01k
    auto& accessor = it->second;
3920
3921
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3922
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3923
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3924
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3925
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3926
20.0k
                                         &file_paths);
3927
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3928
40.0k
            for (const auto& index_id : index_ids) {
3929
40.0k
                add_file_to_delete_if_not_packed(
3930
40.0k
                        rs_meta_pb,
3931
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3932
40.0k
                                               index_id.second),
3933
40.0k
                        &file_paths);
3934
40.0k
            }
3935
20.0k
        } else if (!index_ids.empty()) {
3936
2
            add_file_to_delete_if_not_packed(
3937
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3938
2
                    &file_paths);
3939
2
        }
3940
20.0k
    }
3941
3942
4.01k
    int should_delete_dbm = may_have_versioned_delete_bitmap(rs_meta_pb.partition_id(), tablet_id);
3943
4.01k
    if (should_delete_dbm == 1) {
3944
4.00k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3945
4.00k
        std::vector<std::string> rowset_dbm_keys;
3946
4.00k
        if (decrement_delete_bitmap_packed_file_ref_counts(
3947
4.00k
                    tablet_id, rowset_id, &delete_bitmap_storage_type, nullptr) != 0) {
3948
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3949
0
                    .tag("instance_id", instance_id_)
3950
0
                    .tag("tablet_id", tablet_id)
3951
0
                    .tag("rowset_id", rowset_id);
3952
0
            return -1;
3953
0
        }
3954
4.00k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3955
2.00k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3956
2.00k
        }
3957
4.00k
    } else if (should_delete_dbm != 0) {
3958
0
        return -1;
3959
0
    }
3960
    // TODO(AlexYue): seems could do do batch
3961
4.01k
    return accessor->delete_files(file_paths);
3962
4.01k
}
3963
3964
102k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3965
102k
    LOG_INFO("begin process_packed_file_location_index")
3966
102k
            .tag("instance_id", instance_id_)
3967
102k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3968
102k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3969
102k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3970
102k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3971
102k
    if (index_map.empty()) {
3972
87.5k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3973
87.5k
                .tag("instance_id", instance_id_)
3974
87.5k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3975
87.5k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3976
87.5k
        return 0;
3977
87.5k
    }
3978
3979
15.0k
    struct PackedSmallFileInfo {
3980
15.0k
        std::string small_file_path;
3981
15.0k
    };
3982
15.0k
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3983
15.0k
    packed_file_updates.reserve(index_map.size());
3984
29.9k
    for (const auto& [small_path, index_pb] : index_map) {
3985
30.0k
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3986
0
            continue;
3987
0
        }
3988
29.9k
        packed_file_updates[index_pb.packed_file_path()].push_back(
3989
29.9k
                PackedSmallFileInfo {small_path});
3990
29.9k
    }
3991
15.0k
    if (packed_file_updates.empty()) {
3992
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3993
0
                .tag("instance_id", instance_id_)
3994
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3995
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3996
0
                .tag("index_map_size", index_map.size());
3997
0
        return 0;
3998
0
    }
3999
4000
15.0k
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4001
15.0k
    int ret = 0;
4002
15.0k
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
4003
15.0k
        if (small_files.empty()) {
4004
0
            continue;
4005
0
        }
4006
4007
15.0k
        bool success = false;
4008
15.0k
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4009
14.9k
            std::unique_ptr<Transaction> txn;
4010
14.9k
            TxnErrorCode err = txn_kv_->create_txn(&txn);
4011
14.9k
            if (err != TxnErrorCode::TXN_OK) {
4012
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
4013
0
                        .tag("instance_id", instance_id_)
4014
0
                        .tag("packed_file_path", packed_file_path)
4015
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4016
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4017
0
                        .tag("err", err);
4018
0
                ret = -1;
4019
0
                break;
4020
0
            }
4021
4022
14.9k
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4023
14.9k
            std::string packed_val;
4024
14.9k
            err = txn->get(packed_key, &packed_val);
4025
14.9k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4026
0
                LOG_WARNING("packed file info not found when recycling rowset")
4027
0
                        .tag("instance_id", instance_id_)
4028
0
                        .tag("packed_file_path", packed_file_path)
4029
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4030
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4031
0
                        .tag("key", hex(packed_key))
4032
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
4033
                // Skip this packed file entry and continue with others
4034
0
                success = true;
4035
0
                break;
4036
0
            }
4037
14.9k
            if (err != TxnErrorCode::TXN_OK) {
4038
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
4039
0
                        .tag("instance_id", instance_id_)
4040
0
                        .tag("packed_file_path", packed_file_path)
4041
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4042
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4043
0
                        .tag("err", err);
4044
0
                ret = -1;
4045
0
                break;
4046
0
            }
4047
4048
14.9k
            cloud::PackedFileInfoPB packed_info;
4049
14.9k
            if (!packed_info.ParseFromString(packed_val)) {
4050
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
4051
0
                        .tag("instance_id", instance_id_)
4052
0
                        .tag("packed_file_path", packed_file_path)
4053
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4054
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4055
0
                ret = -1;
4056
0
                break;
4057
0
            }
4058
4059
14.9k
            LOG_INFO("packed file update check")
4060
14.9k
                    .tag("instance_id", instance_id_)
4061
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4062
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4063
14.9k
                    .tag("merged_file_path", packed_file_path)
4064
14.9k
                    .tag("requested_small_files", small_files.size())
4065
14.9k
                    .tag("merge_entries", packed_info.slices_size());
4066
4067
14.9k
            auto* small_file_entries = packed_info.mutable_slices();
4068
14.9k
            int64_t changed_files = 0;
4069
14.9k
            int64_t missing_entries = 0;
4070
14.9k
            int64_t already_deleted = 0;
4071
29.9k
            for (const auto& small_file_info : small_files) {
4072
29.9k
                bool found = false;
4073
74.8k
                for (auto& small_file_entry : *small_file_entries) {
4074
74.8k
                    if (small_file_entry.path() == small_file_info.small_file_path) {
4075
29.9k
                        if (!small_file_entry.deleted()) {
4076
29.9k
                            small_file_entry.set_deleted(true);
4077
29.9k
                            if (!small_file_entry.corrected()) {
4078
29.9k
                                small_file_entry.set_corrected(true);
4079
29.9k
                            }
4080
29.9k
                            ++changed_files;
4081
29.9k
                        } else {
4082
14
                            ++already_deleted;
4083
14
                        }
4084
29.9k
                        found = true;
4085
29.9k
                        break;
4086
29.9k
                    }
4087
74.8k
                }
4088
29.9k
                if (!found) {
4089
0
                    ++missing_entries;
4090
0
                    LOG_WARNING("packed file info missing small file entry")
4091
0
                            .tag("instance_id", instance_id_)
4092
0
                            .tag("packed_file_path", packed_file_path)
4093
0
                            .tag("small_file_path", small_file_info.small_file_path)
4094
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4095
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4096
0
                }
4097
29.9k
            }
4098
4099
14.9k
            if (changed_files == 0) {
4100
0
                LOG_INFO("skip merge file update: no merge entries changed")
4101
0
                        .tag("instance_id", instance_id_)
4102
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4103
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4104
0
                        .tag("merged_file_path", packed_file_path)
4105
0
                        .tag("missing_entries", missing_entries)
4106
0
                        .tag("already_deleted", already_deleted)
4107
0
                        .tag("requested_small_files", small_files.size())
4108
0
                        .tag("merge_entries", packed_info.slices_size());
4109
0
                success = true;
4110
0
                break;
4111
0
            }
4112
4113
            // Calculate remaining files
4114
14.9k
            int64_t left_file_count = 0;
4115
14.9k
            int64_t left_file_bytes = 0;
4116
59.9k
            for (const auto& small_file_entry : packed_info.slices()) {
4117
59.9k
                if (!small_file_entry.deleted()) {
4118
15.0k
                    ++left_file_count;
4119
15.0k
                    left_file_bytes += small_file_entry.size();
4120
15.0k
                }
4121
59.9k
            }
4122
14.9k
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4123
14.9k
            packed_info.set_ref_cnt(left_file_count);
4124
14.9k
            LOG_INFO("updated packed file reference info")
4125
14.9k
                    .tag("instance_id", instance_id_)
4126
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4127
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4128
14.9k
                    .tag("packed_file_path", packed_file_path)
4129
14.9k
                    .tag("ref_cnt", left_file_count)
4130
14.9k
                    .tag("left_file_bytes", left_file_bytes);
4131
4132
14.9k
            if (left_file_count == 0) {
4133
7.50k
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4134
7.50k
            }
4135
4136
14.9k
            std::string updated_val;
4137
14.9k
            if (!packed_info.SerializeToString(&updated_val)) {
4138
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4139
0
                        .tag("instance_id", instance_id_)
4140
0
                        .tag("packed_file_path", packed_file_path)
4141
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4142
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4143
0
                ret = -1;
4144
0
                break;
4145
0
            }
4146
4147
14.9k
            txn->put(packed_key, updated_val);
4148
14.9k
            err = txn->commit();
4149
15.0k
            if (err == TxnErrorCode::TXN_OK) {
4150
15.0k
                success = true;
4151
15.0k
                if (left_file_count == 0) {
4152
7.50k
                    LOG_INFO("packed file ready to delete, deleting immediately")
4153
7.50k
                            .tag("instance_id", instance_id_)
4154
7.50k
                            .tag("packed_file_path", packed_file_path);
4155
7.50k
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4156
0
                        ret = -1;
4157
0
                    }
4158
7.50k
                }
4159
15.0k
                break;
4160
15.0k
            }
4161
18.4E
            if (err == TxnErrorCode::TXN_CONFLICT) {
4162
0
                if (attempt >= max_retry_times) {
4163
0
                    LOG_WARNING("packed file info update conflict after max retry")
4164
0
                            .tag("instance_id", instance_id_)
4165
0
                            .tag("packed_file_path", packed_file_path)
4166
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4167
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4168
0
                            .tag("changed_files", changed_files)
4169
0
                            .tag("attempt", attempt);
4170
0
                    ret = -1;
4171
0
                    break;
4172
0
                }
4173
0
                LOG_WARNING("packed file info update conflict, retrying")
4174
0
                        .tag("instance_id", instance_id_)
4175
0
                        .tag("packed_file_path", packed_file_path)
4176
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4177
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4178
0
                        .tag("changed_files", changed_files)
4179
0
                        .tag("attempt", attempt);
4180
0
                sleep_for_packed_file_retry();
4181
0
                continue;
4182
0
            }
4183
4184
18.4E
            LOG_WARNING("failed to commit packed file info update")
4185
18.4E
                    .tag("instance_id", instance_id_)
4186
18.4E
                    .tag("packed_file_path", packed_file_path)
4187
18.4E
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4188
18.4E
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4189
18.4E
                    .tag("err", err)
4190
18.4E
                    .tag("changed_files", changed_files);
4191
18.4E
            ret = -1;
4192
18.4E
            break;
4193
18.4E
        }
4194
4195
15.0k
        if (!success) {
4196
0
            ret = -1;
4197
0
        }
4198
15.0k
    }
4199
4200
15.0k
    return ret;
4201
15.0k
}
4202
4203
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4204
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
4205
79.9k
        std::vector<std::string>* keys) {
4206
79.9k
    TEST_SYNC_POINT("InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts");
4207
79.9k
    if (out_storage_type) {
4208
79.9k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4209
79.9k
    }
4210
4211
    // Get delete bitmap storage info from FDB
4212
79.9k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4213
79.9k
    std::unique_ptr<Transaction> txn;
4214
79.9k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4215
79.9k
    if (err != TxnErrorCode::TXN_OK) {
4216
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4217
0
                .tag("instance_id", instance_id_)
4218
0
                .tag("tablet_id", tablet_id)
4219
0
                .tag("rowset_id", rowset_id)
4220
0
                .tag("err", err);
4221
0
        return -1;
4222
0
    }
4223
4224
79.9k
    ValueBuf dbm_val;
4225
79.9k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4226
79.9k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4227
        // No delete bitmap for this rowset, nothing to do
4228
15.1k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4229
15.1k
                .tag("instance_id", instance_id_)
4230
15.1k
                .tag("tablet_id", tablet_id)
4231
15.1k
                .tag("rowset_id", rowset_id);
4232
15.1k
        return 0;
4233
15.1k
    }
4234
64.8k
    if (err != TxnErrorCode::TXN_OK) {
4235
0
        LOG_WARNING("failed to get delete bitmap storage")
4236
0
                .tag("instance_id", instance_id_)
4237
0
                .tag("tablet_id", tablet_id)
4238
0
                .tag("rowset_id", rowset_id)
4239
0
                .tag("err", err);
4240
0
        return -1;
4241
0
    }
4242
4243
64.8k
    if (keys) {
4244
11.5k
        for (auto& key : dbm_val.keys()) {
4245
11.5k
            keys->push_back(std::move(key));
4246
11.5k
        }
4247
11.5k
    }
4248
4249
64.8k
    DeleteBitmapStoragePB storage;
4250
64.8k
    if (!dbm_val.to_pb(&storage)) {
4251
0
        LOG_WARNING("failed to parse delete bitmap storage")
4252
0
                .tag("instance_id", instance_id_)
4253
0
                .tag("tablet_id", tablet_id)
4254
0
                .tag("rowset_id", rowset_id);
4255
0
        return -1;
4256
0
    }
4257
4258
64.8k
    if (storage.store_in_fdb()) {
4259
1
        if (out_storage_type) {
4260
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4261
1
        }
4262
1
        return 0;
4263
1
    }
4264
4265
    // Check if delete bitmap is stored in standalone file.
4266
64.8k
    if (!storage.has_packed_slice_location() ||
4267
64.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4268
64.8k
        if (out_storage_type) {
4269
64.8k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4270
64.8k
        }
4271
64.8k
        return 0;
4272
64.8k
    }
4273
4274
10
    if (out_storage_type) {
4275
1
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4276
1
    }
4277
4278
10
    const auto& packed_loc = storage.packed_slice_location();
4279
10
    const std::string& packed_file_path = packed_loc.packed_file_path();
4280
4281
10
    LOG_INFO("decrementing delete bitmap packed file ref count")
4282
10
            .tag("instance_id", instance_id_)
4283
10
            .tag("tablet_id", tablet_id)
4284
10
            .tag("rowset_id", rowset_id)
4285
10
            .tag("packed_file_path", packed_file_path);
4286
4287
10
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4288
10
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4289
1
        std::unique_ptr<Transaction> update_txn;
4290
1
        err = txn_kv_->create_txn(&update_txn);
4291
1
        if (err != TxnErrorCode::TXN_OK) {
4292
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4293
0
                    .tag("instance_id", instance_id_)
4294
0
                    .tag("tablet_id", tablet_id)
4295
0
                    .tag("rowset_id", rowset_id)
4296
0
                    .tag("err", err);
4297
0
            return -1;
4298
0
        }
4299
4300
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4301
1
        std::string packed_val;
4302
1
        err = update_txn->get(packed_key, &packed_val);
4303
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4304
0
            LOG_WARNING("packed file info not found for delete bitmap")
4305
0
                    .tag("instance_id", instance_id_)
4306
0
                    .tag("tablet_id", tablet_id)
4307
0
                    .tag("rowset_id", rowset_id)
4308
0
                    .tag("packed_file_path", packed_file_path);
4309
0
            return 0;
4310
0
        }
4311
1
        if (err != TxnErrorCode::TXN_OK) {
4312
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4313
0
                    .tag("instance_id", instance_id_)
4314
0
                    .tag("tablet_id", tablet_id)
4315
0
                    .tag("rowset_id", rowset_id)
4316
0
                    .tag("packed_file_path", packed_file_path)
4317
0
                    .tag("err", err);
4318
0
            return -1;
4319
0
        }
4320
4321
1
        cloud::PackedFileInfoPB packed_info;
4322
1
        if (!packed_info.ParseFromString(packed_val)) {
4323
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4324
0
                    .tag("instance_id", instance_id_)
4325
0
                    .tag("tablet_id", tablet_id)
4326
0
                    .tag("rowset_id", rowset_id)
4327
0
                    .tag("packed_file_path", packed_file_path);
4328
0
            return -1;
4329
0
        }
4330
4331
        // Find and mark the small file entry as deleted
4332
        // Use tablet_id and rowset_id to match entry instead of path,
4333
        // because path format may vary with path_version (with or without shard prefix)
4334
1
        auto* entries = packed_info.mutable_slices();
4335
1
        bool found = false;
4336
1
        bool already_deleted = false;
4337
1
        for (auto& entry : *entries) {
4338
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4339
1
                if (!entry.deleted()) {
4340
1
                    entry.set_deleted(true);
4341
1
                    if (!entry.corrected()) {
4342
1
                        entry.set_corrected(true);
4343
1
                    }
4344
1
                } else {
4345
0
                    already_deleted = true;
4346
0
                }
4347
1
                found = true;
4348
1
                break;
4349
1
            }
4350
1
        }
4351
4352
1
        if (!found) {
4353
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4354
0
                    .tag("instance_id", instance_id_)
4355
0
                    .tag("tablet_id", tablet_id)
4356
0
                    .tag("rowset_id", rowset_id)
4357
0
                    .tag("packed_file_path", packed_file_path);
4358
0
            return 0;
4359
0
        }
4360
4361
1
        if (already_deleted) {
4362
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4363
0
                    .tag("instance_id", instance_id_)
4364
0
                    .tag("tablet_id", tablet_id)
4365
0
                    .tag("rowset_id", rowset_id)
4366
0
                    .tag("packed_file_path", packed_file_path);
4367
0
            return 0;
4368
0
        }
4369
4370
        // Calculate remaining files
4371
1
        int64_t left_file_count = 0;
4372
1
        int64_t left_file_bytes = 0;
4373
1
        for (const auto& entry : packed_info.slices()) {
4374
1
            if (!entry.deleted()) {
4375
0
                ++left_file_count;
4376
0
                left_file_bytes += entry.size();
4377
0
            }
4378
1
        }
4379
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4380
1
        packed_info.set_ref_cnt(left_file_count);
4381
4382
1
        if (left_file_count == 0) {
4383
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4384
1
        }
4385
4386
1
        std::string updated_val;
4387
1
        if (!packed_info.SerializeToString(&updated_val)) {
4388
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4389
0
                    .tag("instance_id", instance_id_)
4390
0
                    .tag("tablet_id", tablet_id)
4391
0
                    .tag("rowset_id", rowset_id)
4392
0
                    .tag("packed_file_path", packed_file_path);
4393
0
            return -1;
4394
0
        }
4395
4396
1
        update_txn->put(packed_key, updated_val);
4397
1
        err = update_txn->commit();
4398
1
        if (err == TxnErrorCode::TXN_OK) {
4399
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4400
1
                    .tag("instance_id", instance_id_)
4401
1
                    .tag("tablet_id", tablet_id)
4402
1
                    .tag("rowset_id", rowset_id)
4403
1
                    .tag("packed_file_path", packed_file_path)
4404
1
                    .tag("left_file_count", left_file_count);
4405
1
            if (left_file_count == 0) {
4406
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4407
0
                    return -1;
4408
0
                }
4409
1
            }
4410
1
            return 0;
4411
1
        }
4412
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4413
0
            if (attempt >= max_retry_times) {
4414
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4415
0
                        .tag("instance_id", instance_id_)
4416
0
                        .tag("tablet_id", tablet_id)
4417
0
                        .tag("rowset_id", rowset_id)
4418
0
                        .tag("packed_file_path", packed_file_path)
4419
0
                        .tag("attempt", attempt);
4420
0
                return -1;
4421
0
            }
4422
0
            sleep_for_packed_file_retry();
4423
0
            continue;
4424
0
        }
4425
4426
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4427
0
                .tag("instance_id", instance_id_)
4428
0
                .tag("tablet_id", tablet_id)
4429
0
                .tag("rowset_id", rowset_id)
4430
0
                .tag("packed_file_path", packed_file_path)
4431
0
                .tag("err", err);
4432
0
        return -1;
4433
0
    }
4434
4435
9
    return -1;
4436
10
}
4437
4438
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4439
                                                const std::string& packed_key,
4440
7.50k
                                                const cloud::PackedFileInfoPB& packed_info) {
4441
7.50k
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4442
0
        LOG_WARNING("packed file missing resource id when recycling")
4443
0
                .tag("instance_id", instance_id_)
4444
0
                .tag("packed_file_path", packed_file_path);
4445
0
        return -1;
4446
0
    }
4447
4448
7.50k
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4449
7.50k
    if (!accessor) {
4450
0
        LOG_WARNING("no accessor available to delete packed file")
4451
0
                .tag("instance_id", instance_id_)
4452
0
                .tag("packed_file_path", packed_file_path)
4453
0
                .tag("resource_id", packed_info.resource_id());
4454
0
        return -1;
4455
0
    }
4456
4457
7.50k
    int del_ret = accessor->delete_file(packed_file_path);
4458
7.50k
    if (del_ret != 0 && del_ret != 1) {
4459
0
        LOG_WARNING("failed to delete packed file")
4460
0
                .tag("instance_id", instance_id_)
4461
0
                .tag("packed_file_path", packed_file_path)
4462
0
                .tag("resource_id", resource_id)
4463
0
                .tag("ret", del_ret);
4464
0
        return -1;
4465
0
    }
4466
7.50k
    if (del_ret == 1) {
4467
0
        LOG_INFO("packed file already removed")
4468
0
                .tag("instance_id", instance_id_)
4469
0
                .tag("packed_file_path", packed_file_path)
4470
0
                .tag("resource_id", resource_id);
4471
7.50k
    } else {
4472
7.50k
        LOG_INFO("deleted packed file")
4473
7.50k
                .tag("instance_id", instance_id_)
4474
7.50k
                .tag("packed_file_path", packed_file_path)
4475
7.50k
                .tag("resource_id", resource_id);
4476
7.50k
    }
4477
4478
7.50k
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4479
7.50k
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4480
7.50k
        std::unique_ptr<Transaction> del_txn;
4481
7.50k
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4482
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4483
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4484
0
                    .tag("instance_id", instance_id_)
4485
0
                    .tag("packed_file_path", packed_file_path)
4486
0
                    .tag("attempt", attempt)
4487
0
                    .tag("err", err);
4488
0
            return -1;
4489
0
        }
4490
4491
7.50k
        std::string latest_val;
4492
7.50k
        err = del_txn->get(packed_key, &latest_val);
4493
7.50k
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4494
0
            return 0;
4495
0
        }
4496
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4497
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4498
0
                    .tag("instance_id", instance_id_)
4499
0
                    .tag("packed_file_path", packed_file_path)
4500
0
                    .tag("attempt", attempt)
4501
0
                    .tag("err", err);
4502
0
            return -1;
4503
0
        }
4504
4505
7.50k
        cloud::PackedFileInfoPB latest_info;
4506
7.50k
        if (!latest_info.ParseFromString(latest_val)) {
4507
0
            LOG_WARNING("failed to parse packed file info before removal")
4508
0
                    .tag("instance_id", instance_id_)
4509
0
                    .tag("packed_file_path", packed_file_path)
4510
0
                    .tag("attempt", attempt);
4511
0
            return -1;
4512
0
        }
4513
4514
7.50k
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4515
7.50k
              latest_info.ref_cnt() == 0)) {
4516
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4517
0
                    .tag("instance_id", instance_id_)
4518
0
                    .tag("packed_file_path", packed_file_path)
4519
0
                    .tag("attempt", attempt);
4520
0
            return 0;
4521
0
        }
4522
4523
7.50k
        del_txn->remove(packed_key);
4524
7.50k
        err = del_txn->commit();
4525
7.50k
        if (err == TxnErrorCode::TXN_OK) {
4526
7.50k
            LOG_INFO("removed packed file metadata")
4527
7.50k
                    .tag("instance_id", instance_id_)
4528
7.50k
                    .tag("packed_file_path", packed_file_path);
4529
7.50k
            return 0;
4530
7.50k
        }
4531
18.4E
        if (err == TxnErrorCode::TXN_CONFLICT) {
4532
0
            if (attempt >= max_retry_times) {
4533
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4534
0
                        .tag("instance_id", instance_id_)
4535
0
                        .tag("packed_file_path", packed_file_path)
4536
0
                        .tag("attempt", attempt);
4537
0
                return -1;
4538
0
            }
4539
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4540
0
                    .tag("instance_id", instance_id_)
4541
0
                    .tag("packed_file_path", packed_file_path)
4542
0
                    .tag("attempt", attempt);
4543
0
            sleep_for_packed_file_retry();
4544
0
            continue;
4545
0
        }
4546
18.4E
        LOG_WARNING("failed to remove packed file kv")
4547
18.4E
                .tag("instance_id", instance_id_)
4548
18.4E
                .tag("packed_file_path", packed_file_path)
4549
18.4E
                .tag("attempt", attempt)
4550
18.4E
                .tag("err", err);
4551
18.4E
        return -1;
4552
18.4E
    }
4553
18.4E
    return -1;
4554
7.50k
}
4555
4556
int InstanceRecycler::delete_rowset_data(
4557
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4558
        RecyclerMetricsContext& metrics_context,
4559
446
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4560
446
    int ret = 0;
4561
    // resource_id -> file_paths
4562
446
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4563
    // (resource_id, tablet_id, rowset_id)
4564
446
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4565
446
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4566
4567
106k
    for (const auto& [_, rs] : rowsets) {
4568
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4569
        // due to aborted schema change.
4570
106k
        if (is_formal_rowset) {
4571
53.1k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4572
                // Tablet has been recycled and this rowset has no packed slices, so file data
4573
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4574
                // slice info must still run to decrement packed file ref counts.
4575
0
                continue;
4576
0
            }
4577
53.1k
        }
4578
4579
106k
        int64_t num_segments = rs.num_segments();
4580
        // Check num_segments before accessor lookup, because empty rowsets
4581
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4582
        // set. Skipping them early avoids a spurious "no such resource id" error
4583
        // that marks the entire batch as failed and prevents txn_remove from
4584
        // cleaning up recycle KV keys.
4585
106k
        if (num_segments <= 0) {
4586
10.0k
            metrics_context.total_recycled_num++;
4587
10.0k
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4588
10.0k
            continue;
4589
10.0k
        }
4590
4591
96.4k
        auto it = accessor_map_.find(rs.resource_id());
4592
        // possible if the accessor is not initilized correctly
4593
96.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4594
2.00k
            LOG_WARNING("instance has no such resource id")
4595
2.00k
                    .tag("instance_id", instance_id_)
4596
2.00k
                    .tag("resource_id", rs.resource_id());
4597
2.00k
            ret = -1;
4598
2.00k
            continue;
4599
2.00k
        }
4600
4601
94.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4602
94.4k
        const auto& rowset_id = rs.rowset_id_v2();
4603
94.4k
        int64_t tablet_id = rs.tablet_id();
4604
94.4k
        LOG_INFO("recycle rowset merge index size")
4605
94.4k
                .tag("instance_id", instance_id_)
4606
94.4k
                .tag("tablet_id", tablet_id)
4607
94.4k
                .tag("rowset_id", rowset_id)
4608
94.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4609
94.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4610
0
            ret = -1;
4611
0
            continue;
4612
0
        }
4613
4614
94.4k
        int should_delete_dbm = may_have_versioned_delete_bitmap(rs.partition_id(), tablet_id);
4615
94.4k
        if (should_delete_dbm == 1) {
4616
73.4k
            DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4617
73.4k
            std::vector<std::string> rowset_dbm_keys;
4618
73.4k
            if (decrement_delete_bitmap_packed_file_ref_counts(
4619
73.4k
                        tablet_id, rowset_id, &delete_bitmap_storage_type,
4620
73.4k
                        delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4621
0
                LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4622
0
                        .tag("instance_id", instance_id_)
4623
0
                        .tag("tablet_id", tablet_id)
4624
0
                        .tag("rowset_id", rowset_id)
4625
0
                        .tag("task_type", metrics_context.operation_type);
4626
0
                ret = -1;
4627
0
                continue;
4628
0
            }
4629
73.4k
            if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4630
11.5k
                delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4631
11.5k
            }
4632
73.4k
            if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4633
61.5k
                file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4634
61.5k
            }
4635
73.4k
        } else if (should_delete_dbm != 0) {
4636
0
            ret = -1;
4637
0
            continue;
4638
0
        }
4639
4640
        // Process inverted indexes
4641
94.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4642
        // default format as v1.
4643
94.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4644
94.4k
                                                            ? rs.inverted_index_storage_format()
4645
94.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4646
94.4k
        int inverted_index_get_ret = 0;
4647
94.4k
        if (rs.has_tablet_schema()) {
4648
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4649
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4650
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4651
53.5k
                }
4652
53.5k
            }
4653
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4654
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4655
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4656
26.5k
            }
4657
67.5k
        } else {
4658
67.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4659
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4660
0
                                "instance_id="
4661
0
                             << instance_id_ << " tablet_id=" << tablet_id
4662
0
                             << " rowset_id=" << rowset_id;
4663
0
                ret = -1;
4664
0
                continue;
4665
0
            }
4666
67.5k
            InvertedIndexInfo index_info;
4667
67.5k
            inverted_index_get_ret =
4668
67.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4669
67.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4670
67.5k
                                     &inverted_index_get_ret);
4671
67.5k
            if (inverted_index_get_ret == 0) {
4672
62.0k
                if (!rs.has_inverted_index_storage_format()) {
4673
62.0k
                    index_format = index_info.first;
4674
62.0k
                }
4675
62.0k
                index_ids = index_info.second;
4676
62.0k
            } else if (inverted_index_get_ret == 1) {
4677
                // 1. Schema kv not found means tablet has been recycled
4678
                // Maybe some tablet recycle failed by some bugs
4679
                // We need to delete again to double check
4680
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4681
                // because we are uncertain about the inverted index information.
4682
                // If there are inverted indexes, some data might not be deleted,
4683
                // but this is acceptable as we have made our best effort to delete the data.
4684
5.50k
                LOG_INFO(
4685
5.50k
                        "delete rowset data schema kv not found, need to delete again to "
4686
5.50k
                        "double "
4687
5.50k
                        "check")
4688
5.50k
                        .tag("instance_id", instance_id_)
4689
5.50k
                        .tag("tablet_id", tablet_id)
4690
5.50k
                        .tag("rowset", rs.ShortDebugString());
4691
                // Currently index_ids is guaranteed to be empty,
4692
                // but we clear it again here as a safeguard against future code changes
4693
                // that might cause index_ids to no longer be empty
4694
5.50k
                index_format = InvertedIndexStorageFormatPB::V2;
4695
5.50k
                index_ids.clear();
4696
18.4E
            } else {
4697
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4698
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4699
18.4E
                ret = -1;
4700
18.4E
                continue;
4701
18.4E
            }
4702
67.5k
        }
4703
94.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE && !is_formal_rowset) {
4704
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4705
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4706
6
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4707
6
            continue;
4708
6
        }
4709
405k
        for (int64_t i = 0; i < num_segments; ++i) {
4710
310k
            auto segment_id = rowset_segment_id(rs, i);
4711
310k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4712
310k
                                             &file_paths);
4713
310k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4714
572k
                for (const auto& index_id : index_ids) {
4715
572k
                    add_file_to_delete_if_not_packed(
4716
572k
                            rs,
4717
572k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4718
572k
                                                   index_id.second),
4719
572k
                            &file_paths);
4720
572k
                }
4721
302k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4722
                // try to recycle inverted index v2 when get_ret == 1
4723
                // we treat schema not found as if it has a v2 format inverted index
4724
                // to reduce chance of data leakage
4725
7.49k
                if (inverted_index_get_ret == 1) {
4726
7.49k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4727
7.49k
                            .tag("instance_id", instance_id_)
4728
7.49k
                            .tag("inverted index v2 path",
4729
7.49k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4730
7.49k
                }
4731
7.49k
                add_file_to_delete_if_not_packed(
4732
7.49k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4733
7.49k
            }
4734
310k
        }
4735
94.4k
    }
4736
4737
446
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4738
446
                                                 "delete_rowset_data",
4739
446
                                                 [](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
4739
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
4739
205
                                                 [](const int& ret) { return ret != 0; });
4740
446
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4741
205
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4742
205
            DCHECK(accessor_map_.count(*rid))
4743
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4744
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4745
205
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4746
205
                                     &accessor_map_);
4747
205
            if (!accessor_map_.contains(*rid)) {
4748
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4749
0
                        .tag("resource_id", resource_id)
4750
0
                        .tag("instance_id", instance_id_);
4751
0
                return -1;
4752
0
            }
4753
205
            auto& accessor = accessor_map_[*rid];
4754
205
            int ret = accessor->delete_files(*paths);
4755
205
            if (!ret) {
4756
                // deduplication of different files with the same rowset id
4757
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4758
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4759
205
                std::set<std::string> deleted_rowset_id;
4760
4761
205
                std::for_each(paths->begin(), paths->end(),
4762
205
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4763
923k
                               this](const std::string& path) {
4764
923k
                                  std::vector<std::string> str;
4765
923k
                                  butil::SplitString(path, '/', &str);
4766
923k
                                  std::string rowset_id;
4767
923k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4768
919k
                                      rowset_id = str.back().substr(0, pos);
4769
919k
                                  } else {
4770
3.69k
                                      if (path.find("packed_file/") != std::string::npos) {
4771
0
                                          return; // packed files do not have rowset_id encoded
4772
0
                                      }
4773
3.69k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4774
3.69k
                                      return;
4775
3.69k
                                  }
4776
919k
                                  auto rs_meta = rowsets.find(rowset_id);
4777
919k
                                  if (rs_meta != rowsets.end() &&
4778
919k
                                      !deleted_rowset_id.contains(rowset_id)) {
4779
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4780
84.4k
                                      metrics_context.total_recycled_data_size +=
4781
84.4k
                                              rs_meta->second.total_disk_size();
4782
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4783
84.4k
                                              rs_meta->second.num_segments();
4784
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4785
84.4k
                                              rs_meta->second.total_disk_size();
4786
84.4k
                                      metrics_context.total_recycled_num++;
4787
84.4k
                                  }
4788
919k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4763
7
                               this](const std::string& path) {
4764
7
                                  std::vector<std::string> str;
4765
7
                                  butil::SplitString(path, '/', &str);
4766
7
                                  std::string rowset_id;
4767
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4768
7
                                      rowset_id = str.back().substr(0, pos);
4769
7
                                  } else {
4770
0
                                      if (path.find("packed_file/") != std::string::npos) {
4771
0
                                          return; // packed files do not have rowset_id encoded
4772
0
                                      }
4773
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4774
0
                                      return;
4775
0
                                  }
4776
7
                                  auto rs_meta = rowsets.find(rowset_id);
4777
7
                                  if (rs_meta != rowsets.end() &&
4778
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4779
7
                                      deleted_rowset_id.emplace(rowset_id);
4780
7
                                      metrics_context.total_recycled_data_size +=
4781
7
                                              rs_meta->second.total_disk_size();
4782
7
                                      segment_metrics_context_.total_recycled_num +=
4783
7
                                              rs_meta->second.num_segments();
4784
7
                                      segment_metrics_context_.total_recycled_data_size +=
4785
7
                                              rs_meta->second.total_disk_size();
4786
7
                                      metrics_context.total_recycled_num++;
4787
7
                                  }
4788
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
4763
923k
                               this](const std::string& path) {
4764
923k
                                  std::vector<std::string> str;
4765
923k
                                  butil::SplitString(path, '/', &str);
4766
923k
                                  std::string rowset_id;
4767
923k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4768
919k
                                      rowset_id = str.back().substr(0, pos);
4769
919k
                                  } else {
4770
3.69k
                                      if (path.find("packed_file/") != std::string::npos) {
4771
0
                                          return; // packed files do not have rowset_id encoded
4772
0
                                      }
4773
3.69k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4774
3.69k
                                      return;
4775
3.69k
                                  }
4776
919k
                                  auto rs_meta = rowsets.find(rowset_id);
4777
919k
                                  if (rs_meta != rowsets.end() &&
4778
919k
                                      !deleted_rowset_id.contains(rowset_id)) {
4779
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4780
84.4k
                                      metrics_context.total_recycled_data_size +=
4781
84.4k
                                              rs_meta->second.total_disk_size();
4782
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4783
84.4k
                                              rs_meta->second.num_segments();
4784
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4785
84.4k
                                              rs_meta->second.total_disk_size();
4786
84.4k
                                      metrics_context.total_recycled_num++;
4787
84.4k
                                  }
4788
919k
                              });
4789
205
            }
4790
205
            return ret;
4791
205
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4741
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4742
6
            DCHECK(accessor_map_.count(*rid))
4743
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4744
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4745
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4746
6
                                     &accessor_map_);
4747
6
            if (!accessor_map_.contains(*rid)) {
4748
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4749
0
                        .tag("resource_id", resource_id)
4750
0
                        .tag("instance_id", instance_id_);
4751
0
                return -1;
4752
0
            }
4753
6
            auto& accessor = accessor_map_[*rid];
4754
6
            int ret = accessor->delete_files(*paths);
4755
6
            if (!ret) {
4756
                // deduplication of different files with the same rowset id
4757
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4758
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4759
6
                std::set<std::string> deleted_rowset_id;
4760
4761
6
                std::for_each(paths->begin(), paths->end(),
4762
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4763
6
                               this](const std::string& path) {
4764
6
                                  std::vector<std::string> str;
4765
6
                                  butil::SplitString(path, '/', &str);
4766
6
                                  std::string rowset_id;
4767
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4768
6
                                      rowset_id = str.back().substr(0, pos);
4769
6
                                  } else {
4770
6
                                      if (path.find("packed_file/") != std::string::npos) {
4771
6
                                          return; // packed files do not have rowset_id encoded
4772
6
                                      }
4773
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4774
6
                                      return;
4775
6
                                  }
4776
6
                                  auto rs_meta = rowsets.find(rowset_id);
4777
6
                                  if (rs_meta != rowsets.end() &&
4778
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4779
6
                                      deleted_rowset_id.emplace(rowset_id);
4780
6
                                      metrics_context.total_recycled_data_size +=
4781
6
                                              rs_meta->second.total_disk_size();
4782
6
                                      segment_metrics_context_.total_recycled_num +=
4783
6
                                              rs_meta->second.num_segments();
4784
6
                                      segment_metrics_context_.total_recycled_data_size +=
4785
6
                                              rs_meta->second.total_disk_size();
4786
6
                                      metrics_context.total_recycled_num++;
4787
6
                                  }
4788
6
                              });
4789
6
            }
4790
6
            return ret;
4791
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4741
199
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4742
199
            DCHECK(accessor_map_.count(*rid))
4743
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4744
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4745
199
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4746
199
                                     &accessor_map_);
4747
199
            if (!accessor_map_.contains(*rid)) {
4748
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4749
0
                        .tag("resource_id", resource_id)
4750
0
                        .tag("instance_id", instance_id_);
4751
0
                return -1;
4752
0
            }
4753
199
            auto& accessor = accessor_map_[*rid];
4754
199
            int ret = accessor->delete_files(*paths);
4755
199
            if (!ret) {
4756
                // deduplication of different files with the same rowset id
4757
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4758
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4759
199
                std::set<std::string> deleted_rowset_id;
4760
4761
199
                std::for_each(paths->begin(), paths->end(),
4762
199
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4763
199
                               this](const std::string& path) {
4764
199
                                  std::vector<std::string> str;
4765
199
                                  butil::SplitString(path, '/', &str);
4766
199
                                  std::string rowset_id;
4767
199
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4768
199
                                      rowset_id = str.back().substr(0, pos);
4769
199
                                  } else {
4770
199
                                      if (path.find("packed_file/") != std::string::npos) {
4771
199
                                          return; // packed files do not have rowset_id encoded
4772
199
                                      }
4773
199
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4774
199
                                      return;
4775
199
                                  }
4776
199
                                  auto rs_meta = rowsets.find(rowset_id);
4777
199
                                  if (rs_meta != rowsets.end() &&
4778
199
                                      !deleted_rowset_id.contains(rowset_id)) {
4779
199
                                      deleted_rowset_id.emplace(rowset_id);
4780
199
                                      metrics_context.total_recycled_data_size +=
4781
199
                                              rs_meta->second.total_disk_size();
4782
199
                                      segment_metrics_context_.total_recycled_num +=
4783
199
                                              rs_meta->second.num_segments();
4784
199
                                      segment_metrics_context_.total_recycled_data_size +=
4785
199
                                              rs_meta->second.total_disk_size();
4786
199
                                      metrics_context.total_recycled_num++;
4787
199
                                  }
4788
199
                              });
4789
199
            }
4790
199
            return ret;
4791
199
        });
4792
205
    }
4793
446
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4794
6
        LOG_INFO(
4795
6
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4796
6
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4797
6
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4798
6
        concurrent_delete_executor.add([&]() -> int {
4799
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4800
6
            if (!ret) {
4801
6
                auto rs = rowsets.at(rowset_id);
4802
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4803
6
                metrics_context.total_recycled_num++;
4804
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4805
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4806
6
            }
4807
6
            return ret;
4808
6
        });
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
4798
6
        concurrent_delete_executor.add([&]() -> int {
4799
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4800
6
            if (!ret) {
4801
6
                auto rs = rowsets.at(rowset_id);
4802
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4803
6
                metrics_context.total_recycled_num++;
4804
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4805
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4806
6
            }
4807
6
            return ret;
4808
6
        });
4809
6
    }
4810
4811
446
    bool finished = true;
4812
446
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4813
446
    for (int r : rets) {
4814
211
        if (r != 0) {
4815
0
            ret = -1;
4816
0
            break;
4817
0
        }
4818
211
    }
4819
446
    ret = finished ? ret : -1;
4820
446
    return ret;
4821
446
}
4822
4823
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4824
43.5k
                                         const std::string& rowset_id) {
4825
43.5k
    auto it = accessor_map_.find(resource_id);
4826
43.5k
    if (it == accessor_map_.end()) {
4827
400
        LOG_WARNING("instance has no such resource id")
4828
400
                .tag("instance_id", instance_id_)
4829
400
                .tag("resource_id", resource_id)
4830
400
                .tag("tablet_id", tablet_id)
4831
400
                .tag("rowset_id", rowset_id);
4832
400
        return -1;
4833
400
    }
4834
43.1k
    auto& accessor = it->second;
4835
43.1k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4836
43.5k
}
4837
4838
206k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4839
206k
    std::lock_guard lock(recycled_tablets_mtx_);
4840
206k
    return recycled_tablets_.contains(tablet_id);
4841
206k
}
4842
4843
193k
int InstanceRecycler::may_have_versioned_delete_bitmap(int64_t partition_id, int64_t tablet_id) {
4844
193k
    bool is_mow = true;
4845
193k
    if (partition_id != -1) {
4846
183k
        std::lock_guard lock(partition_mow_cache_mutex);
4847
183k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4848
            // cache hit
4849
40.0k
            is_mow = it->second;
4850
40.0k
            return is_mow ? 1 : 0;
4851
40.0k
        }
4852
183k
    }
4853
4854
153k
    TabletIndexPB tablet_index;
4855
153k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4856
153k
    if (ret == 1) {
4857
        // maybe recycled
4858
150k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4859
150k
    }
4860
2.60k
    if (ret != 0) {
4861
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4862
0
                     << ", tablet_id=" << tablet_id;
4863
0
        return ret;
4864
0
    }
4865
4866
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4867
    // obtaining its partition ID from the tablet index.
4868
2.60k
    if (partition_id == -1) {
4869
0
        partition_id = tablet_index.partition_id();
4870
0
        std::lock_guard lock(partition_mow_cache_mutex);
4871
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4872
0
            is_mow = it->second;
4873
0
            return is_mow ? 1 : 0;
4874
0
        }
4875
0
    }
4876
4877
2.60k
    std::string tablet_meta_key =
4878
2.60k
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4879
2.60k
                             partition_id, tablet_id});
4880
2.60k
    std::string tablet_meta_value;
4881
2.60k
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4882
2.60k
    if (ret == 1) {
4883
        // maybe recycled
4884
2.56k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4885
2.56k
    }
4886
42
    if (ret != 0) {
4887
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4888
0
                     << ", tablet_id=" << tablet_id;
4889
0
        return ret;
4890
0
    }
4891
4892
42
    TabletMetaCloudPB tablet_meta;
4893
42
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4894
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4895
0
                     << ", tablet_id=" << tablet_id;
4896
0
        return -1;
4897
0
    }
4898
    // The changelog companion of a MoW data tablet stores versioned delete bitmaps copied from
4899
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4900
    // false value as the MoW state of the whole partition.
4901
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isChangelogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4902
42
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_CHANGELOG) {
4903
1
        return 1;
4904
1
    }
4905
41
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4906
41
    std::lock_guard lock(partition_mow_cache_mutex);
4907
41
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4908
41
    return it->second ? 1 : 0;
4909
42
}
4910
4911
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4912
92.4k
                                                         const std::string& rowset_id) {
4913
92.4k
    int ret = may_have_versioned_delete_bitmap(partition_id, tablet_id);
4914
92.4k
    if (ret <= 0) {
4915
1.00k
        return ret;
4916
1.00k
    }
4917
4918
91.4k
    std::string dbm_start_key =
4919
91.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4920
91.4k
    std::string dbm_end_key = dbm_start_key;
4921
91.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4922
91.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4923
91.4k
    if (ret != 0) {
4924
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4925
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4926
0
                     << " rowset_id=" << rowset_id;
4927
0
    }
4928
91.4k
    return ret;
4929
92.4k
}
4930
4931
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4932
51.2k
    std::string delete_bitmap_start =
4933
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4934
51.2k
    std::string delete_bitmap_end =
4935
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4936
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4937
51.2k
    if (ret != 0) {
4938
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4939
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4940
0
    }
4941
51.2k
    return ret;
4942
51.2k
}
4943
4944
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4945
4
    if (key.empty()) {
4946
0
        return false;
4947
0
    }
4948
4
    std::string_view key_view = key;
4949
4
    key_view.remove_prefix(1); // remove keyspace prefix
4950
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4951
4
    if (decode_key(&key_view, &decoded) != 0) {
4952
0
        return false;
4953
0
    }
4954
4
    if (decoded.size() < 4) {
4955
0
        return false;
4956
0
    }
4957
4
    try {
4958
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4959
4
    } catch (const std::bad_variant_access&) {
4960
0
        return false;
4961
0
    }
4962
4
    return true;
4963
4
}
4964
4965
14
int InstanceRecycler::recycle_packed_files() {
4966
14
    const std::string task_name = "recycle_packed_files";
4967
14
    auto start_tp = steady_clock::now();
4968
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4969
14
    int ret = 0;
4970
14
    PackedFileRecycleStats stats;
4971
4972
14
    register_recycle_task(task_name, start_time);
4973
14
    DORIS_CLOUD_DEFER {
4974
14
        unregister_recycle_task(task_name);
4975
14
        int64_t cost =
4976
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4977
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4978
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4979
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4980
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4981
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4982
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4983
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4984
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4985
14
                                                             stats.bytes_object_deleted);
4986
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4987
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4988
14
                .tag("instance_id", instance_id_)
4989
14
                .tag("num_scanned", stats.num_scanned)
4990
14
                .tag("num_corrected", stats.num_corrected)
4991
14
                .tag("num_deleted", stats.num_deleted)
4992
14
                .tag("num_failed", stats.num_failed)
4993
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4994
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4995
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4996
14
                .tag("bytes_deleted", stats.bytes_deleted)
4997
14
                .tag("ret", ret);
4998
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4973
14
    DORIS_CLOUD_DEFER {
4974
14
        unregister_recycle_task(task_name);
4975
14
        int64_t cost =
4976
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4977
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4978
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4979
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4980
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4981
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4982
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4983
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4984
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4985
14
                                                             stats.bytes_object_deleted);
4986
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4987
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4988
14
                .tag("instance_id", instance_id_)
4989
14
                .tag("num_scanned", stats.num_scanned)
4990
14
                .tag("num_corrected", stats.num_corrected)
4991
14
                .tag("num_deleted", stats.num_deleted)
4992
14
                .tag("num_failed", stats.num_failed)
4993
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4994
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4995
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4996
14
                .tag("bytes_deleted", stats.bytes_deleted)
4997
14
                .tag("ret", ret);
4998
14
    };
4999
5000
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
5001
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
5002
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
5003
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
5000
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
5001
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
5002
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
5003
4
    };
5004
5005
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
5006
5007
14
    std::string begin = packed_file_key({instance_id_, ""});
5008
14
    std::string end = packed_file_key({instance_id_, "\xff"});
5009
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
5010
0
        ret = -1;
5011
0
    }
5012
5013
14
    return ret;
5014
14
}
5015
5016
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
5017
                                                  RecyclerMetricsContext& metrics_context,
5018
0
                                                  int64_t partition_id, bool is_empty_tablet) {
5019
0
    std::string tablet_key_begin, tablet_key_end;
5020
5021
0
    if (partition_id > 0) {
5022
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
5023
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
5024
0
    } else {
5025
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
5026
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
5027
0
    }
5028
    // for calculate the total num or bytes of recyled objects
5029
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
5030
0
                                                          std::string_view v) -> int {
5031
0
        doris::TabletMetaCloudPB tablet_meta_pb;
5032
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
5033
0
            return 0;
5034
0
        }
5035
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
5036
5037
0
        if (config::enable_recycler_check_lazy_txn_finished &&
5038
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
5039
0
            return 0;
5040
0
        }
5041
5042
0
        if (!is_empty_tablet) {
5043
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
5044
0
                return 0;
5045
0
            }
5046
0
            tablet_metrics_context_.total_need_recycle_num++;
5047
0
        }
5048
0
        return 0;
5049
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_
5050
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
5051
0
    metrics_context.report(true);
5052
0
    tablet_metrics_context_.report(true);
5053
0
    segment_metrics_context_.report(true);
5054
0
    return ret;
5055
0
}
5056
5057
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
5058
0
                                                 RecyclerMetricsContext& metrics_context) {
5059
0
    int ret = 0;
5060
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
5061
0
    std::unique_ptr<Transaction> txn;
5062
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5063
0
        LOG_WARNING("failed to recycle tablet ")
5064
0
                .tag("tablet id", tablet_id)
5065
0
                .tag("instance_id", instance_id_)
5066
0
                .tag("reason", "failed to create txn");
5067
0
        ret = -1;
5068
0
    }
5069
0
    GetRowsetResponse resp;
5070
0
    std::string msg;
5071
0
    MetaServiceCode code = MetaServiceCode::OK;
5072
    // get rowsets in tablet
5073
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5074
0
                        tablet_id, code, msg, &resp);
5075
0
    if (code != MetaServiceCode::OK) {
5076
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5077
0
                .tag("tablet id", tablet_id)
5078
0
                .tag("msg", msg)
5079
0
                .tag("code", code)
5080
0
                .tag("instance id", instance_id_);
5081
0
        ret = -1;
5082
0
    }
5083
0
    for (const auto& rs_meta : resp.rowset_meta()) {
5084
        /*
5085
        * For compatibility, we skip the loop for [0-1] here.
5086
        * The purpose of this loop is to delete object files,
5087
        * and since [0-1] only has meta and doesn't have object files,
5088
        * skipping it doesn't affect system correctness.
5089
        *
5090
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
5091
        * would return error -1 directly, causing the recycle operation to fail.
5092
        *
5093
        * [0-1] doesn't have resource id is a bug.
5094
        * In the future, we will fix this problem, after that,
5095
        * we can remove this if statement.
5096
        *
5097
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
5098
        */
5099
5100
0
        if (rs_meta.end_version() == 1) {
5101
            // Assert that [0-1] has no resource_id to make sure
5102
            // this if statement will not be forgetted to remove
5103
            // when the resource id bug is fixed
5104
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5105
0
            continue;
5106
0
        }
5107
0
        if (!rs_meta.has_resource_id()) {
5108
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5109
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5110
0
                    .tag("instance_id", instance_id_)
5111
0
                    .tag("tablet_id", tablet_id);
5112
0
            continue;
5113
0
        }
5114
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5115
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5116
        // possible if the accessor is not initilized correctly
5117
0
        if (it == accessor_map_.end()) [[unlikely]] {
5118
0
            LOG_WARNING(
5119
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5120
0
                    "recycle process")
5121
0
                    .tag("tablet id", tablet_id)
5122
0
                    .tag("instance_id", instance_id_)
5123
0
                    .tag("resource_id", rs_meta.resource_id())
5124
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5125
0
            continue;
5126
0
        }
5127
5128
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
5129
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5130
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5131
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
5132
0
    }
5133
0
    return ret;
5134
0
}
5135
5136
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5137
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5138
4.26k
            .tag("instance_id", instance_id_)
5139
4.26k
            .tag("tablet_id", tablet_id);
5140
5141
4.26k
    if (should_recycle_versioned_keys()) {
5142
16
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5143
16
        if (ret != 0) {
5144
0
            return ret;
5145
0
        }
5146
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5147
        // during the recycle_versioned_tablet process.
5148
        //
5149
        // .. And remove restore job rowsets of this tablet too
5150
16
    }
5151
5152
4.26k
    int ret = 0;
5153
4.26k
    auto start_time = steady_clock::now();
5154
5155
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5156
5157
    // collect resource ids
5158
262
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5159
262
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5160
262
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5161
262
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5162
262
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5163
262
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5164
5165
262
    std::set<std::string> resource_ids;
5166
262
    int64_t recycle_rowsets_number = 0;
5167
262
    int64_t recycle_segments_number = 0;
5168
262
    int64_t recycle_rowsets_data_size = 0;
5169
262
    int64_t recycle_rowsets_index_size = 0;
5170
262
    int64_t recycle_restore_job_rowsets_number = 0;
5171
262
    int64_t recycle_restore_job_segments_number = 0;
5172
262
    int64_t recycle_restore_job_rowsets_data_size = 0;
5173
262
    int64_t recycle_restore_job_rowsets_index_size = 0;
5174
262
    int64_t max_rowset_version = 0;
5175
262
    int64_t min_rowset_creation_time = INT64_MAX;
5176
262
    int64_t max_rowset_creation_time = 0;
5177
262
    int64_t min_rowset_expiration_time = INT64_MAX;
5178
262
    int64_t max_rowset_expiration_time = 0;
5179
5180
262
    DORIS_CLOUD_DEFER {
5181
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5182
262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5183
262
                .tag("instance_id", instance_id_)
5184
262
                .tag("tablet_id", tablet_id)
5185
262
                .tag("recycle rowsets number", recycle_rowsets_number)
5186
262
                .tag("recycle segments number", recycle_segments_number)
5187
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5188
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5189
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5190
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5191
262
                .tag("all restore job rowsets recycle data size",
5192
262
                     recycle_restore_job_rowsets_data_size)
5193
262
                .tag("all restore job rowsets recycle index size",
5194
262
                     recycle_restore_job_rowsets_index_size)
5195
262
                .tag("max rowset version", max_rowset_version)
5196
262
                .tag("min rowset creation time", min_rowset_creation_time)
5197
262
                .tag("max rowset creation time", max_rowset_creation_time)
5198
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
5199
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
5200
262
                .tag("task type", metrics_context.operation_type)
5201
262
                .tag("ret", ret);
5202
262
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5180
262
    DORIS_CLOUD_DEFER {
5181
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5182
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5183
262
                .tag("instance_id", instance_id_)
5184
262
                .tag("tablet_id", tablet_id)
5185
262
                .tag("recycle rowsets number", recycle_rowsets_number)
5186
262
                .tag("recycle segments number", recycle_segments_number)
5187
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5188
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5189
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5190
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5191
262
                .tag("all restore job rowsets recycle data size",
5192
262
                     recycle_restore_job_rowsets_data_size)
5193
262
                .tag("all restore job rowsets recycle index size",
5194
262
                     recycle_restore_job_rowsets_index_size)
5195
262
                .tag("max rowset version", max_rowset_version)
5196
262
                .tag("min rowset creation time", min_rowset_creation_time)
5197
262
                .tag("max rowset creation time", max_rowset_creation_time)
5198
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
5199
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
5200
262
                .tag("task type", metrics_context.operation_type)
5201
262
                .tag("ret", ret);
5202
262
    };
5203
5204
262
    std::unique_ptr<Transaction> txn;
5205
262
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5206
0
        LOG_WARNING("failed to recycle tablet ")
5207
0
                .tag("tablet id", tablet_id)
5208
0
                .tag("instance_id", instance_id_)
5209
0
                .tag("reason", "failed to create txn");
5210
0
        ret = -1;
5211
0
    }
5212
262
    GetRowsetResponse resp;
5213
262
    std::string msg;
5214
262
    MetaServiceCode code = MetaServiceCode::OK;
5215
    // get rowsets in tablet
5216
262
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5217
262
                        tablet_id, code, msg, &resp);
5218
262
    if (code != MetaServiceCode::OK) {
5219
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5220
0
                .tag("tablet id", tablet_id)
5221
0
                .tag("msg", msg)
5222
0
                .tag("code", code)
5223
0
                .tag("instance id", instance_id_);
5224
0
        ret = -1;
5225
0
    }
5226
262
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5227
5228
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5229
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5230
3
            if (rs_meta.num_segments() <= 0) {
5231
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5232
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5233
2
                        .tag("instance_id", instance_id_)
5234
2
                        .tag("tablet_id", tablet_id);
5235
2
                recycle_rowsets_number += 1;
5236
2
                continue;
5237
2
            }
5238
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5239
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5240
1
                    .tag("instance_id", instance_id_)
5241
1
                    .tag("tablet_id", tablet_id);
5242
1
            return -1;
5243
3
        }
5244
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5245
0
                << "rs_meta" << rs_meta.ShortDebugString();
5246
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5247
        // possible if the accessor is not initilized correctly
5248
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5249
1
            LOG_WARNING(
5250
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5251
1
                    "recycle process")
5252
1
                    .tag("tablet id", tablet_id)
5253
1
                    .tag("instance_id", instance_id_)
5254
1
                    .tag("resource_id", rs_meta.resource_id())
5255
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5256
1
            return -1;
5257
1
        }
5258
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5259
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5260
0
                    .tag("instance_id", instance_id_)
5261
0
                    .tag("tablet_id", tablet_id)
5262
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5263
0
            return -1;
5264
0
        }
5265
2.54k
        int should_delete_dbm = may_have_versioned_delete_bitmap(rs_meta.partition_id(), tablet_id);
5266
2.54k
        if (should_delete_dbm == 1) {
5267
2.54k
            DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
5268
2.54k
            std::vector<std::string> rowset_dbm_keys;
5269
2.54k
            if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5270
2.54k
                                                               &delete_bitmap_storage_type,
5271
2.54k
                                                               nullptr) != 0) {
5272
0
                LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5273
0
                        .tag("instance_id", instance_id_)
5274
0
                        .tag("tablet_id", tablet_id)
5275
0
                        .tag("rowset_id", rs_meta.rowset_id_v2())
5276
0
                        .tag("task_type", metrics_context.operation_type);
5277
0
                return -1;
5278
0
            }
5279
18.4E
        } else if (should_delete_dbm != 0) {
5280
0
            return -1;
5281
0
        }
5282
2.54k
        recycle_rowsets_number += 1;
5283
2.54k
        recycle_segments_number += rs_meta.num_segments();
5284
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5285
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5286
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5287
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5288
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5289
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5290
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5291
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5292
2.54k
    }
5293
5294
    // get restore job rowset in tablet
5295
260
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5296
260
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5297
260
    if (code != MetaServiceCode::OK) {
5298
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5299
0
                .tag("tablet id", tablet_id)
5300
0
                .tag("msg", msg)
5301
0
                .tag("code", code)
5302
0
                .tag("instance id", instance_id_);
5303
0
        return -1;
5304
0
    }
5305
5306
260
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5307
0
        if (!rs_meta.has_resource_id()) {
5308
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5309
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5310
0
                    .tag("instance_id", instance_id_)
5311
0
                    .tag("tablet_id", tablet_id);
5312
0
            return -1;
5313
0
        }
5314
5315
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5316
        // possible if the accessor is not initilized correctly
5317
0
        if (it == accessor_map_.end()) [[unlikely]] {
5318
0
            LOG_WARNING(
5319
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5320
0
                    "recycle process")
5321
0
                    .tag("tablet id", tablet_id)
5322
0
                    .tag("instance_id", instance_id_)
5323
0
                    .tag("resource_id", rs_meta.resource_id())
5324
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5325
0
            return -1;
5326
0
        }
5327
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5328
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5329
0
                    .tag("instance_id", instance_id_)
5330
0
                    .tag("tablet_id", tablet_id)
5331
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5332
0
            return -1;
5333
0
        }
5334
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5335
0
                                                           nullptr) != 0) {
5336
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5337
0
                    .tag("instance_id", instance_id_)
5338
0
                    .tag("tablet_id", tablet_id)
5339
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5340
0
            return -1;
5341
0
        }
5342
0
        recycle_restore_job_rowsets_number += 1;
5343
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5344
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5345
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5346
0
        resource_ids.emplace(rs_meta.resource_id());
5347
0
    }
5348
5349
260
    LOG_INFO("recycle tablet start to delete object")
5350
260
            .tag("instance id", instance_id_)
5351
260
            .tag("tablet id", tablet_id)
5352
260
            .tag("recycle tablet resource ids are",
5353
260
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5354
260
                                 [](std::string rs_id, const auto& it) {
5355
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5356
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
5354
217
                                 [](std::string rs_id, const auto& it) {
5355
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5356
217
                                 }));
5357
5358
260
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5359
260
            _thread_pool_group.s3_producer_pool,
5360
260
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5361
260
            [](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
5361
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5362
5363
    // delete all rowset data in this tablet
5364
    // ATTN: there may be data leak if not all accessor initilized successfully
5365
    //       partial data deleted if the tablet is stored cross-storage vault
5366
    //       vault id is not attached to TabletMeta...
5367
260
    for (const auto& resource_id : resource_ids) {
5368
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5369
217
        concurrent_delete_executor.add(
5370
217
                [&, rs_id = resource_id,
5371
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5372
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5373
217
                    if (res != 0) {
5374
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5375
3
                                     << " path=" << accessor_ptr->uri()
5376
3
                                     << " task type=" << metrics_context.operation_type;
5377
3
                        return std::make_pair(-1, rs_id);
5378
3
                    }
5379
214
                    return std::make_pair(0, rs_id);
5380
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5371
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5372
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5373
217
                    if (res != 0) {
5374
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5375
3
                                     << " path=" << accessor_ptr->uri()
5376
3
                                     << " task type=" << metrics_context.operation_type;
5377
3
                        return std::make_pair(-1, rs_id);
5378
3
                    }
5379
214
                    return std::make_pair(0, rs_id);
5380
217
                });
5381
217
    }
5382
5383
260
    bool finished = true;
5384
260
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5385
260
    for (auto& r : rets) {
5386
217
        if (r.first != 0) {
5387
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5388
3
            ret = -1;
5389
3
        }
5390
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5391
217
    }
5392
260
    ret = finished ? ret : -1;
5393
5394
260
    if (ret != 0) { // failed recycle tablet data
5395
3
        LOG_WARNING("ret!=0")
5396
3
                .tag("finished", finished)
5397
3
                .tag("ret", ret)
5398
3
                .tag("instance_id", instance_id_)
5399
3
                .tag("tablet_id", tablet_id);
5400
3
        return ret;
5401
3
    }
5402
5403
257
    tablet_metrics_context_.total_recycled_data_size +=
5404
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5405
257
    tablet_metrics_context_.total_recycled_num += 1;
5406
257
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5407
257
    segment_metrics_context_.total_recycled_data_size +=
5408
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5409
257
    metrics_context.total_recycled_data_size +=
5410
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5411
257
    tablet_metrics_context_.report();
5412
257
    segment_metrics_context_.report();
5413
257
    metrics_context.report();
5414
5415
257
    txn.reset();
5416
257
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5417
0
        LOG_WARNING("failed to recycle tablet ")
5418
0
                .tag("tablet id", tablet_id)
5419
0
                .tag("instance_id", instance_id_)
5420
0
                .tag("reason", "failed to create txn");
5421
0
        ret = -1;
5422
0
    }
5423
    // delete all rowset kv in this tablet
5424
257
    txn->remove(rs_key0, rs_key1);
5425
257
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5426
257
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5427
5428
    // remove delete bitmap for MoW table
5429
257
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5430
257
    txn->remove(pending_key);
5431
257
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5432
257
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5433
257
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5434
5435
257
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5436
257
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5437
257
    txn->remove(dbm_start_key, dbm_end_key);
5438
257
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5439
257
              << " end=" << hex(dbm_end_key);
5440
5441
257
    TxnErrorCode err = txn->commit();
5442
257
    if (err != TxnErrorCode::TXN_OK) {
5443
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5444
0
        ret = -1;
5445
0
    }
5446
5447
257
    if (ret == 0) {
5448
        // All object files under tablet have been deleted
5449
257
        std::lock_guard lock(recycled_tablets_mtx_);
5450
257
        recycled_tablets_.insert(tablet_id);
5451
257
    }
5452
5453
257
    return ret;
5454
260
}
5455
5456
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5457
16
                                               RecyclerMetricsContext& metrics_context) {
5458
16
    int ret = 0;
5459
16
    auto start_time = steady_clock::now();
5460
5461
16
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5462
5463
    // collect resource ids
5464
13
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5465
13
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5466
13
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5467
13
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5468
5469
13
    int64_t recycle_rowsets_number = 0;
5470
13
    int64_t recycle_segments_number = 0;
5471
13
    int64_t recycle_rowsets_data_size = 0;
5472
13
    int64_t recycle_rowsets_index_size = 0;
5473
13
    int64_t max_rowset_version = 0;
5474
13
    int64_t min_rowset_creation_time = INT64_MAX;
5475
13
    int64_t max_rowset_creation_time = 0;
5476
13
    int64_t min_rowset_expiration_time = INT64_MAX;
5477
13
    int64_t max_rowset_expiration_time = 0;
5478
5479
13
    DORIS_CLOUD_DEFER {
5480
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5481
13
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5482
13
                .tag("instance_id", instance_id_)
5483
13
                .tag("tablet_id", tablet_id)
5484
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5485
13
                .tag("recycle segments number", recycle_segments_number)
5486
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5487
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5488
13
                .tag("max rowset version", max_rowset_version)
5489
13
                .tag("min rowset creation time", min_rowset_creation_time)
5490
13
                .tag("max rowset creation time", max_rowset_creation_time)
5491
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5492
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5493
13
                .tag("ret", ret);
5494
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5479
13
    DORIS_CLOUD_DEFER {
5480
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5481
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5482
13
                .tag("instance_id", instance_id_)
5483
13
                .tag("tablet_id", tablet_id)
5484
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5485
13
                .tag("recycle segments number", recycle_segments_number)
5486
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5487
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5488
13
                .tag("max rowset version", max_rowset_version)
5489
13
                .tag("min rowset creation time", min_rowset_creation_time)
5490
13
                .tag("max rowset creation time", max_rowset_creation_time)
5491
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5492
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5493
13
                .tag("ret", ret);
5494
13
    };
5495
5496
13
    std::unique_ptr<Transaction> txn;
5497
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5498
0
        LOG_WARNING("failed to recycle tablet ")
5499
0
                .tag("tablet id", tablet_id)
5500
0
                .tag("instance_id", instance_id_)
5501
0
                .tag("reason", "failed to create txn");
5502
0
        ret = -1;
5503
0
    }
5504
5505
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5506
    // by the related operation logs.
5507
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5508
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5509
13
    MetaReader meta_reader(instance_id_);
5510
13
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5511
13
    if (err == TxnErrorCode::TXN_OK) {
5512
13
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5513
13
    }
5514
13
    if (err != TxnErrorCode::TXN_OK) {
5515
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5516
0
                .tag("tablet id", tablet_id)
5517
0
                .tag("err", err)
5518
0
                .tag("instance id", instance_id_);
5519
0
        ret = -1;
5520
0
    }
5521
5522
13
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5523
13
             load_rowset_metas.size(), compact_rowset_metas.size())
5524
13
            .tag("instance_id", instance_id_)
5525
13
            .tag("tablet_id", tablet_id);
5526
5527
13
    SyncExecutor<int> concurrent_delete_executor(
5528
13
            _thread_pool_group.s3_producer_pool,
5529
13
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5530
13
            [](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
5531
5532
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5533
61
        recycle_rowsets_number += 1;
5534
61
        recycle_segments_number += rs_meta.num_segments();
5535
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5536
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5537
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5538
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5539
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5540
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5541
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5542
61
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5532
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5533
61
        recycle_rowsets_number += 1;
5534
61
        recycle_segments_number += rs_meta.num_segments();
5535
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5536
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5537
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5538
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5539
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5540
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5541
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5542
61
    };
5543
5544
13
    std::vector<RowsetDeleteTask> all_tasks;
5545
61
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5546
61
        update_rowset_stats(rs_meta);
5547
        // Version 0-1 rowset has no resource_id and no actual data files,
5548
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5549
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5550
61
        RowsetDeleteTask task;
5551
61
        task.rowset_meta = rs_meta;
5552
61
        task.versioned_rowset_key =
5553
61
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5554
61
        task.non_versioned_rowset_key =
5555
61
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5556
61
        task.versionstamp = versionstamp;
5557
61
        all_tasks.push_back(std::move(task));
5558
61
    }
5559
5560
13
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5561
0
        update_rowset_stats(rs_meta);
5562
        // Version 0-1 rowset has no resource_id and no actual data files,
5563
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5564
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5565
0
        RowsetDeleteTask task;
5566
0
        task.rowset_meta = rs_meta;
5567
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5568
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5569
0
        task.non_versioned_rowset_key =
5570
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5571
0
        task.versionstamp = versionstamp;
5572
0
        all_tasks.push_back(std::move(task));
5573
0
    }
5574
5575
13
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5576
0
        RecycleRowsetPB recycle_rowset;
5577
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5578
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5579
0
            return -1;
5580
0
        }
5581
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5582
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5583
                // in old version, keep this key-value pair and it needs to be checked manually
5584
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5585
0
                return -1;
5586
0
            }
5587
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5588
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5589
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5590
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5591
0
                return -1;
5592
0
            }
5593
            // decode rowset_id
5594
0
            auto k1 = k;
5595
0
            k1.remove_prefix(1);
5596
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5597
0
            decode_key(&k1, &out);
5598
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5599
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5600
0
            LOG_INFO("delete old-version rowset data")
5601
0
                    .tag("instance_id", instance_id_)
5602
0
                    .tag("tablet_id", tablet_id)
5603
0
                    .tag("rowset_id", rowset_id);
5604
5605
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5606
            // so we must use prefix deletion directly instead of batch delete.
5607
0
            concurrent_delete_executor.add(
5608
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5609
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5610
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5611
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
5612
0
        } else {
5613
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5614
            // Version 0-1 rowset has no resource_id and no actual data files,
5615
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5616
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5617
0
            RowsetDeleteTask task;
5618
0
            task.rowset_meta = rowset_meta;
5619
0
            task.recycle_rowset_key = k;
5620
0
            all_tasks.push_back(std::move(task));
5621
0
        }
5622
0
        return 0;
5623
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_
5624
5625
13
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5626
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5627
0
                .tag("tablet id", tablet_id)
5628
0
                .tag("instance_id", instance_id_)
5629
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5630
0
        ret = -1;
5631
0
    }
5632
5633
    // Phase 1: Classify tasks by ref_count
5634
13
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5635
61
    for (auto& task : all_tasks) {
5636
61
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5637
61
        if (classify_ret < 0) {
5638
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5639
0
                    .tag("instance_id", instance_id_)
5640
0
                    .tag("tablet_id", tablet_id)
5641
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5642
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5643
0
                return recycle_rowset_meta_and_data(t);
5644
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5645
0
        }
5646
61
    }
5647
5648
13
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5649
5650
13
    LOG_INFO("batch delete plan created")
5651
13
            .tag("instance_id", instance_id_)
5652
13
            .tag("tablet_id", tablet_id)
5653
13
            .tag("plan_count", batch_delete_tasks.size());
5654
5655
    // Phase 2: Execute batch delete using existing delete_rowset_data
5656
13
    if (!batch_delete_tasks.empty()) {
5657
11
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5658
50
        for (const auto& task : batch_delete_tasks) {
5659
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5660
50
            if (task.rowset_meta.resource_id().empty()) {
5661
11
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5662
11
                        .tag("instance_id", instance_id_)
5663
11
                        .tag("tablet_id", tablet_id)
5664
11
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5665
11
                continue;
5666
11
            }
5667
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5668
39
        }
5669
5670
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5671
11
        bool delete_success = true;
5672
11
        if (!rowsets_to_delete.empty()) {
5673
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5674
9
                                                         "batch_delete_versioned_tablet");
5675
9
            int delete_ret = delete_rowset_data(
5676
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5677
9
            if (delete_ret != 0) {
5678
0
                LOG_WARNING("batch delete execution failed")
5679
0
                        .tag("instance_id", instance_id_)
5680
0
                        .tag("tablet_id", tablet_id);
5681
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5682
0
                ret = -1;
5683
0
                delete_success = false;
5684
0
            }
5685
9
        }
5686
5687
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5688
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5689
11
        if (delete_success) {
5690
11
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5691
11
            if (cleanup_ret != 0) {
5692
0
                LOG_WARNING("batch delete cleanup failed")
5693
0
                        .tag("instance_id", instance_id_)
5694
0
                        .tag("tablet_id", tablet_id);
5695
0
                ret = -1;
5696
0
            }
5697
11
        }
5698
11
    }
5699
5700
    // Always wait for fallback tasks to complete before returning
5701
13
    bool finished = true;
5702
13
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5703
13
    for (int r : rets) {
5704
0
        if (r != 0) {
5705
0
            ret = -1;
5706
0
        }
5707
0
    }
5708
5709
13
    ret = finished ? ret : -1;
5710
5711
13
    if (ret != 0) { // failed recycle tablet data
5712
0
        LOG_WARNING("recycle versioned tablet failed")
5713
0
                .tag("finished", finished)
5714
0
                .tag("ret", ret)
5715
0
                .tag("instance_id", instance_id_)
5716
0
                .tag("tablet_id", tablet_id);
5717
0
        return ret;
5718
0
    }
5719
5720
13
    tablet_metrics_context_.total_recycled_data_size +=
5721
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5722
13
    tablet_metrics_context_.total_recycled_num += 1;
5723
13
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5724
13
    segment_metrics_context_.total_recycled_data_size +=
5725
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5726
13
    metrics_context.total_recycled_data_size +=
5727
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5728
13
    tablet_metrics_context_.report();
5729
13
    segment_metrics_context_.report();
5730
13
    metrics_context.report();
5731
5732
13
    txn.reset();
5733
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5734
0
        LOG_WARNING("failed to recycle tablet ")
5735
0
                .tag("tablet id", tablet_id)
5736
0
                .tag("instance_id", instance_id_)
5737
0
                .tag("reason", "failed to create txn");
5738
0
        ret = -1;
5739
0
    }
5740
    // delete all rowset kv in this tablet
5741
13
    txn->remove(rs_key0, rs_key1);
5742
13
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5743
5744
    // remove delete bitmap for MoW table
5745
13
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5746
13
    txn->remove(pending_key);
5747
13
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5748
13
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5749
13
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5750
5751
13
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5752
13
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5753
13
    txn->remove(dbm_start_key, dbm_end_key);
5754
13
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5755
13
              << " end=" << hex(dbm_end_key);
5756
5757
13
    err = txn->commit();
5758
13
    if (err != TxnErrorCode::TXN_OK) {
5759
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5760
0
        ret = -1;
5761
0
    }
5762
5763
13
    if (ret == 0) {
5764
        // All object files under tablet have been deleted
5765
13
        std::lock_guard lock(recycled_tablets_mtx_);
5766
13
        recycled_tablets_.insert(tablet_id);
5767
13
    }
5768
5769
13
    return ret;
5770
13
}
5771
5772
66
int InstanceRecycler::recycle_rowsets() {
5773
66
    if (should_recycle_versioned_keys()) {
5774
5
        return recycle_versioned_rowsets();
5775
5
    }
5776
5777
61
    const std::string task_name = "recycle_rowsets";
5778
61
    int64_t num_scanned = 0;
5779
61
    int64_t num_expired = 0;
5780
61
    int64_t num_prepare = 0;
5781
61
    int64_t num_compacted = 0;
5782
61
    int64_t num_empty_rowset = 0;
5783
61
    size_t total_rowset_key_size = 0;
5784
61
    size_t total_rowset_value_size = 0;
5785
61
    size_t expired_rowset_size = 0;
5786
61
    std::atomic_long num_recycled = 0;
5787
61
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5788
5789
61
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5790
61
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5791
61
    std::string recyc_rs_key0;
5792
61
    std::string recyc_rs_key1;
5793
61
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5794
61
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5795
5796
61
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5797
5798
61
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5799
61
    register_recycle_task(task_name, start_time);
5800
5801
61
    DORIS_CLOUD_DEFER {
5802
61
        unregister_recycle_task(task_name);
5803
61
        int64_t cost =
5804
61
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5805
61
        metrics_context.finish_report();
5806
61
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5807
61
                .tag("instance_id", instance_id_)
5808
61
                .tag("num_scanned", num_scanned)
5809
61
                .tag("num_expired", num_expired)
5810
61
                .tag("num_recycled", num_recycled)
5811
61
                .tag("num_recycled.prepare", num_prepare)
5812
61
                .tag("num_recycled.compacted", num_compacted)
5813
61
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5814
61
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5815
61
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5816
61
                .tag("expired_rowset_meta_size", expired_rowset_size);
5817
61
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5801
7
    DORIS_CLOUD_DEFER {
5802
7
        unregister_recycle_task(task_name);
5803
7
        int64_t cost =
5804
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5805
7
        metrics_context.finish_report();
5806
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5807
7
                .tag("instance_id", instance_id_)
5808
7
                .tag("num_scanned", num_scanned)
5809
7
                .tag("num_expired", num_expired)
5810
7
                .tag("num_recycled", num_recycled)
5811
7
                .tag("num_recycled.prepare", num_prepare)
5812
7
                .tag("num_recycled.compacted", num_compacted)
5813
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5814
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5815
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5816
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5817
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5801
54
    DORIS_CLOUD_DEFER {
5802
54
        unregister_recycle_task(task_name);
5803
54
        int64_t cost =
5804
54
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5805
54
        metrics_context.finish_report();
5806
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5807
54
                .tag("instance_id", instance_id_)
5808
54
                .tag("num_scanned", num_scanned)
5809
54
                .tag("num_expired", num_expired)
5810
54
                .tag("num_recycled", num_recycled)
5811
54
                .tag("num_recycled.prepare", num_prepare)
5812
54
                .tag("num_recycled.compacted", num_compacted)
5813
54
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5814
54
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5815
54
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5816
54
                .tag("expired_rowset_meta_size", expired_rowset_size);
5817
54
    };
5818
5819
61
    std::vector<std::string> rowset_keys;
5820
61
    std::vector<std::string> rowset_keys_to_mark_recycled;
5821
61
    std::vector<std::string> rowset_keys_to_abort_job;
5822
    // rowset_id -> rowset_meta
5823
    // store rowset id and meta for statistics rs size when delete
5824
61
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5825
5826
61
    std::mutex async_recycled_rowset_keys_mutex;
5827
61
    std::vector<std::string> async_recycled_rowset_keys;
5828
61
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5829
61
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5830
61
    worker_pool->start();
5831
61
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5832
61
                                            int64_t partition_id, int64_t tablet_id,
5833
30.9k
                                            const std::string& rowset_id) {
5834
        // Try to delete rowset data in background thread
5835
30.9k
        int ret = worker_pool->submit_with_timeout(
5836
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5837
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
                        return;
5840
0
                    }
5841
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5842
28.4k
                        0) {
5843
0
                        return;
5844
0
                    }
5845
28.4k
                    std::vector<std::string> keys;
5846
28.4k
                    {
5847
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5848
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5849
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5850
278
                            keys.swap(async_recycled_rowset_keys);
5851
278
                        }
5852
28.4k
                    }
5853
28.4k
                    if (keys.empty()) return;
5854
288
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5856
0
                                     << instance_id_;
5857
288
                    } else {
5858
288
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5859
288
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5860
288
                                           num_recycled, start_time);
5861
288
                    }
5862
288
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5836
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5837
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
                        return;
5840
0
                    }
5841
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5842
1
                        0) {
5843
0
                        return;
5844
0
                    }
5845
1
                    std::vector<std::string> keys;
5846
1
                    {
5847
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5848
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5849
1
                        if (async_recycled_rowset_keys.size() > 100) {
5850
0
                            keys.swap(async_recycled_rowset_keys);
5851
0
                        }
5852
1
                    }
5853
1
                    if (keys.empty()) return;
5854
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5856
0
                                     << instance_id_;
5857
0
                    } else {
5858
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5859
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5860
0
                                           num_recycled, start_time);
5861
0
                    }
5862
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5836
28.4k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5837
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
                        return;
5840
0
                    }
5841
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5842
28.4k
                        0) {
5843
0
                        return;
5844
0
                    }
5845
28.4k
                    std::vector<std::string> keys;
5846
28.4k
                    {
5847
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5848
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5849
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5850
278
                            keys.swap(async_recycled_rowset_keys);
5851
278
                        }
5852
28.4k
                    }
5853
28.4k
                    if (keys.empty()) return;
5854
288
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5855
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5856
0
                                     << instance_id_;
5857
288
                    } else {
5858
288
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5859
288
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5860
288
                                           num_recycled, start_time);
5861
288
                    }
5862
288
                },
5863
30.9k
                0);
5864
30.9k
        if (ret == 0) return 0;
5865
        // Submit task failed, delete rowset data in current thread
5866
2.41k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5867
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5868
0
            return -1;
5869
0
        }
5870
2.41k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5871
0
            return -1;
5872
0
        }
5873
2.41k
        rowset_keys.push_back(std::move(key));
5874
2.41k
        return 0;
5875
2.41k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5833
1
                                            const std::string& rowset_id) {
5834
        // Try to delete rowset data in background thread
5835
1
        int ret = worker_pool->submit_with_timeout(
5836
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5837
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
1
                        return;
5840
1
                    }
5841
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5842
1
                        0) {
5843
1
                        return;
5844
1
                    }
5845
1
                    std::vector<std::string> keys;
5846
1
                    {
5847
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5848
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5849
1
                        if (async_recycled_rowset_keys.size() > 100) {
5850
1
                            keys.swap(async_recycled_rowset_keys);
5851
1
                        }
5852
1
                    }
5853
1
                    if (keys.empty()) return;
5854
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5855
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5856
1
                                     << instance_id_;
5857
1
                    } else {
5858
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5859
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5860
1
                                           num_recycled, start_time);
5861
1
                    }
5862
1
                },
5863
1
                0);
5864
1
        if (ret == 0) return 0;
5865
        // Submit task failed, delete rowset data in current thread
5866
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5867
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5868
0
            return -1;
5869
0
        }
5870
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5871
0
            return -1;
5872
0
        }
5873
0
        rowset_keys.push_back(std::move(key));
5874
0
        return 0;
5875
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5833
30.9k
                                            const std::string& rowset_id) {
5834
        // Try to delete rowset data in background thread
5835
30.9k
        int ret = worker_pool->submit_with_timeout(
5836
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5837
30.9k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
30.9k
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
30.9k
                        return;
5840
30.9k
                    }
5841
30.9k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5842
30.9k
                        0) {
5843
30.9k
                        return;
5844
30.9k
                    }
5845
30.9k
                    std::vector<std::string> keys;
5846
30.9k
                    {
5847
30.9k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5848
30.9k
                        async_recycled_rowset_keys.push_back(std::move(key));
5849
30.9k
                        if (async_recycled_rowset_keys.size() > 100) {
5850
30.9k
                            keys.swap(async_recycled_rowset_keys);
5851
30.9k
                        }
5852
30.9k
                    }
5853
30.9k
                    if (keys.empty()) return;
5854
30.9k
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5855
30.9k
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5856
30.9k
                                     << instance_id_;
5857
30.9k
                    } else {
5858
30.9k
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5859
30.9k
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5860
30.9k
                                           num_recycled, start_time);
5861
30.9k
                    }
5862
30.9k
                },
5863
30.9k
                0);
5864
30.9k
        if (ret == 0) return 0;
5865
        // Submit task failed, delete rowset data in current thread
5866
2.41k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5867
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5868
0
            return -1;
5869
0
        }
5870
2.41k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5871
0
            return -1;
5872
0
        }
5873
2.41k
        rowset_keys.push_back(std::move(key));
5874
2.41k
        return 0;
5875
2.41k
    };
5876
5877
61
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5878
5879
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5880
124k
        ++num_scanned;
5881
124k
        total_rowset_key_size += k.size();
5882
124k
        total_rowset_value_size += v.size();
5883
124k
        RecycleRowsetPB rowset;
5884
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5885
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5886
0
            return -1;
5887
0
        }
5888
5889
124k
        int64_t current_time = ::time(nullptr);
5890
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5891
5892
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5893
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5894
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5895
124k
        if (current_time < expiration) { // not expired
5896
0
            return 0;
5897
0
        }
5898
124k
        ++num_expired;
5899
124k
        expired_rowset_size += v.size();
5900
5901
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5902
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5903
                // in old version, keep this key-value pair and it needs to be checked manually
5904
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5905
0
                return -1;
5906
0
            }
5907
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5908
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5909
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5910
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5911
10.0k
                rowset_keys.emplace_back(k);
5912
10.0k
                return 0;
5913
10.0k
            }
5914
            // decode rowset_id
5915
10.2k
            auto k1 = k;
5916
10.2k
            k1.remove_prefix(1);
5917
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5918
10.2k
            decode_key(&k1, &out);
5919
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5920
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5921
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5922
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5923
10.2k
                      << " task_type=" << metrics_context.operation_type;
5924
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5925
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5926
0
                return -1;
5927
0
            }
5928
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5929
10.2k
            metrics_context.total_recycled_num++;
5930
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5931
10.2k
                    rowset.rowset_meta().total_disk_size();
5932
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5933
10.2k
            return 0;
5934
10.2k
        }
5935
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5936
5937
        // TODO(plat1ko): check rowset not referenced
5938
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5939
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5940
0
                LOG_INFO("recycle rowset that has empty resource id");
5941
0
            } else {
5942
                // other situations, keep this key-value pair and it needs to be checked manually
5943
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5944
0
                return -1;
5945
0
            }
5946
0
        }
5947
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5948
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5949
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5950
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5951
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5952
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5953
104k
                  << " rowset_meta_size=" << v.size()
5954
104k
                  << " creation_time=" << rowset_meta->creation_time()
5955
104k
                  << " task_type=" << metrics_context.operation_type;
5956
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5957
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5958
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5959
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5960
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5961
20.0k
                                 "kv "
5962
20.0k
                                 "at next turn, instance_id="
5963
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5964
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5965
20.0k
                              << rowset_meta->end_version() << "]";
5966
20.0k
                    return 0;
5967
20.0k
                }
5968
50.0k
            }
5969
5970
30.9k
            num_prepare += 1;
5971
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5972
30.9k
                rowset_meta->end_version() != 1) {
5973
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5974
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5975
10.2k
                                 "instance_id="
5976
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5977
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5978
10.2k
                              << rowset_meta->end_version() << "]";
5979
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5980
10.2k
                    return 0;
5981
10.2k
                }
5982
30.2k
            }
5983
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5984
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5985
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5986
0
                return -1;
5987
0
            }
5988
53.1k
        } else {
5989
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5990
53.1k
            rowset_keys.emplace_back(k);
5991
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5992
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5993
53.1k
                ++num_empty_rowset;
5994
53.1k
            }
5995
53.1k
        }
5996
73.7k
        return 0;
5997
104k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5879
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5880
7
        ++num_scanned;
5881
7
        total_rowset_key_size += k.size();
5882
7
        total_rowset_value_size += v.size();
5883
7
        RecycleRowsetPB rowset;
5884
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5885
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5886
0
            return -1;
5887
0
        }
5888
5889
7
        int64_t current_time = ::time(nullptr);
5890
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5891
5892
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5893
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5894
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5895
7
        if (current_time < expiration) { // not expired
5896
0
            return 0;
5897
0
        }
5898
7
        ++num_expired;
5899
7
        expired_rowset_size += v.size();
5900
5901
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5902
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5903
                // in old version, keep this key-value pair and it needs to be checked manually
5904
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5905
0
                return -1;
5906
0
            }
5907
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5908
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5909
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5910
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5911
0
                rowset_keys.emplace_back(k);
5912
0
                return 0;
5913
0
            }
5914
            // decode rowset_id
5915
0
            auto k1 = k;
5916
0
            k1.remove_prefix(1);
5917
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5918
0
            decode_key(&k1, &out);
5919
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5920
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5921
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5922
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5923
0
                      << " task_type=" << metrics_context.operation_type;
5924
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5925
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5926
0
                return -1;
5927
0
            }
5928
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5929
0
            metrics_context.total_recycled_num++;
5930
0
            segment_metrics_context_.total_recycled_data_size +=
5931
0
                    rowset.rowset_meta().total_disk_size();
5932
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5933
0
            return 0;
5934
0
        }
5935
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5936
5937
        // TODO(plat1ko): check rowset not referenced
5938
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5939
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5940
0
                LOG_INFO("recycle rowset that has empty resource id");
5941
0
            } else {
5942
                // other situations, keep this key-value pair and it needs to be checked manually
5943
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5944
0
                return -1;
5945
0
            }
5946
0
        }
5947
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5948
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5949
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5950
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5951
7
                  << "] txn_id=" << rowset_meta->txn_id()
5952
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5953
7
                  << " rowset_meta_size=" << v.size()
5954
7
                  << " creation_time=" << rowset_meta->creation_time()
5955
7
                  << " task_type=" << metrics_context.operation_type;
5956
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5957
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5958
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5959
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5960
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5961
4
                                 "kv "
5962
4
                                 "at next turn, instance_id="
5963
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5964
4
                              << " version=[" << rowset_meta->start_version() << '-'
5965
4
                              << rowset_meta->end_version() << "]";
5966
4
                    return 0;
5967
4
                }
5968
6
            }
5969
5970
3
            num_prepare += 1;
5971
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5972
3
                rowset_meta->end_version() != 1) {
5973
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5974
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5975
2
                                 "instance_id="
5976
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5977
2
                              << " version=[" << rowset_meta->start_version() << '-'
5978
2
                              << rowset_meta->end_version() << "]";
5979
2
                    rowset_keys_to_abort_job.emplace_back(k);
5980
2
                    return 0;
5981
2
                }
5982
2
            }
5983
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5984
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5985
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5986
0
                return -1;
5987
0
            }
5988
1
        } else {
5989
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5990
0
            rowset_keys.emplace_back(k);
5991
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5992
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5993
0
                ++num_empty_rowset;
5994
0
            }
5995
0
        }
5996
1
        return 0;
5997
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5879
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5880
124k
        ++num_scanned;
5881
124k
        total_rowset_key_size += k.size();
5882
124k
        total_rowset_value_size += v.size();
5883
124k
        RecycleRowsetPB rowset;
5884
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5885
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5886
0
            return -1;
5887
0
        }
5888
5889
124k
        int64_t current_time = ::time(nullptr);
5890
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5891
5892
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5893
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5894
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5895
124k
        if (current_time < expiration) { // not expired
5896
0
            return 0;
5897
0
        }
5898
124k
        ++num_expired;
5899
124k
        expired_rowset_size += v.size();
5900
5901
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5902
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5903
                // in old version, keep this key-value pair and it needs to be checked manually
5904
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5905
0
                return -1;
5906
0
            }
5907
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5908
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5909
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5910
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5911
10.0k
                rowset_keys.emplace_back(k);
5912
10.0k
                return 0;
5913
10.0k
            }
5914
            // decode rowset_id
5915
10.2k
            auto k1 = k;
5916
10.2k
            k1.remove_prefix(1);
5917
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5918
10.2k
            decode_key(&k1, &out);
5919
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5920
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5921
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5922
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5923
10.2k
                      << " task_type=" << metrics_context.operation_type;
5924
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5925
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5926
0
                return -1;
5927
0
            }
5928
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5929
10.2k
            metrics_context.total_recycled_num++;
5930
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5931
10.2k
                    rowset.rowset_meta().total_disk_size();
5932
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5933
10.2k
            return 0;
5934
10.2k
        }
5935
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5936
5937
        // TODO(plat1ko): check rowset not referenced
5938
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5939
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5940
0
                LOG_INFO("recycle rowset that has empty resource id");
5941
0
            } else {
5942
                // other situations, keep this key-value pair and it needs to be checked manually
5943
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5944
0
                return -1;
5945
0
            }
5946
0
        }
5947
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5948
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5949
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5950
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5951
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5952
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5953
104k
                  << " rowset_meta_size=" << v.size()
5954
104k
                  << " creation_time=" << rowset_meta->creation_time()
5955
104k
                  << " task_type=" << metrics_context.operation_type;
5956
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5957
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5958
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5959
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5960
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5961
20.0k
                                 "kv "
5962
20.0k
                                 "at next turn, instance_id="
5963
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5964
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5965
20.0k
                              << rowset_meta->end_version() << "]";
5966
20.0k
                    return 0;
5967
20.0k
                }
5968
50.0k
            }
5969
5970
30.9k
            num_prepare += 1;
5971
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5972
30.9k
                rowset_meta->end_version() != 1) {
5973
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5974
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5975
10.2k
                                 "instance_id="
5976
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5977
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5978
10.2k
                              << rowset_meta->end_version() << "]";
5979
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5980
10.2k
                    return 0;
5981
10.2k
                }
5982
30.2k
            }
5983
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5984
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5985
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5986
0
                return -1;
5987
0
            }
5988
53.1k
        } else {
5989
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5990
53.1k
            rowset_keys.emplace_back(k);
5991
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5992
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5993
53.1k
                ++num_empty_rowset;
5994
53.1k
            }
5995
53.1k
        }
5996
73.7k
        return 0;
5997
104k
    };
5998
5999
394
    auto loop_done = [&]() -> int {
6000
394
        std::vector<std::string> rowset_keys_to_delete;
6001
        // rowset_id -> rowset_meta
6002
        // store rowset id and meta for statistics rs size when delete
6003
394
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6004
394
        std::vector<std::string> mark_keys_to_process;
6005
394
        std::vector<std::string> abort_job_keys_to_process;
6006
394
        rowset_keys_to_delete.swap(rowset_keys);
6007
394
        rowsets_to_delete.swap(rowsets);
6008
394
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6009
394
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6010
394
        if (!mark_keys_to_process.empty()) {
6011
69
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6012
69
                    *worker_pool, std::move(mark_keys_to_process));
6013
69
        }
6014
394
        if (!abort_job_keys_to_process.empty()) {
6015
46
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6016
46
                                               &num_recycled);
6017
46
        }
6018
394
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
6019
394
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
6020
394
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6021
394
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6022
394
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6023
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6024
0
                return;
6025
0
            }
6026
394
            if (!versioned_delete_bitmap_key_groups.empty() &&
6027
394
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6028
50
                                                         versioned_delete_bitmap_key_groups) != 0) {
6029
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6030
0
                             << instance_id_;
6031
0
                return;
6032
0
            }
6033
394
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6034
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6035
0
                return;
6036
0
            }
6037
394
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6038
394
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6019
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
6020
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6021
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6022
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6023
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6024
0
                return;
6025
0
            }
6026
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
6027
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6028
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
6029
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6030
0
                             << instance_id_;
6031
0
                return;
6032
0
            }
6033
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6034
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6035
0
                return;
6036
0
            }
6037
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6038
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
6019
387
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
6020
387
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6021
387
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6022
387
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6023
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6024
0
                return;
6025
0
            }
6026
387
            if (!versioned_delete_bitmap_key_groups.empty() &&
6027
387
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6028
50
                                                         versioned_delete_bitmap_key_groups) != 0) {
6029
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6030
0
                             << instance_id_;
6031
0
                return;
6032
0
            }
6033
387
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6034
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6035
0
                return;
6036
0
            }
6037
387
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6038
387
        });
6039
394
        return 0;
6040
394
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5999
7
    auto loop_done = [&]() -> int {
6000
7
        std::vector<std::string> rowset_keys_to_delete;
6001
        // rowset_id -> rowset_meta
6002
        // store rowset id and meta for statistics rs size when delete
6003
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6004
7
        std::vector<std::string> mark_keys_to_process;
6005
7
        std::vector<std::string> abort_job_keys_to_process;
6006
7
        rowset_keys_to_delete.swap(rowset_keys);
6007
7
        rowsets_to_delete.swap(rowsets);
6008
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6009
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6010
7
        if (!mark_keys_to_process.empty()) {
6011
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6012
4
                    *worker_pool, std::move(mark_keys_to_process));
6013
4
        }
6014
7
        if (!abort_job_keys_to_process.empty()) {
6015
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6016
2
                                               &num_recycled);
6017
2
        }
6018
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
6019
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
6020
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6021
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6022
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6023
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6024
7
                return;
6025
7
            }
6026
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
6027
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6028
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
6029
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6030
7
                             << instance_id_;
6031
7
                return;
6032
7
            }
6033
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6034
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6035
7
                return;
6036
7
            }
6037
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6038
7
        });
6039
7
        return 0;
6040
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5999
387
    auto loop_done = [&]() -> int {
6000
387
        std::vector<std::string> rowset_keys_to_delete;
6001
        // rowset_id -> rowset_meta
6002
        // store rowset id and meta for statistics rs size when delete
6003
387
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
6004
387
        std::vector<std::string> mark_keys_to_process;
6005
387
        std::vector<std::string> abort_job_keys_to_process;
6006
387
        rowset_keys_to_delete.swap(rowset_keys);
6007
387
        rowsets_to_delete.swap(rowsets);
6008
387
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
6009
387
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
6010
387
        if (!mark_keys_to_process.empty()) {
6011
65
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
6012
65
                    *worker_pool, std::move(mark_keys_to_process));
6013
65
        }
6014
387
        if (!abort_job_keys_to_process.empty()) {
6015
44
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
6016
44
                                               &num_recycled);
6017
44
        }
6018
387
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
6019
387
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
6020
387
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6021
387
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6022
387
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6023
387
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6024
387
                return;
6025
387
            }
6026
387
            if (!versioned_delete_bitmap_key_groups.empty() &&
6027
387
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6028
387
                                                         versioned_delete_bitmap_key_groups) != 0) {
6029
387
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6030
387
                             << instance_id_;
6031
387
                return;
6032
387
            }
6033
387
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6034
387
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6035
387
                return;
6036
387
            }
6037
387
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6038
387
        });
6039
387
        return 0;
6040
387
    };
6041
6042
61
    if (config::enable_recycler_stats_metrics) {
6043
0
        scan_and_statistics_rowsets();
6044
0
    }
6045
    // recycle_func and loop_done for scan and recycle
6046
61
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6047
61
                               std::move(loop_done));
6048
6049
61
    worker_pool->stop();
6050
6051
61
    if (!async_recycled_rowset_keys.empty()) {
6052
9
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6053
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6054
0
            return -1;
6055
9
        } else {
6056
9
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6057
9
        }
6058
9
    }
6059
6060
    // Report final metrics after all concurrent tasks completed
6061
61
    segment_metrics_context_.report();
6062
61
    metrics_context.report();
6063
6064
61
    return ret;
6065
61
}
6066
6067
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
6068
0
                                                     int64_t tablet_id, std::string* next_key) {
6069
0
    DCHECK(next_key != nullptr);
6070
0
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
6071
0
        return -1;
6072
0
    }
6073
0
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
6074
0
    return 0;
6075
0
}
6076
6077
13
int InstanceRecycler::recycle_restore_jobs() {
6078
13
    const std::string task_name = "recycle_restore_jobs";
6079
13
    int64_t num_scanned = 0;
6080
13
    int64_t num_expired = 0;
6081
13
    int64_t num_recycled = 0;
6082
13
    int64_t num_aborted = 0;
6083
6084
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6085
6086
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6087
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6088
13
    std::string restore_job_key0;
6089
13
    std::string restore_job_key1;
6090
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6091
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6092
6093
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6094
6095
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6096
13
    register_recycle_task(task_name, start_time);
6097
6098
13
    DORIS_CLOUD_DEFER {
6099
13
        unregister_recycle_task(task_name);
6100
13
        int64_t cost =
6101
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6102
13
        metrics_context.finish_report();
6103
6104
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6105
13
                .tag("instance_id", instance_id_)
6106
13
                .tag("num_scanned", num_scanned)
6107
13
                .tag("num_expired", num_expired)
6108
13
                .tag("num_recycled", num_recycled)
6109
13
                .tag("num_aborted", num_aborted);
6110
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6098
13
    DORIS_CLOUD_DEFER {
6099
13
        unregister_recycle_task(task_name);
6100
13
        int64_t cost =
6101
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6102
13
        metrics_context.finish_report();
6103
6104
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6105
13
                .tag("instance_id", instance_id_)
6106
13
                .tag("num_scanned", num_scanned)
6107
13
                .tag("num_expired", num_expired)
6108
13
                .tag("num_recycled", num_recycled)
6109
13
                .tag("num_aborted", num_aborted);
6110
13
    };
6111
6112
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6113
6114
13
    std::vector<std::string_view> restore_job_keys;
6115
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6116
41
        ++num_scanned;
6117
41
        RestoreJobCloudPB restore_job_pb;
6118
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6119
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6120
0
            return -1;
6121
0
        }
6122
41
        int64_t expiration =
6123
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6124
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6125
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6126
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6127
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6128
0
                   << " state=" << restore_job_pb.state();
6129
41
        int64_t current_time = ::time(nullptr);
6130
41
        if (current_time < expiration) { // not expired
6131
0
            return 0;
6132
0
        }
6133
41
        ++num_expired;
6134
6135
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6136
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6137
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6138
6139
41
        std::unique_ptr<Transaction> txn;
6140
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6141
41
        if (err != TxnErrorCode::TXN_OK) {
6142
0
            LOG_WARNING("failed to recycle restore job")
6143
0
                    .tag("err", err)
6144
0
                    .tag("tablet id", tablet_id)
6145
0
                    .tag("instance_id", instance_id_)
6146
0
                    .tag("reason", "failed to create txn");
6147
0
            return -1;
6148
0
        }
6149
6150
41
        std::string val;
6151
41
        err = txn->get(k, &val);
6152
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6153
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6154
0
            return 0;
6155
0
        }
6156
41
        if (err != TxnErrorCode::TXN_OK) {
6157
0
            LOG_WARNING("failed to get kv");
6158
0
            return -1;
6159
0
        }
6160
41
        restore_job_pb.Clear();
6161
41
        if (!restore_job_pb.ParseFromString(val)) {
6162
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6163
0
            return -1;
6164
0
        }
6165
6166
        // PREPARED or COMMITTED, change state to DROPPED and return
6167
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6168
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6169
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6170
0
            restore_job_pb.set_need_recycle_data(true);
6171
0
            txn->put(k, restore_job_pb.SerializeAsString());
6172
0
            err = txn->commit();
6173
0
            if (err != TxnErrorCode::TXN_OK) {
6174
0
                LOG_WARNING("failed to commit txn: {}", err);
6175
0
                return -1;
6176
0
            }
6177
0
            num_aborted++;
6178
0
            return 0;
6179
0
        }
6180
6181
        // Change state to RECYCLING
6182
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6183
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6184
21
            txn->put(k, restore_job_pb.SerializeAsString());
6185
21
            err = txn->commit();
6186
21
            if (err != TxnErrorCode::TXN_OK) {
6187
0
                LOG_WARNING("failed to commit txn: {}", err);
6188
0
                return -1;
6189
0
            }
6190
21
            return 0;
6191
21
        }
6192
6193
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6194
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6195
6196
        // Recycle all data associated with the restore job.
6197
        // This includes rowsets, segments, and related resources.
6198
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6199
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6200
0
            LOG_WARNING("failed to recycle tablet")
6201
0
                    .tag("tablet_id", tablet_id)
6202
0
                    .tag("instance_id", instance_id_);
6203
0
            return -1;
6204
0
        }
6205
6206
        // delete all restore job rowset kv
6207
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6208
6209
20
        err = txn->commit();
6210
20
        if (err != TxnErrorCode::TXN_OK) {
6211
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6212
0
                    .tag("err", err)
6213
0
                    .tag("tablet id", tablet_id)
6214
0
                    .tag("instance_id", instance_id_)
6215
0
                    .tag("reason", "failed to commit txn");
6216
0
            return -1;
6217
0
        }
6218
6219
20
        metrics_context.total_recycled_num = ++num_recycled;
6220
20
        metrics_context.report();
6221
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6222
20
        restore_job_keys.push_back(k);
6223
6224
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6225
20
                  << " tablet_id=" << tablet_id;
6226
20
        return 0;
6227
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
6115
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6116
41
        ++num_scanned;
6117
41
        RestoreJobCloudPB restore_job_pb;
6118
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6119
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6120
0
            return -1;
6121
0
        }
6122
41
        int64_t expiration =
6123
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6124
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6125
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6126
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6127
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6128
0
                   << " state=" << restore_job_pb.state();
6129
41
        int64_t current_time = ::time(nullptr);
6130
41
        if (current_time < expiration) { // not expired
6131
0
            return 0;
6132
0
        }
6133
41
        ++num_expired;
6134
6135
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6136
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6137
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6138
6139
41
        std::unique_ptr<Transaction> txn;
6140
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6141
41
        if (err != TxnErrorCode::TXN_OK) {
6142
0
            LOG_WARNING("failed to recycle restore job")
6143
0
                    .tag("err", err)
6144
0
                    .tag("tablet id", tablet_id)
6145
0
                    .tag("instance_id", instance_id_)
6146
0
                    .tag("reason", "failed to create txn");
6147
0
            return -1;
6148
0
        }
6149
6150
41
        std::string val;
6151
41
        err = txn->get(k, &val);
6152
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6153
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6154
0
            return 0;
6155
0
        }
6156
41
        if (err != TxnErrorCode::TXN_OK) {
6157
0
            LOG_WARNING("failed to get kv");
6158
0
            return -1;
6159
0
        }
6160
41
        restore_job_pb.Clear();
6161
41
        if (!restore_job_pb.ParseFromString(val)) {
6162
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6163
0
            return -1;
6164
0
        }
6165
6166
        // PREPARED or COMMITTED, change state to DROPPED and return
6167
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6168
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6169
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6170
0
            restore_job_pb.set_need_recycle_data(true);
6171
0
            txn->put(k, restore_job_pb.SerializeAsString());
6172
0
            err = txn->commit();
6173
0
            if (err != TxnErrorCode::TXN_OK) {
6174
0
                LOG_WARNING("failed to commit txn: {}", err);
6175
0
                return -1;
6176
0
            }
6177
0
            num_aborted++;
6178
0
            return 0;
6179
0
        }
6180
6181
        // Change state to RECYCLING
6182
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6183
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6184
21
            txn->put(k, restore_job_pb.SerializeAsString());
6185
21
            err = txn->commit();
6186
21
            if (err != TxnErrorCode::TXN_OK) {
6187
0
                LOG_WARNING("failed to commit txn: {}", err);
6188
0
                return -1;
6189
0
            }
6190
21
            return 0;
6191
21
        }
6192
6193
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6194
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6195
6196
        // Recycle all data associated with the restore job.
6197
        // This includes rowsets, segments, and related resources.
6198
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6199
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6200
0
            LOG_WARNING("failed to recycle tablet")
6201
0
                    .tag("tablet_id", tablet_id)
6202
0
                    .tag("instance_id", instance_id_);
6203
0
            return -1;
6204
0
        }
6205
6206
        // delete all restore job rowset kv
6207
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6208
6209
20
        err = txn->commit();
6210
20
        if (err != TxnErrorCode::TXN_OK) {
6211
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6212
0
                    .tag("err", err)
6213
0
                    .tag("tablet id", tablet_id)
6214
0
                    .tag("instance_id", instance_id_)
6215
0
                    .tag("reason", "failed to commit txn");
6216
0
            return -1;
6217
0
        }
6218
6219
20
        metrics_context.total_recycled_num = ++num_recycled;
6220
20
        metrics_context.report();
6221
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6222
20
        restore_job_keys.push_back(k);
6223
6224
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6225
20
                  << " tablet_id=" << tablet_id;
6226
20
        return 0;
6227
20
    };
6228
6229
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6230
3
        if (restore_job_keys.empty()) return 0;
6231
1
        DORIS_CLOUD_DEFER {
6232
1
            restore_job_keys.clear();
6233
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6231
1
        DORIS_CLOUD_DEFER {
6232
1
            restore_job_keys.clear();
6233
1
        };
6234
6235
1
        std::unique_ptr<Transaction> txn;
6236
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6237
1
        if (err != TxnErrorCode::TXN_OK) {
6238
0
            LOG_WARNING("failed to recycle restore job")
6239
0
                    .tag("err", err)
6240
0
                    .tag("instance_id", instance_id_)
6241
0
                    .tag("reason", "failed to create txn");
6242
0
            return -1;
6243
0
        }
6244
20
        for (auto& k : restore_job_keys) {
6245
20
            txn->remove(k);
6246
20
        }
6247
1
        err = txn->commit();
6248
1
        if (err != TxnErrorCode::TXN_OK) {
6249
0
            LOG_WARNING("failed to recycle restore job")
6250
0
                    .tag("err", err)
6251
0
                    .tag("instance_id", instance_id_)
6252
0
                    .tag("reason", "failed to commit txn");
6253
0
            return -1;
6254
0
        }
6255
1
        return 0;
6256
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6229
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6230
3
        if (restore_job_keys.empty()) return 0;
6231
1
        DORIS_CLOUD_DEFER {
6232
1
            restore_job_keys.clear();
6233
1
        };
6234
6235
1
        std::unique_ptr<Transaction> txn;
6236
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6237
1
        if (err != TxnErrorCode::TXN_OK) {
6238
0
            LOG_WARNING("failed to recycle restore job")
6239
0
                    .tag("err", err)
6240
0
                    .tag("instance_id", instance_id_)
6241
0
                    .tag("reason", "failed to create txn");
6242
0
            return -1;
6243
0
        }
6244
20
        for (auto& k : restore_job_keys) {
6245
20
            txn->remove(k);
6246
20
        }
6247
1
        err = txn->commit();
6248
1
        if (err != TxnErrorCode::TXN_OK) {
6249
0
            LOG_WARNING("failed to recycle restore job")
6250
0
                    .tag("err", err)
6251
0
                    .tag("instance_id", instance_id_)
6252
0
                    .tag("reason", "failed to commit txn");
6253
0
            return -1;
6254
0
        }
6255
1
        return 0;
6256
1
    };
6257
6258
13
    if (config::enable_recycler_stats_metrics) {
6259
0
        scan_and_statistics_restore_jobs();
6260
0
    }
6261
6262
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6263
13
                            std::move(loop_done));
6264
13
}
6265
6266
11
int InstanceRecycler::recycle_versioned_rowsets() {
6267
11
    const std::string task_name = "recycle_rowsets";
6268
11
    int64_t num_scanned = 0;
6269
11
    int64_t num_expired = 0;
6270
11
    int64_t num_prepare = 0;
6271
11
    int64_t num_compacted = 0;
6272
11
    int64_t num_empty_rowset = 0;
6273
11
    size_t total_rowset_key_size = 0;
6274
11
    size_t total_rowset_value_size = 0;
6275
11
    size_t expired_rowset_size = 0;
6276
11
    std::atomic_long num_recycled = 0;
6277
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6278
6279
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6280
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6281
11
    std::string recyc_rs_key0;
6282
11
    std::string recyc_rs_key1;
6283
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6284
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6285
6286
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6287
6288
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6289
11
    register_recycle_task(task_name, start_time);
6290
6291
11
    DORIS_CLOUD_DEFER {
6292
11
        unregister_recycle_task(task_name);
6293
11
        int64_t cost =
6294
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6295
11
        metrics_context.finish_report();
6296
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6297
11
                .tag("instance_id", instance_id_)
6298
11
                .tag("num_scanned", num_scanned)
6299
11
                .tag("num_expired", num_expired)
6300
11
                .tag("num_recycled", num_recycled)
6301
11
                .tag("num_recycled.prepare", num_prepare)
6302
11
                .tag("num_recycled.compacted", num_compacted)
6303
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6304
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6305
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6306
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6307
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6291
11
    DORIS_CLOUD_DEFER {
6292
11
        unregister_recycle_task(task_name);
6293
11
        int64_t cost =
6294
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6295
11
        metrics_context.finish_report();
6296
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6297
11
                .tag("instance_id", instance_id_)
6298
11
                .tag("num_scanned", num_scanned)
6299
11
                .tag("num_expired", num_expired)
6300
11
                .tag("num_recycled", num_recycled)
6301
11
                .tag("num_recycled.prepare", num_prepare)
6302
11
                .tag("num_recycled.compacted", num_compacted)
6303
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6304
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6305
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6306
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6307
11
    };
6308
6309
11
    std::vector<std::string> orphan_rowset_keys;
6310
6311
    // Store keys of rowset recycled by background workers
6312
11
    std::mutex async_recycled_rowset_keys_mutex;
6313
11
    std::vector<std::string> async_recycled_rowset_keys;
6314
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6315
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6316
11
    worker_pool->start();
6317
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6318
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6319
        // Try to delete rowset data in background thread
6320
400
        int ret = worker_pool->submit_with_timeout(
6321
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6322
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6323
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6324
400
                        return;
6325
400
                    }
6326
                    // The async recycled rowsets are staled format or has not been used,
6327
                    // so we don't need to check the rowset ref count key.
6328
0
                    std::vector<std::string> keys;
6329
0
                    {
6330
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6331
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6332
0
                        if (async_recycled_rowset_keys.size() > 100) {
6333
0
                            keys.swap(async_recycled_rowset_keys);
6334
0
                        }
6335
0
                    }
6336
0
                    if (keys.empty()) return;
6337
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6338
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6339
0
                                     << instance_id_;
6340
0
                    } else {
6341
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6342
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6343
0
                                           num_recycled, start_time);
6344
0
                    }
6345
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
6321
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6322
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6323
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6324
400
                        return;
6325
400
                    }
6326
                    // The async recycled rowsets are staled format or has not been used,
6327
                    // so we don't need to check the rowset ref count key.
6328
0
                    std::vector<std::string> keys;
6329
0
                    {
6330
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6331
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6332
0
                        if (async_recycled_rowset_keys.size() > 100) {
6333
0
                            keys.swap(async_recycled_rowset_keys);
6334
0
                        }
6335
0
                    }
6336
0
                    if (keys.empty()) return;
6337
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6338
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6339
0
                                     << instance_id_;
6340
0
                    } else {
6341
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6342
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6343
0
                                           num_recycled, start_time);
6344
0
                    }
6345
0
                },
6346
400
                0);
6347
400
        if (ret == 0) return 0;
6348
        // Submit task failed, delete rowset data in current thread
6349
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6350
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6351
0
            return -1;
6352
0
        }
6353
0
        orphan_rowset_keys.push_back(std::move(key));
6354
0
        return 0;
6355
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
6318
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6319
        // Try to delete rowset data in background thread
6320
400
        int ret = worker_pool->submit_with_timeout(
6321
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6322
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6323
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6324
400
                        return;
6325
400
                    }
6326
                    // The async recycled rowsets are staled format or has not been used,
6327
                    // so we don't need to check the rowset ref count key.
6328
400
                    std::vector<std::string> keys;
6329
400
                    {
6330
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6331
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6332
400
                        if (async_recycled_rowset_keys.size() > 100) {
6333
400
                            keys.swap(async_recycled_rowset_keys);
6334
400
                        }
6335
400
                    }
6336
400
                    if (keys.empty()) return;
6337
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6338
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6339
400
                                     << instance_id_;
6340
400
                    } else {
6341
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6342
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6343
400
                                           num_recycled, start_time);
6344
400
                    }
6345
400
                },
6346
400
                0);
6347
400
        if (ret == 0) return 0;
6348
        // Submit task failed, delete rowset data in current thread
6349
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6350
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6351
0
            return -1;
6352
0
        }
6353
0
        orphan_rowset_keys.push_back(std::move(key));
6354
0
        return 0;
6355
0
    };
6356
6357
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6358
6359
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6360
2.01k
        ++num_scanned;
6361
2.01k
        total_rowset_key_size += k.size();
6362
2.01k
        total_rowset_value_size += v.size();
6363
2.01k
        RecycleRowsetPB rowset;
6364
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6365
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6366
0
            return -1;
6367
0
        }
6368
6369
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6370
6371
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6372
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6373
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6374
2.01k
        int64_t current_time = ::time(nullptr);
6375
2.01k
        if (current_time < final_expiration) { // not expired
6376
0
            return 0;
6377
0
        }
6378
2.01k
        ++num_expired;
6379
2.01k
        expired_rowset_size += v.size();
6380
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6381
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6382
                // in old version, keep this key-value pair and it needs to be checked manually
6383
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6384
0
                return -1;
6385
0
            }
6386
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6387
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6388
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6389
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6390
0
                orphan_rowset_keys.emplace_back(k);
6391
0
                return -1;
6392
0
            }
6393
            // decode rowset_id
6394
0
            auto k1 = k;
6395
0
            k1.remove_prefix(1);
6396
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6397
0
            decode_key(&k1, &out);
6398
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6399
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6400
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6401
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6402
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6403
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6404
0
                return -1;
6405
0
            }
6406
0
            return 0;
6407
0
        }
6408
        // TODO(plat1ko): check rowset not referenced
6409
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6410
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6411
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6412
0
                LOG_INFO("recycle rowset that has empty resource id");
6413
0
            } else {
6414
                // other situations, keep this key-value pair and it needs to be checked manually
6415
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6416
0
                return -1;
6417
0
            }
6418
0
        }
6419
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6420
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6421
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6422
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6423
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6424
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6425
2.01k
                  << " rowset_meta_size=" << v.size()
6426
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6427
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6428
            // unable to calculate file path, can only be deleted by rowset id prefix
6429
400
            num_prepare += 1;
6430
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6431
400
                                             rowset_meta->tablet_id(),
6432
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6433
0
                return -1;
6434
0
            }
6435
1.61k
        } else {
6436
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6437
1.61k
            worker_pool->submit(
6438
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6439
                        // The load & compact rowset keys are recycled during recycling operation logs.
6440
1.61k
                        RowsetDeleteTask task;
6441
1.61k
                        task.rowset_meta = rowset_meta;
6442
1.61k
                        task.recycle_rowset_key = k;
6443
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6444
1.59k
                            return;
6445
1.59k
                        }
6446
15
                        num_compacted += is_compacted;
6447
15
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6448
15
                        if (rowset_meta.num_segments() == 0) {
6449
0
                            ++num_empty_rowset;
6450
0
                        }
6451
15
                    });
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
6438
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6439
                        // The load & compact rowset keys are recycled during recycling operation logs.
6440
1.61k
                        RowsetDeleteTask task;
6441
1.61k
                        task.rowset_meta = rowset_meta;
6442
1.61k
                        task.recycle_rowset_key = k;
6443
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6444
1.59k
                            return;
6445
1.59k
                        }
6446
15
                        num_compacted += is_compacted;
6447
15
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6448
15
                        if (rowset_meta.num_segments() == 0) {
6449
0
                            ++num_empty_rowset;
6450
0
                        }
6451
15
                    });
6452
1.61k
        }
6453
2.01k
        return 0;
6454
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
6359
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6360
2.01k
        ++num_scanned;
6361
2.01k
        total_rowset_key_size += k.size();
6362
2.01k
        total_rowset_value_size += v.size();
6363
2.01k
        RecycleRowsetPB rowset;
6364
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6365
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6366
0
            return -1;
6367
0
        }
6368
6369
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6370
6371
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6372
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6373
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6374
2.01k
        int64_t current_time = ::time(nullptr);
6375
2.01k
        if (current_time < final_expiration) { // not expired
6376
0
            return 0;
6377
0
        }
6378
2.01k
        ++num_expired;
6379
2.01k
        expired_rowset_size += v.size();
6380
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6381
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6382
                // in old version, keep this key-value pair and it needs to be checked manually
6383
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6384
0
                return -1;
6385
0
            }
6386
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6387
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6388
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6389
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6390
0
                orphan_rowset_keys.emplace_back(k);
6391
0
                return -1;
6392
0
            }
6393
            // decode rowset_id
6394
0
            auto k1 = k;
6395
0
            k1.remove_prefix(1);
6396
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6397
0
            decode_key(&k1, &out);
6398
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6399
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6400
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6401
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6402
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6403
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6404
0
                return -1;
6405
0
            }
6406
0
            return 0;
6407
0
        }
6408
        // TODO(plat1ko): check rowset not referenced
6409
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6410
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6411
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6412
0
                LOG_INFO("recycle rowset that has empty resource id");
6413
0
            } else {
6414
                // other situations, keep this key-value pair and it needs to be checked manually
6415
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6416
0
                return -1;
6417
0
            }
6418
0
        }
6419
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6420
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6421
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6422
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6423
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6424
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6425
2.01k
                  << " rowset_meta_size=" << v.size()
6426
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6427
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6428
            // unable to calculate file path, can only be deleted by rowset id prefix
6429
400
            num_prepare += 1;
6430
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6431
400
                                             rowset_meta->tablet_id(),
6432
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6433
0
                return -1;
6434
0
            }
6435
1.61k
        } else {
6436
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6437
1.61k
            worker_pool->submit(
6438
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6439
                        // The load & compact rowset keys are recycled during recycling operation logs.
6440
1.61k
                        RowsetDeleteTask task;
6441
1.61k
                        task.rowset_meta = rowset_meta;
6442
1.61k
                        task.recycle_rowset_key = k;
6443
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6444
1.61k
                            return;
6445
1.61k
                        }
6446
1.61k
                        num_compacted += is_compacted;
6447
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6448
1.61k
                        if (rowset_meta.num_segments() == 0) {
6449
1.61k
                            ++num_empty_rowset;
6450
1.61k
                        }
6451
1.61k
                    });
6452
1.61k
        }
6453
2.01k
        return 0;
6454
2.01k
    };
6455
6456
11
    if (config::enable_recycler_stats_metrics) {
6457
0
        scan_and_statistics_rowsets();
6458
0
    }
6459
6460
11
    auto loop_done = [&]() -> int {
6461
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6462
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6463
0
        }
6464
6
        orphan_rowset_keys.clear();
6465
6
        return 0;
6466
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6460
6
    auto loop_done = [&]() -> int {
6461
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6462
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6463
0
        }
6464
6
        orphan_rowset_keys.clear();
6465
6
        return 0;
6466
6
    };
6467
6468
    // recycle_func and loop_done for scan and recycle
6469
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6470
11
                               std::move(loop_done));
6471
6472
11
    worker_pool->stop();
6473
6474
11
    if (!async_recycled_rowset_keys.empty()) {
6475
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6476
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6477
0
            return -1;
6478
0
        } else {
6479
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6480
0
        }
6481
0
    }
6482
6483
    // Report final metrics after all concurrent tasks completed
6484
11
    segment_metrics_context_.report();
6485
11
    metrics_context.report();
6486
6487
11
    return ret;
6488
11
}
6489
6490
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6491
1.61k
    constexpr int MAX_RETRY = 10;
6492
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6493
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6494
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6495
1.61k
    std::string_view reference_instance_id = instance_id_;
6496
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6497
8
        reference_instance_id = rowset_meta.reference_instance_id();
6498
8
    }
6499
6500
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6501
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6502
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6503
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6504
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6505
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6506
1.61k
        std::unique_ptr<Transaction> txn;
6507
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6508
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6509
0
            LOG_WARNING("failed to create txn").tag("err", err);
6510
0
            return -1;
6511
0
        }
6512
6513
1.61k
        std::string rowset_ref_count_key =
6514
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6515
1.61k
        int64_t ref_count = 0;
6516
1.61k
        {
6517
1.61k
            std::string value;
6518
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6519
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6520
                // This is the old version rowset, we could recycle it directly.
6521
1.60k
                ref_count = 1;
6522
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6523
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6524
0
                return -1;
6525
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6526
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6527
0
                return -1;
6528
0
            }
6529
1.61k
        }
6530
6531
1.61k
        if (ref_count == 1) {
6532
            // It would not be added since it is recycling.
6533
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6534
1.60k
                LOG_WARNING("failed to delete rowset data");
6535
1.60k
                return -1;
6536
1.60k
            }
6537
6538
            // Reset the transaction to avoid timeout.
6539
10
            err = txn_kv_->create_txn(&txn);
6540
10
            if (err != TxnErrorCode::TXN_OK) {
6541
0
                LOG_WARNING("failed to create txn").tag("err", err);
6542
0
                return -1;
6543
0
            }
6544
10
            txn->remove(rowset_ref_count_key);
6545
10
            LOG_INFO("delete rowset data ref count key")
6546
10
                    .tag("txn_id", rowset_meta.txn_id())
6547
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6548
6549
10
            std::string dbm_start_key =
6550
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6551
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6552
10
                    {reference_instance_id, tablet_id, rowset_id,
6553
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6554
10
            txn->remove(dbm_start_key, dbm_end_key);
6555
10
            LOG_INFO("remove delete bitmap kv")
6556
10
                    .tag("begin", hex(dbm_start_key))
6557
10
                    .tag("end", hex(dbm_end_key));
6558
6559
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6560
10
                    {reference_instance_id, tablet_id, rowset_id});
6561
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6562
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6563
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6564
10
            LOG_INFO("remove versioned delete bitmap kv")
6565
10
                    .tag("begin", hex(versioned_dbm_start_key))
6566
10
                    .tag("end", hex(versioned_dbm_end_key));
6567
10
        } else {
6568
            // Decrease the rowset ref count.
6569
            //
6570
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6571
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6572
3
            txn->atomic_add(rowset_ref_count_key, -1);
6573
3
            LOG_INFO("decrease rowset data ref count")
6574
3
                    .tag("txn_id", rowset_meta.txn_id())
6575
3
                    .tag("ref_count", ref_count - 1)
6576
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6577
3
        }
6578
6579
13
        if (!task.versioned_rowset_key.empty()) {
6580
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6581
0
                                                          task.versionstamp);
6582
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6583
0
        }
6584
6585
13
        if (!task.non_versioned_rowset_key.empty()) {
6586
0
            txn->remove(task.non_versioned_rowset_key);
6587
0
            LOG_INFO("remove non versioned rowset key")
6588
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6589
0
        }
6590
6591
        // empty when recycle ref rowsets for deleted instance
6592
13
        if (!task.recycle_rowset_key.empty()) {
6593
12
            txn->remove(task.recycle_rowset_key);
6594
12
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6595
12
        }
6596
6597
13
        err = txn->commit();
6598
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6599
            // The rowset ref count key has been changed, we need to retry.
6600
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6601
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6602
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6603
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6604
0
            continue;
6605
13
        } else if (err != TxnErrorCode::TXN_OK) {
6606
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6607
0
            return -1;
6608
0
        }
6609
13
        LOG_INFO("recycle rowset meta and data success");
6610
13
        return 0;
6611
13
    }
6612
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6613
0
            .tag("tablet_id", tablet_id)
6614
0
            .tag("rowset_id", rowset_id)
6615
0
            .tag("retry", MAX_RETRY);
6616
0
    return -1;
6617
1.61k
}
6618
6619
37
int InstanceRecycler::recycle_tmp_rowsets() {
6620
37
    const std::string task_name = "recycle_tmp_rowsets";
6621
37
    int64_t num_scanned = 0;
6622
37
    int64_t num_expired = 0;
6623
37
    std::atomic_long num_recycled = 0;
6624
37
    size_t expired_rowset_size = 0;
6625
37
    size_t total_rowset_key_size = 0;
6626
37
    size_t total_rowset_value_size = 0;
6627
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6628
6629
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6630
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6631
37
    std::string tmp_rs_key0;
6632
37
    std::string tmp_rs_key1;
6633
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6634
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6635
6636
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6637
6638
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6639
37
    register_recycle_task(task_name, start_time);
6640
6641
37
    DORIS_CLOUD_DEFER {
6642
37
        unregister_recycle_task(task_name);
6643
37
        int64_t cost =
6644
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6645
37
        metrics_context.finish_report();
6646
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6647
37
                .tag("instance_id", instance_id_)
6648
37
                .tag("num_scanned", num_scanned)
6649
37
                .tag("num_expired", num_expired)
6650
37
                .tag("num_recycled", num_recycled)
6651
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6652
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6653
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6654
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6641
12
    DORIS_CLOUD_DEFER {
6642
12
        unregister_recycle_task(task_name);
6643
12
        int64_t cost =
6644
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6645
12
        metrics_context.finish_report();
6646
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6647
12
                .tag("instance_id", instance_id_)
6648
12
                .tag("num_scanned", num_scanned)
6649
12
                .tag("num_expired", num_expired)
6650
12
                .tag("num_recycled", num_recycled)
6651
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6652
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6653
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6654
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6641
25
    DORIS_CLOUD_DEFER {
6642
25
        unregister_recycle_task(task_name);
6643
25
        int64_t cost =
6644
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6645
25
        metrics_context.finish_report();
6646
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6647
25
                .tag("instance_id", instance_id_)
6648
25
                .tag("num_scanned", num_scanned)
6649
25
                .tag("num_expired", num_expired)
6650
25
                .tag("num_recycled", num_recycled)
6651
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6652
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6653
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6654
25
    };
6655
6656
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6657
37
    std::vector<std::string> tmp_rowset_keys;
6658
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6659
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6660
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6661
6662
    // rowset_id -> rowset_meta
6663
    // store tmp_rowset id and meta for statistics rs size when delete
6664
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6665
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6666
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6667
37
    worker_pool->start();
6668
6669
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6670
6671
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6672
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6673
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6674
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6675
53.2k
                                    std::string_view k, std::string_view v) -> int {
6676
53.2k
        ++num_scanned;
6677
53.2k
        total_rowset_key_size += k.size();
6678
53.2k
        total_rowset_value_size += v.size();
6679
53.2k
        doris::RowsetMetaCloudPB rowset;
6680
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6681
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6685
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6686
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6687
0
                   << " txn_expiration=" << rowset.txn_expiration()
6688
0
                   << " rowset_creation_time=" << rowset.creation_time();
6689
53.2k
        int64_t current_time = ::time(nullptr);
6690
53.2k
        if (current_time < expiration) { // not expired
6691
0
            return 0;
6692
0
        }
6693
53.2k
        ++num_expired;
6694
53.2k
        expired_rowset_size += v.size();
6695
53.2k
        if (!rowset.has_resource_id()) {
6696
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6697
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6698
0
                return -1;
6699
0
            }
6700
            // might be a delete pred rowset
6701
0
            tmp_rowset_keys.emplace_back(k);
6702
0
            return 0;
6703
0
        }
6704
6705
        // TODO(plat1ko): check rowset not referenced
6706
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6707
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6708
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6709
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6710
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6711
53.2k
                  << " num_expired=" << num_expired
6712
53.2k
                  << " task_type=" << metrics_context.operation_type;
6713
6714
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6715
16
            if (need_mark_rowset_as_recycled(rowset)) {
6716
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6717
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6718
9
                             "at next turn, instance_id="
6719
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6720
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6721
9
                return 0;
6722
9
            }
6723
16
        }
6724
6725
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6726
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6727
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6728
261
                             "instance_id="
6729
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6730
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6731
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6732
261
                return 0;
6733
261
            }
6734
265
        }
6735
6736
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6737
        // Remove the rowset ref count key directly since it has not been used.
6738
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6739
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6740
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6741
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6742
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6743
6744
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6745
53.0k
        return 0;
6746
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6675
16
                                    std::string_view k, std::string_view v) -> int {
6676
16
        ++num_scanned;
6677
16
        total_rowset_key_size += k.size();
6678
16
        total_rowset_value_size += v.size();
6679
16
        doris::RowsetMetaCloudPB rowset;
6680
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6681
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6685
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6686
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6687
0
                   << " txn_expiration=" << rowset.txn_expiration()
6688
0
                   << " rowset_creation_time=" << rowset.creation_time();
6689
16
        int64_t current_time = ::time(nullptr);
6690
16
        if (current_time < expiration) { // not expired
6691
0
            return 0;
6692
0
        }
6693
16
        ++num_expired;
6694
16
        expired_rowset_size += v.size();
6695
16
        if (!rowset.has_resource_id()) {
6696
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6697
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6698
0
                return -1;
6699
0
            }
6700
            // might be a delete pred rowset
6701
0
            tmp_rowset_keys.emplace_back(k);
6702
0
            return 0;
6703
0
        }
6704
6705
        // TODO(plat1ko): check rowset not referenced
6706
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6707
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6708
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6709
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6710
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6711
16
                  << " num_expired=" << num_expired
6712
16
                  << " task_type=" << metrics_context.operation_type;
6713
6714
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6715
16
            if (need_mark_rowset_as_recycled(rowset)) {
6716
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6717
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6718
9
                             "at next turn, instance_id="
6719
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6720
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6721
9
                return 0;
6722
9
            }
6723
16
        }
6724
6725
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6726
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6727
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6728
3
                             "instance_id="
6729
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6730
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6731
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6732
3
                return 0;
6733
3
            }
6734
7
        }
6735
6736
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6737
        // Remove the rowset ref count key directly since it has not been used.
6738
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6739
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6740
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6741
4
                  << "key=" << hex(rowset_ref_count_key);
6742
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6743
6744
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6745
4
        return 0;
6746
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6675
53.2k
                                    std::string_view k, std::string_view v) -> int {
6676
53.2k
        ++num_scanned;
6677
53.2k
        total_rowset_key_size += k.size();
6678
53.2k
        total_rowset_value_size += v.size();
6679
53.2k
        doris::RowsetMetaCloudPB rowset;
6680
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6681
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6685
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6686
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6687
0
                   << " txn_expiration=" << rowset.txn_expiration()
6688
0
                   << " rowset_creation_time=" << rowset.creation_time();
6689
53.2k
        int64_t current_time = ::time(nullptr);
6690
53.2k
        if (current_time < expiration) { // not expired
6691
0
            return 0;
6692
0
        }
6693
53.2k
        ++num_expired;
6694
53.2k
        expired_rowset_size += v.size();
6695
53.2k
        if (!rowset.has_resource_id()) {
6696
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6697
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6698
0
                return -1;
6699
0
            }
6700
            // might be a delete pred rowset
6701
0
            tmp_rowset_keys.emplace_back(k);
6702
0
            return 0;
6703
0
        }
6704
6705
        // TODO(plat1ko): check rowset not referenced
6706
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6707
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6708
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6709
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6710
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6711
53.2k
                  << " num_expired=" << num_expired
6712
53.2k
                  << " task_type=" << metrics_context.operation_type;
6713
6714
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6715
0
            if (need_mark_rowset_as_recycled(rowset)) {
6716
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6717
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6718
0
                             "at next turn, instance_id="
6719
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6720
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6721
0
                return 0;
6722
0
            }
6723
0
        }
6724
6725
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6726
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6727
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6728
258
                             "instance_id="
6729
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6730
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6731
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6732
258
                return 0;
6733
258
            }
6734
258
        }
6735
6736
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6737
        // Remove the rowset ref count key directly since it has not been used.
6738
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6739
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6740
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6741
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6742
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6743
6744
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6745
53.0k
        return 0;
6746
53.2k
    };
6747
6748
37
    auto loop_done = [&]() -> int {
6749
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6750
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6751
24
        std::vector<std::string> mark_keys_to_process;
6752
24
        std::vector<std::string> abort_keys_to_process;
6753
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6754
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6755
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6756
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6757
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6758
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6759
24
        if (!mark_keys_to_process.empty()) {
6760
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6761
7
                    *worker_pool, std::move(mark_keys_to_process));
6762
7
        }
6763
24
        if (!abort_keys_to_process.empty()) {
6764
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6765
5
                                           &num_recycled, &metrics_context);
6766
5
        }
6767
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6768
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6769
24
                             tmp_rowset_ref_count_keys_to_delete =
6770
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6771
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6772
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6773
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6774
24
                                   metrics_context) != 0) {
6775
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6776
2
                return;
6777
2
            }
6778
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6779
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6780
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6781
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6782
0
                                 << rs.ShortDebugString();
6783
0
                    return;
6784
0
                }
6785
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6786
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6787
0
                                 << rs.ShortDebugString();
6788
0
                    return;
6789
0
                }
6790
51.0k
            }
6791
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6792
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6793
0
                return;
6794
0
            }
6795
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6796
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6797
0
                return;
6798
0
            }
6799
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6800
22
            return;
6801
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6772
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6773
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6774
12
                                   metrics_context) != 0) {
6775
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6776
0
                return;
6777
0
            }
6778
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6779
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6780
4
                                                       rs.rowset_id_v2()) != 0) {
6781
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6782
0
                                 << rs.ShortDebugString();
6783
0
                    return;
6784
0
                }
6785
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6786
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6787
0
                                 << rs.ShortDebugString();
6788
0
                    return;
6789
0
                }
6790
4
            }
6791
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6792
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6793
0
                return;
6794
0
            }
6795
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6796
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6797
0
                return;
6798
0
            }
6799
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6800
12
            return;
6801
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6772
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6773
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6774
12
                                   metrics_context) != 0) {
6775
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6776
2
                return;
6777
2
            }
6778
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6779
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6780
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6781
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6782
0
                                 << rs.ShortDebugString();
6783
0
                    return;
6784
0
                }
6785
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6786
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6787
0
                                 << rs.ShortDebugString();
6788
0
                    return;
6789
0
                }
6790
51.0k
            }
6791
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6792
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6793
0
                return;
6794
0
            }
6795
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6796
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6797
0
                return;
6798
0
            }
6799
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6800
10
            return;
6801
10
        });
6802
24
        return 0;
6803
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6748
12
    auto loop_done = [&]() -> int {
6749
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6750
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6751
12
        std::vector<std::string> mark_keys_to_process;
6752
12
        std::vector<std::string> abort_keys_to_process;
6753
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6754
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6755
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6756
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6757
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6758
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6759
12
        if (!mark_keys_to_process.empty()) {
6760
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6761
7
                    *worker_pool, std::move(mark_keys_to_process));
6762
7
        }
6763
12
        if (!abort_keys_to_process.empty()) {
6764
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6765
3
                                           &num_recycled, &metrics_context);
6766
3
        }
6767
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6768
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6769
12
                             tmp_rowset_ref_count_keys_to_delete =
6770
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6771
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6772
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6773
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6774
12
                                   metrics_context) != 0) {
6775
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6776
12
                return;
6777
12
            }
6778
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6779
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6780
12
                                                       rs.rowset_id_v2()) != 0) {
6781
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6782
12
                                 << rs.ShortDebugString();
6783
12
                    return;
6784
12
                }
6785
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6786
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6787
12
                                 << rs.ShortDebugString();
6788
12
                    return;
6789
12
                }
6790
12
            }
6791
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6792
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6793
12
                return;
6794
12
            }
6795
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6796
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6797
12
                return;
6798
12
            }
6799
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6800
12
            return;
6801
12
        });
6802
12
        return 0;
6803
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6748
12
    auto loop_done = [&]() -> int {
6749
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6750
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6751
12
        std::vector<std::string> mark_keys_to_process;
6752
12
        std::vector<std::string> abort_keys_to_process;
6753
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6754
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6755
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6756
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6757
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6758
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6759
12
        if (!mark_keys_to_process.empty()) {
6760
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6761
0
                    *worker_pool, std::move(mark_keys_to_process));
6762
0
        }
6763
12
        if (!abort_keys_to_process.empty()) {
6764
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6765
2
                                           &num_recycled, &metrics_context);
6766
2
        }
6767
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6768
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6769
12
                             tmp_rowset_ref_count_keys_to_delete =
6770
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6771
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6772
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6773
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6774
12
                                   metrics_context) != 0) {
6775
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6776
12
                return;
6777
12
            }
6778
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6779
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6780
12
                                                       rs.rowset_id_v2()) != 0) {
6781
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6782
12
                                 << rs.ShortDebugString();
6783
12
                    return;
6784
12
                }
6785
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6786
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6787
12
                                 << rs.ShortDebugString();
6788
12
                    return;
6789
12
                }
6790
12
            }
6791
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6792
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6793
12
                return;
6794
12
            }
6795
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6796
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6797
12
                return;
6798
12
            }
6799
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6800
12
            return;
6801
12
        });
6802
12
        return 0;
6803
12
    };
6804
6805
37
    if (config::enable_recycler_stats_metrics) {
6806
0
        scan_and_statistics_tmp_rowsets();
6807
0
    }
6808
    // recycle_func and loop_done for scan and recycle
6809
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6810
37
                               std::move(loop_done));
6811
6812
37
    worker_pool->stop();
6813
6814
    // Report final metrics after all concurrent tasks completed
6815
37
    segment_metrics_context_.report();
6816
37
    metrics_context.report();
6817
6818
37
    return ret;
6819
37
}
6820
6821
int InstanceRecycler::scan_and_recycle(
6822
        std::string begin, std::string_view end,
6823
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6824
352
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6825
352
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6826
352
    int ret = 0;
6827
352
    int64_t cnt = 0;
6828
352
    int get_range_retried = 0;
6829
352
    std::string err;
6830
352
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6831
352
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6832
352
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6833
352
                  << " ret=" << ret << " err=" << err;
6834
352
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6830
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6831
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6832
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6833
39
                  << " ret=" << ret << " err=" << err;
6834
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6830
313
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6831
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6832
313
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6833
313
                  << " ret=" << ret << " err=" << err;
6834
313
    };
6835
6836
352
    std::unique_ptr<RangeGetIterator> it;
6837
910
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6838
711
        if (get_range_retried > 1000) {
6839
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6840
0
            ret = -3;
6841
0
            return ret;
6842
0
        }
6843
711
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6844
711
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6845
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6846
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6847
0
                         << " get_range_retried=" << get_range_retried;
6848
0
            ++get_range_retried;
6849
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6850
0
            continue; // try again
6851
0
        }
6852
711
        if (!it->has_next()) {
6853
153
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6854
153
            break; // scan finished
6855
153
        }
6856
558
        bool begin_updated = false;
6857
558
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6858
558
                  << ") iterator->size()=" << it->size();
6859
258k
        while (it->has_next()) {
6860
258k
            ++cnt;
6861
            // recycle corresponding resources
6862
258k
            auto [k, v] = it->next();
6863
258k
            if (!it->has_next()) {
6864
558
                begin = k;
6865
558
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6866
558
            }
6867
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6868
258k
            if (recycle_func(k, v) != 0) {
6869
4.00k
                err = "recycle_func error";
6870
4.00k
                ret = -1;
6871
4.00k
            }
6872
258k
            if (next_begin_getter) {
6873
0
                std::string next_begin;
6874
0
                if (next_begin_getter(&next_begin)) {
6875
0
                    if (next_begin > k) {
6876
0
                        begin = std::move(next_begin);
6877
0
                        begin_updated = true;
6878
0
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6879
0
                                   << " after key=" << hex(k);
6880
0
                        break;
6881
0
                    }
6882
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6883
0
                            .tag("next_begin", hex(next_begin))
6884
0
                            .tag("current_key", hex(k));
6885
0
                }
6886
0
            }
6887
258k
        }
6888
558
        if (!begin_updated) {
6889
558
            begin.push_back('\x00'); // Update to next smallest key for iteration
6890
558
        } else {
6891
0
            it.reset();
6892
0
        }
6893
6894
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6895
        // if we want to continue scanning, the recycle_func should not return non-zero
6896
558
        if (loop_done && loop_done() != 0) {
6897
9
            err = "loop_done error";
6898
9
            ret = -1;
6899
9
        }
6900
558
    }
6901
352
    return ret;
6902
352
}
6903
6904
19
int InstanceRecycler::abort_timeout_txn() {
6905
19
    const std::string task_name = "abort_timeout_txn";
6906
19
    int64_t num_scanned = 0;
6907
19
    int64_t num_timeout = 0;
6908
19
    int64_t num_abort = 0;
6909
19
    int64_t num_advance = 0;
6910
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6911
6912
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6913
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6914
19
    std::string begin_txn_running_key;
6915
19
    std::string end_txn_running_key;
6916
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6917
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6918
6919
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6920
6921
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6922
19
    register_recycle_task(task_name, start_time);
6923
6924
19
    DORIS_CLOUD_DEFER {
6925
19
        unregister_recycle_task(task_name);
6926
19
        int64_t cost =
6927
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6928
19
        metrics_context.finish_report();
6929
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6930
19
                .tag("instance_id", instance_id_)
6931
19
                .tag("num_scanned", num_scanned)
6932
19
                .tag("num_timeout", num_timeout)
6933
19
                .tag("num_abort", num_abort)
6934
19
                .tag("num_advance", num_advance);
6935
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6924
3
    DORIS_CLOUD_DEFER {
6925
3
        unregister_recycle_task(task_name);
6926
3
        int64_t cost =
6927
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6928
3
        metrics_context.finish_report();
6929
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6930
3
                .tag("instance_id", instance_id_)
6931
3
                .tag("num_scanned", num_scanned)
6932
3
                .tag("num_timeout", num_timeout)
6933
3
                .tag("num_abort", num_abort)
6934
3
                .tag("num_advance", num_advance);
6935
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6924
16
    DORIS_CLOUD_DEFER {
6925
16
        unregister_recycle_task(task_name);
6926
16
        int64_t cost =
6927
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6928
16
        metrics_context.finish_report();
6929
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6930
16
                .tag("instance_id", instance_id_)
6931
16
                .tag("num_scanned", num_scanned)
6932
16
                .tag("num_timeout", num_timeout)
6933
16
                .tag("num_abort", num_abort)
6934
16
                .tag("num_advance", num_advance);
6935
16
    };
6936
6937
19
    int64_t current_time =
6938
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6939
6940
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6941
19
                                  &current_time, &metrics_context,
6942
19
                                  this](std::string_view k, std::string_view v) -> int {
6943
9
        ++num_scanned;
6944
6945
9
        std::unique_ptr<Transaction> txn;
6946
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6947
9
        if (err != TxnErrorCode::TXN_OK) {
6948
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6949
0
            return -1;
6950
0
        }
6951
9
        std::string_view k1 = k;
6952
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6953
9
        k1.remove_prefix(1); // Remove key space
6954
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6955
9
        if (decode_key(&k1, &out) != 0) {
6956
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6957
0
            return -1;
6958
0
        }
6959
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6960
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6961
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6962
        // Update txn_info
6963
9
        std::string txn_inf_key, txn_inf_val;
6964
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6965
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6966
9
        if (err != TxnErrorCode::TXN_OK) {
6967
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6968
0
            return -1;
6969
0
        }
6970
9
        TxnInfoPB txn_info;
6971
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6972
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
6976
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6977
3
            txn.reset();
6978
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6979
3
            std::shared_ptr<TxnLazyCommitTask> task =
6980
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6981
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6982
3
            if (ret.first != MetaServiceCode::OK) {
6983
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6984
0
                             << "msg=" << ret.second;
6985
0
                return -1;
6986
0
            }
6987
3
            ++num_advance;
6988
3
            return 0;
6989
6
        } else {
6990
6
            TxnRunningPB txn_running_pb;
6991
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6992
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6993
0
                return -1;
6994
0
            }
6995
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6996
4
                return 0;
6997
4
            }
6998
2
            ++num_timeout;
6999
7000
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7001
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7002
2
            txn_info.set_finish_time(current_time);
7003
2
            txn_info.set_reason("timeout");
7004
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7005
2
            txn_inf_val.clear();
7006
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7007
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7008
0
                return -1;
7009
0
            }
7010
2
            txn->put(txn_inf_key, txn_inf_val);
7011
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7012
            // Put recycle txn key
7013
2
            std::string recyc_txn_key, recyc_txn_val;
7014
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7015
2
            RecycleTxnPB recycle_txn_pb;
7016
2
            recycle_txn_pb.set_creation_time(current_time);
7017
2
            recycle_txn_pb.set_label(txn_info.label());
7018
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7019
0
                LOG_WARNING("failed to serialize txn recycle info")
7020
0
                        .tag("key", hex(k))
7021
0
                        .tag("db_id", db_id)
7022
0
                        .tag("txn_id", txn_id);
7023
0
                return -1;
7024
0
            }
7025
2
            txn->put(recyc_txn_key, recyc_txn_val);
7026
            // Remove txn running key
7027
2
            txn->remove(k);
7028
2
            err = txn->commit();
7029
2
            if (err != TxnErrorCode::TXN_OK) {
7030
0
                LOG_WARNING("failed to commit txn err={}", err)
7031
0
                        .tag("key", hex(k))
7032
0
                        .tag("db_id", db_id)
7033
0
                        .tag("txn_id", txn_id);
7034
0
                return -1;
7035
0
            }
7036
2
            metrics_context.total_recycled_num = ++num_abort;
7037
2
            metrics_context.report();
7038
2
        }
7039
7040
2
        return 0;
7041
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6942
3
                                  this](std::string_view k, std::string_view v) -> int {
6943
3
        ++num_scanned;
6944
6945
3
        std::unique_ptr<Transaction> txn;
6946
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6947
3
        if (err != TxnErrorCode::TXN_OK) {
6948
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6949
0
            return -1;
6950
0
        }
6951
3
        std::string_view k1 = k;
6952
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6953
3
        k1.remove_prefix(1); // Remove key space
6954
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6955
3
        if (decode_key(&k1, &out) != 0) {
6956
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6957
0
            return -1;
6958
0
        }
6959
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6960
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6961
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6962
        // Update txn_info
6963
3
        std::string txn_inf_key, txn_inf_val;
6964
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6965
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6966
3
        if (err != TxnErrorCode::TXN_OK) {
6967
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6968
0
            return -1;
6969
0
        }
6970
3
        TxnInfoPB txn_info;
6971
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6972
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
6976
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6977
3
            txn.reset();
6978
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6979
3
            std::shared_ptr<TxnLazyCommitTask> task =
6980
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6981
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6982
3
            if (ret.first != MetaServiceCode::OK) {
6983
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6984
0
                             << "msg=" << ret.second;
6985
0
                return -1;
6986
0
            }
6987
3
            ++num_advance;
6988
3
            return 0;
6989
3
        } else {
6990
0
            TxnRunningPB txn_running_pb;
6991
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6992
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6993
0
                return -1;
6994
0
            }
6995
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6996
0
                return 0;
6997
0
            }
6998
0
            ++num_timeout;
6999
7000
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7001
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7002
0
            txn_info.set_finish_time(current_time);
7003
0
            txn_info.set_reason("timeout");
7004
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7005
0
            txn_inf_val.clear();
7006
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7007
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7008
0
                return -1;
7009
0
            }
7010
0
            txn->put(txn_inf_key, txn_inf_val);
7011
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7012
            // Put recycle txn key
7013
0
            std::string recyc_txn_key, recyc_txn_val;
7014
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7015
0
            RecycleTxnPB recycle_txn_pb;
7016
0
            recycle_txn_pb.set_creation_time(current_time);
7017
0
            recycle_txn_pb.set_label(txn_info.label());
7018
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7019
0
                LOG_WARNING("failed to serialize txn recycle info")
7020
0
                        .tag("key", hex(k))
7021
0
                        .tag("db_id", db_id)
7022
0
                        .tag("txn_id", txn_id);
7023
0
                return -1;
7024
0
            }
7025
0
            txn->put(recyc_txn_key, recyc_txn_val);
7026
            // Remove txn running key
7027
0
            txn->remove(k);
7028
0
            err = txn->commit();
7029
0
            if (err != TxnErrorCode::TXN_OK) {
7030
0
                LOG_WARNING("failed to commit txn err={}", err)
7031
0
                        .tag("key", hex(k))
7032
0
                        .tag("db_id", db_id)
7033
0
                        .tag("txn_id", txn_id);
7034
0
                return -1;
7035
0
            }
7036
0
            metrics_context.total_recycled_num = ++num_abort;
7037
0
            metrics_context.report();
7038
0
        }
7039
7040
0
        return 0;
7041
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6942
6
                                  this](std::string_view k, std::string_view v) -> int {
6943
6
        ++num_scanned;
6944
6945
6
        std::unique_ptr<Transaction> txn;
6946
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6947
6
        if (err != TxnErrorCode::TXN_OK) {
6948
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6949
0
            return -1;
6950
0
        }
6951
6
        std::string_view k1 = k;
6952
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6953
6
        k1.remove_prefix(1); // Remove key space
6954
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6955
6
        if (decode_key(&k1, &out) != 0) {
6956
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6957
0
            return -1;
6958
0
        }
6959
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6960
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6961
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6962
        // Update txn_info
6963
6
        std::string txn_inf_key, txn_inf_val;
6964
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6965
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6966
6
        if (err != TxnErrorCode::TXN_OK) {
6967
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6968
0
            return -1;
6969
0
        }
6970
6
        TxnInfoPB txn_info;
6971
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6972
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6973
0
            return -1;
6974
0
        }
6975
6976
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6977
0
            txn.reset();
6978
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6979
0
            std::shared_ptr<TxnLazyCommitTask> task =
6980
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6981
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6982
0
            if (ret.first != MetaServiceCode::OK) {
6983
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6984
0
                             << "msg=" << ret.second;
6985
0
                return -1;
6986
0
            }
6987
0
            ++num_advance;
6988
0
            return 0;
6989
6
        } else {
6990
6
            TxnRunningPB txn_running_pb;
6991
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6992
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6993
0
                return -1;
6994
0
            }
6995
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6996
4
                return 0;
6997
4
            }
6998
2
            ++num_timeout;
6999
7000
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
7001
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
7002
2
            txn_info.set_finish_time(current_time);
7003
2
            txn_info.set_reason("timeout");
7004
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
7005
2
            txn_inf_val.clear();
7006
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
7007
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
7008
0
                return -1;
7009
0
            }
7010
2
            txn->put(txn_inf_key, txn_inf_val);
7011
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
7012
            // Put recycle txn key
7013
2
            std::string recyc_txn_key, recyc_txn_val;
7014
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
7015
2
            RecycleTxnPB recycle_txn_pb;
7016
2
            recycle_txn_pb.set_creation_time(current_time);
7017
2
            recycle_txn_pb.set_label(txn_info.label());
7018
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
7019
0
                LOG_WARNING("failed to serialize txn recycle info")
7020
0
                        .tag("key", hex(k))
7021
0
                        .tag("db_id", db_id)
7022
0
                        .tag("txn_id", txn_id);
7023
0
                return -1;
7024
0
            }
7025
2
            txn->put(recyc_txn_key, recyc_txn_val);
7026
            // Remove txn running key
7027
2
            txn->remove(k);
7028
2
            err = txn->commit();
7029
2
            if (err != TxnErrorCode::TXN_OK) {
7030
0
                LOG_WARNING("failed to commit txn err={}", err)
7031
0
                        .tag("key", hex(k))
7032
0
                        .tag("db_id", db_id)
7033
0
                        .tag("txn_id", txn_id);
7034
0
                return -1;
7035
0
            }
7036
2
            metrics_context.total_recycled_num = ++num_abort;
7037
2
            metrics_context.report();
7038
2
        }
7039
7040
2
        return 0;
7041
6
    };
7042
7043
19
    if (config::enable_recycler_stats_metrics) {
7044
0
        scan_and_statistics_abort_timeout_txn();
7045
0
    }
7046
    // recycle_func and loop_done for scan and recycle
7047
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7048
19
                            std::move(handle_txn_running_kv));
7049
19
}
7050
7051
22
int InstanceRecycler::recycle_expired_txn_label() {
7052
22
    const std::string task_name = "recycle_expired_txn_label";
7053
22
    int64_t num_scanned = 0;
7054
22
    int64_t num_expired = 0;
7055
22
    std::atomic_long num_recycled = 0;
7056
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7057
22
    int ret = 0;
7058
7059
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7060
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7061
22
    std::string begin_recycle_txn_key;
7062
22
    std::string end_recycle_txn_key;
7063
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7064
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7065
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
7066
7067
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
7068
7069
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7070
22
    register_recycle_task(task_name, start_time);
7071
22
    DORIS_CLOUD_DEFER {
7072
22
        unregister_recycle_task(task_name);
7073
22
        int64_t cost =
7074
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7075
22
        metrics_context.finish_report();
7076
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7077
22
                .tag("instance_id", instance_id_)
7078
22
                .tag("num_scanned", num_scanned)
7079
22
                .tag("num_expired", num_expired)
7080
22
                .tag("num_recycled", num_recycled);
7081
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7071
1
    DORIS_CLOUD_DEFER {
7072
1
        unregister_recycle_task(task_name);
7073
1
        int64_t cost =
7074
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7075
1
        metrics_context.finish_report();
7076
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7077
1
                .tag("instance_id", instance_id_)
7078
1
                .tag("num_scanned", num_scanned)
7079
1
                .tag("num_expired", num_expired)
7080
1
                .tag("num_recycled", num_recycled);
7081
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7071
21
    DORIS_CLOUD_DEFER {
7072
21
        unregister_recycle_task(task_name);
7073
21
        int64_t cost =
7074
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7075
21
        metrics_context.finish_report();
7076
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7077
21
                .tag("instance_id", instance_id_)
7078
21
                .tag("num_scanned", num_scanned)
7079
21
                .tag("num_expired", num_expired)
7080
21
                .tag("num_recycled", num_recycled);
7081
21
    };
7082
7083
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7084
7085
22
    SyncExecutor<int> concurrent_delete_executor(
7086
22
            _thread_pool_group.s3_producer_pool,
7087
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7088
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7088
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7088
38.0k
            [](const int& ret) { return ret != 0; });
7089
7090
22
    int64_t current_time_ms =
7091
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7092
7093
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7094
50.0k
        ++num_scanned;
7095
50.0k
        RecycleTxnPB recycle_txn_pb;
7096
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7097
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7098
0
            return -1;
7099
0
        }
7100
50.0k
        if ((config::force_immediate_recycle) ||
7101
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7102
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7103
50.0k
             current_time_ms)) {
7104
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7105
38.0k
            num_expired++;
7106
7107
38.0k
            std::string_view k1 = k;
7108
38.0k
            k1.remove_prefix(1); // Remove key space
7109
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7110
38.0k
            if (decode_key(&k1, &out) != 0) {
7111
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7112
0
                return -1;
7113
0
            }
7114
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7115
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7116
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7117
38.0k
        }
7118
50.0k
        return 0;
7119
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7093
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7094
1
        ++num_scanned;
7095
1
        RecycleTxnPB recycle_txn_pb;
7096
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7097
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7098
0
            return -1;
7099
0
        }
7100
1
        if ((config::force_immediate_recycle) ||
7101
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7102
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7103
1
             current_time_ms)) {
7104
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7105
1
            num_expired++;
7106
7107
1
            std::string_view k1 = k;
7108
1
            k1.remove_prefix(1); // Remove key space
7109
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7110
1
            if (decode_key(&k1, &out) != 0) {
7111
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7112
0
                return -1;
7113
0
            }
7114
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7115
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7116
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7117
1
        }
7118
1
        return 0;
7119
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7093
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7094
50.0k
        ++num_scanned;
7095
50.0k
        RecycleTxnPB recycle_txn_pb;
7096
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7097
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7098
0
            return -1;
7099
0
        }
7100
50.0k
        if ((config::force_immediate_recycle) ||
7101
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7102
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7103
50.0k
             current_time_ms)) {
7104
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7105
38.0k
            num_expired++;
7106
7107
38.0k
            std::string_view k1 = k;
7108
38.0k
            k1.remove_prefix(1); // Remove key space
7109
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7110
38.0k
            if (decode_key(&k1, &out) != 0) {
7111
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7112
0
                return -1;
7113
0
            }
7114
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7115
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7116
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7117
38.0k
        }
7118
50.0k
        return 0;
7119
50.0k
    };
7120
7121
    // int 0 for success, 1 for conflict, -1 for error
7122
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7123
38.0k
        std::string_view k1 = k;
7124
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7125
38.0k
        k1.remove_prefix(1); // Remove key space
7126
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7127
38.0k
        int ret = decode_key(&k1, &out);
7128
38.0k
        if (ret != 0) {
7129
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7130
0
            return -1;
7131
0
        }
7132
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7133
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7134
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7135
38.0k
        std::unique_ptr<Transaction> txn;
7136
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7137
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7138
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7139
0
            return -1;
7140
0
        }
7141
        // Remove txn index kv
7142
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7143
38.0k
        txn->remove(index_key);
7144
        // Remove txn info kv
7145
38.0k
        std::string info_key, info_val;
7146
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7147
38.0k
        err = txn->get(info_key, &info_val);
7148
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7149
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7150
0
            return -1;
7151
0
        }
7152
38.0k
        TxnInfoPB txn_info;
7153
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7154
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7155
0
            return -1;
7156
0
        }
7157
38.0k
        txn->remove(info_key);
7158
        // Remove sub txn index kvs
7159
38.0k
        std::vector<std::string> sub_txn_index_keys;
7160
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7161
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7162
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7163
38.0k
        }
7164
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7165
38.0k
            txn->remove(sub_txn_index_key);
7166
38.0k
        }
7167
        // Update txn label
7168
38.0k
        std::string label_key, label_val;
7169
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7170
38.0k
        err = txn->get(label_key, &label_val);
7171
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7172
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7173
0
                         << " err=" << err;
7174
0
            return -1;
7175
0
        }
7176
38.0k
        TxnLabelPB txn_label;
7177
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7178
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7179
0
            return -1;
7180
0
        }
7181
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7182
38.0k
        if (it != txn_label.txn_ids().end()) {
7183
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7184
38.0k
        }
7185
38.0k
        if (txn_label.txn_ids().empty()) {
7186
38.0k
            txn->remove(label_key);
7187
38.0k
            TEST_SYNC_POINT_CALLBACK(
7188
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7189
38.0k
        } else {
7190
12
            if (!txn_label.SerializeToString(&label_val)) {
7191
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7192
0
                return -1;
7193
0
            }
7194
12
            TEST_SYNC_POINT_CALLBACK(
7195
12
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7196
12
            txn->atomic_set_ver_value(label_key, label_val);
7197
12
            TEST_SYNC_POINT_CALLBACK(
7198
12
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7199
12
        }
7200
        // Remove recycle txn kv
7201
38.0k
        txn->remove(k);
7202
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7203
38.0k
        err = txn->commit();
7204
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7205
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7206
4
                TEST_SYNC_POINT_CALLBACK(
7207
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7208
                // log the txn_id and label
7209
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7210
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7211
4
                             << " txn_label=" << txn_info.label();
7212
4
                return 1;
7213
4
            }
7214
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7215
0
            return -1;
7216
4
        }
7217
38.0k
        ++num_recycled;
7218
7219
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7220
38.0k
        return 0;
7221
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7122
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7123
1
        std::string_view k1 = k;
7124
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7125
1
        k1.remove_prefix(1); // Remove key space
7126
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7127
1
        int ret = decode_key(&k1, &out);
7128
1
        if (ret != 0) {
7129
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7130
0
            return -1;
7131
0
        }
7132
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7133
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7134
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7135
1
        std::unique_ptr<Transaction> txn;
7136
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7137
1
        if (err != TxnErrorCode::TXN_OK) {
7138
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7139
0
            return -1;
7140
0
        }
7141
        // Remove txn index kv
7142
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7143
1
        txn->remove(index_key);
7144
        // Remove txn info kv
7145
1
        std::string info_key, info_val;
7146
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7147
1
        err = txn->get(info_key, &info_val);
7148
1
        if (err != TxnErrorCode::TXN_OK) {
7149
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7150
0
            return -1;
7151
0
        }
7152
1
        TxnInfoPB txn_info;
7153
1
        if (!txn_info.ParseFromString(info_val)) {
7154
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7155
0
            return -1;
7156
0
        }
7157
1
        txn->remove(info_key);
7158
        // Remove sub txn index kvs
7159
1
        std::vector<std::string> sub_txn_index_keys;
7160
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7161
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7162
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7163
0
        }
7164
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7165
0
            txn->remove(sub_txn_index_key);
7166
0
        }
7167
        // Update txn label
7168
1
        std::string label_key, label_val;
7169
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7170
1
        err = txn->get(label_key, &label_val);
7171
1
        if (err != TxnErrorCode::TXN_OK) {
7172
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7173
0
                         << " err=" << err;
7174
0
            return -1;
7175
0
        }
7176
1
        TxnLabelPB txn_label;
7177
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7178
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7179
0
            return -1;
7180
0
        }
7181
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7182
1
        if (it != txn_label.txn_ids().end()) {
7183
1
            txn_label.mutable_txn_ids()->erase(it);
7184
1
        }
7185
1
        if (txn_label.txn_ids().empty()) {
7186
1
            txn->remove(label_key);
7187
1
            TEST_SYNC_POINT_CALLBACK(
7188
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7189
1
        } else {
7190
0
            if (!txn_label.SerializeToString(&label_val)) {
7191
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7192
0
                return -1;
7193
0
            }
7194
0
            TEST_SYNC_POINT_CALLBACK(
7195
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7196
0
            txn->atomic_set_ver_value(label_key, label_val);
7197
0
            TEST_SYNC_POINT_CALLBACK(
7198
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7199
0
        }
7200
        // Remove recycle txn kv
7201
1
        txn->remove(k);
7202
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7203
1
        err = txn->commit();
7204
1
        if (err != TxnErrorCode::TXN_OK) {
7205
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7206
0
                TEST_SYNC_POINT_CALLBACK(
7207
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7208
                // log the txn_id and label
7209
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7210
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7211
0
                             << " txn_label=" << txn_info.label();
7212
0
                return 1;
7213
0
            }
7214
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7215
0
            return -1;
7216
0
        }
7217
1
        ++num_recycled;
7218
7219
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7220
1
        return 0;
7221
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7122
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7123
38.0k
        std::string_view k1 = k;
7124
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7125
38.0k
        k1.remove_prefix(1); // Remove key space
7126
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7127
38.0k
        int ret = decode_key(&k1, &out);
7128
38.0k
        if (ret != 0) {
7129
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7130
0
            return -1;
7131
0
        }
7132
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7133
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7134
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7135
38.0k
        std::unique_ptr<Transaction> txn;
7136
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7137
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7138
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7139
0
            return -1;
7140
0
        }
7141
        // Remove txn index kv
7142
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7143
38.0k
        txn->remove(index_key);
7144
        // Remove txn info kv
7145
38.0k
        std::string info_key, info_val;
7146
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7147
38.0k
        err = txn->get(info_key, &info_val);
7148
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7149
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7150
0
            return -1;
7151
0
        }
7152
38.0k
        TxnInfoPB txn_info;
7153
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7154
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7155
0
            return -1;
7156
0
        }
7157
38.0k
        txn->remove(info_key);
7158
        // Remove sub txn index kvs
7159
38.0k
        std::vector<std::string> sub_txn_index_keys;
7160
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7161
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7162
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7163
38.0k
        }
7164
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7165
38.0k
            txn->remove(sub_txn_index_key);
7166
38.0k
        }
7167
        // Update txn label
7168
38.0k
        std::string label_key, label_val;
7169
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7170
38.0k
        err = txn->get(label_key, &label_val);
7171
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7172
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7173
0
                         << " err=" << err;
7174
0
            return -1;
7175
0
        }
7176
38.0k
        TxnLabelPB txn_label;
7177
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7178
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7179
0
            return -1;
7180
0
        }
7181
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7182
38.0k
        if (it != txn_label.txn_ids().end()) {
7183
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7184
38.0k
        }
7185
38.0k
        if (txn_label.txn_ids().empty()) {
7186
38.0k
            txn->remove(label_key);
7187
38.0k
            TEST_SYNC_POINT_CALLBACK(
7188
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7189
38.0k
        } else {
7190
12
            if (!txn_label.SerializeToString(&label_val)) {
7191
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7192
0
                return -1;
7193
0
            }
7194
12
            TEST_SYNC_POINT_CALLBACK(
7195
12
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7196
12
            txn->atomic_set_ver_value(label_key, label_val);
7197
12
            TEST_SYNC_POINT_CALLBACK(
7198
12
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7199
12
        }
7200
        // Remove recycle txn kv
7201
38.0k
        txn->remove(k);
7202
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7203
38.0k
        err = txn->commit();
7204
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7205
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7206
4
                TEST_SYNC_POINT_CALLBACK(
7207
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7208
                // log the txn_id and label
7209
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7210
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7211
4
                             << " txn_label=" << txn_info.label();
7212
4
                return 1;
7213
4
            }
7214
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7215
0
            return -1;
7216
4
        }
7217
38.0k
        ++num_recycled;
7218
7219
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7220
38.0k
        return 0;
7221
38.0k
    };
7222
7223
22
    auto loop_done = [&]() -> int {
7224
15
        DORIS_CLOUD_DEFER {
7225
15
            recycle_txn_keys_by_label.clear();
7226
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7224
1
        DORIS_CLOUD_DEFER {
7225
1
            recycle_txn_keys_by_label.clear();
7226
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7224
14
        DORIS_CLOUD_DEFER {
7225
14
            recycle_txn_keys_by_label.clear();
7226
14
        };
7227
15
        TEST_SYNC_POINT_CALLBACK(
7228
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7229
15
                &recycle_txn_keys_by_label);
7230
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7231
38.0k
            int ret = delete_recycle_txn_kv(k);
7232
38.0k
            TEST_SYNC_POINT_CALLBACK(
7233
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7234
38.0k
                    &ret);
7235
38.0k
            if (ret == 1) {
7236
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7237
4
                for (int i = 1; i <= max_retry; ++i) {
7238
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7239
3
                    ret = delete_recycle_txn_kv(k);
7240
3
                    TEST_SYNC_POINT_CALLBACK(
7241
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7242
3
                            "error",
7243
3
                            &ret);
7244
3
                    if (ret != 1) {
7245
1
                        break;
7246
1
                    }
7247
                    // random sleep 0-100 ms to retry
7248
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7249
2
                }
7250
2
            }
7251
38.0k
            return ret;
7252
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7230
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7231
1
            int ret = delete_recycle_txn_kv(k);
7232
1
            TEST_SYNC_POINT_CALLBACK(
7233
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7234
1
                    &ret);
7235
1
            if (ret == 1) {
7236
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7237
0
                for (int i = 1; i <= max_retry; ++i) {
7238
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7239
0
                    ret = delete_recycle_txn_kv(k);
7240
0
                    TEST_SYNC_POINT_CALLBACK(
7241
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7242
0
                            "error",
7243
0
                            &ret);
7244
0
                    if (ret != 1) {
7245
0
                        break;
7246
0
                    }
7247
                    // random sleep 0-100 ms to retry
7248
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7249
0
                }
7250
0
            }
7251
1
            return ret;
7252
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7230
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7231
38.0k
            int ret = delete_recycle_txn_kv(k);
7232
38.0k
            TEST_SYNC_POINT_CALLBACK(
7233
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7234
38.0k
                    &ret);
7235
38.0k
            if (ret == 1) {
7236
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7237
4
                for (int i = 1; i <= max_retry; ++i) {
7238
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7239
3
                    ret = delete_recycle_txn_kv(k);
7240
3
                    TEST_SYNC_POINT_CALLBACK(
7241
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7242
3
                            "error",
7243
3
                            &ret);
7244
3
                    if (ret != 1) {
7245
1
                        break;
7246
1
                    }
7247
                    // random sleep 0-100 ms to retry
7248
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7249
2
                }
7250
2
            }
7251
38.0k
            return ret;
7252
38.0k
        };
7253
7254
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7255
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7256
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7257
0
                           << " txn_count=" << txn_keys.size();
7258
38.0k
                for (const auto& k : txn_keys) {
7259
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7260
38.0k
                    if (ret != 0) {
7261
2
                        LOG_WARNING("failed to delete recycle txn kv")
7262
2
                                .tag("instance id", instance_id_)
7263
2
                                .tag("key", hex(k))
7264
2
                                .tag("label_key", hex(label_key));
7265
2
                        return -1;
7266
2
                    }
7267
38.0k
                }
7268
38.0k
                return 0;
7269
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7255
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7256
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7257
0
                           << " txn_count=" << txn_keys.size();
7258
1
                for (const auto& k : txn_keys) {
7259
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7260
1
                    if (ret != 0) {
7261
0
                        LOG_WARNING("failed to delete recycle txn kv")
7262
0
                                .tag("instance id", instance_id_)
7263
0
                                .tag("key", hex(k))
7264
0
                                .tag("label_key", hex(label_key));
7265
0
                        return -1;
7266
0
                    }
7267
1
                }
7268
1
                return 0;
7269
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7255
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7256
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7257
0
                           << " txn_count=" << txn_keys.size();
7258
38.0k
                for (const auto& k : txn_keys) {
7259
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7260
38.0k
                    if (ret != 0) {
7261
2
                        LOG_WARNING("failed to delete recycle txn kv")
7262
2
                                .tag("instance id", instance_id_)
7263
2
                                .tag("key", hex(k))
7264
2
                                .tag("label_key", hex(label_key));
7265
2
                        return -1;
7266
2
                    }
7267
38.0k
                }
7268
38.0k
                return 0;
7269
38.0k
            });
7270
38.0k
        }
7271
15
        bool finished = true;
7272
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7273
38.0k
        for (int r : rets) {
7274
38.0k
            if (r != 0) {
7275
2
                ret = -1;
7276
2
            }
7277
38.0k
        }
7278
7279
15
        ret = finished ? ret : -1;
7280
7281
        // Update metrics after all concurrent tasks completed
7282
15
        metrics_context.total_recycled_num = num_recycled.load();
7283
15
        metrics_context.report();
7284
7285
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7286
7287
15
        if (ret != 0) {
7288
6
            LOG_WARNING("recycle txn kv ret!=0")
7289
6
                    .tag("finished", finished)
7290
6
                    .tag("ret", ret)
7291
6
                    .tag("instance_id", instance_id_);
7292
6
            return ret;
7293
6
        }
7294
9
        return ret;
7295
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7223
1
    auto loop_done = [&]() -> int {
7224
1
        DORIS_CLOUD_DEFER {
7225
1
            recycle_txn_keys_by_label.clear();
7226
1
        };
7227
1
        TEST_SYNC_POINT_CALLBACK(
7228
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7229
1
                &recycle_txn_keys_by_label);
7230
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7231
1
            int ret = delete_recycle_txn_kv(k);
7232
1
            TEST_SYNC_POINT_CALLBACK(
7233
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7234
1
                    &ret);
7235
1
            if (ret == 1) {
7236
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7237
1
                for (int i = 1; i <= max_retry; ++i) {
7238
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7239
1
                    ret = delete_recycle_txn_kv(k);
7240
1
                    TEST_SYNC_POINT_CALLBACK(
7241
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7242
1
                            "error",
7243
1
                            &ret);
7244
1
                    if (ret != 1) {
7245
1
                        break;
7246
1
                    }
7247
                    // random sleep 0-100 ms to retry
7248
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7249
1
                }
7250
1
            }
7251
1
            return ret;
7252
1
        };
7253
7254
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7255
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7256
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7257
1
                           << " txn_count=" << txn_keys.size();
7258
1
                for (const auto& k : txn_keys) {
7259
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7260
1
                    if (ret != 0) {
7261
1
                        LOG_WARNING("failed to delete recycle txn kv")
7262
1
                                .tag("instance id", instance_id_)
7263
1
                                .tag("key", hex(k))
7264
1
                                .tag("label_key", hex(label_key));
7265
1
                        return -1;
7266
1
                    }
7267
1
                }
7268
1
                return 0;
7269
1
            });
7270
1
        }
7271
1
        bool finished = true;
7272
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7273
1
        for (int r : rets) {
7274
1
            if (r != 0) {
7275
0
                ret = -1;
7276
0
            }
7277
1
        }
7278
7279
1
        ret = finished ? ret : -1;
7280
7281
        // Update metrics after all concurrent tasks completed
7282
1
        metrics_context.total_recycled_num = num_recycled.load();
7283
1
        metrics_context.report();
7284
7285
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7286
7287
1
        if (ret != 0) {
7288
0
            LOG_WARNING("recycle txn kv ret!=0")
7289
0
                    .tag("finished", finished)
7290
0
                    .tag("ret", ret)
7291
0
                    .tag("instance_id", instance_id_);
7292
0
            return ret;
7293
0
        }
7294
1
        return ret;
7295
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7223
14
    auto loop_done = [&]() -> int {
7224
14
        DORIS_CLOUD_DEFER {
7225
14
            recycle_txn_keys_by_label.clear();
7226
14
        };
7227
14
        TEST_SYNC_POINT_CALLBACK(
7228
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7229
14
                &recycle_txn_keys_by_label);
7230
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7231
14
            int ret = delete_recycle_txn_kv(k);
7232
14
            TEST_SYNC_POINT_CALLBACK(
7233
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7234
14
                    &ret);
7235
14
            if (ret == 1) {
7236
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7237
14
                for (int i = 1; i <= max_retry; ++i) {
7238
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7239
14
                    ret = delete_recycle_txn_kv(k);
7240
14
                    TEST_SYNC_POINT_CALLBACK(
7241
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7242
14
                            "error",
7243
14
                            &ret);
7244
14
                    if (ret != 1) {
7245
14
                        break;
7246
14
                    }
7247
                    // random sleep 0-100 ms to retry
7248
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7249
14
                }
7250
14
            }
7251
14
            return ret;
7252
14
        };
7253
7254
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7255
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7256
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7257
38.0k
                           << " txn_count=" << txn_keys.size();
7258
38.0k
                for (const auto& k : txn_keys) {
7259
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7260
38.0k
                    if (ret != 0) {
7261
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7262
38.0k
                                .tag("instance id", instance_id_)
7263
38.0k
                                .tag("key", hex(k))
7264
38.0k
                                .tag("label_key", hex(label_key));
7265
38.0k
                        return -1;
7266
38.0k
                    }
7267
38.0k
                }
7268
38.0k
                return 0;
7269
38.0k
            });
7270
38.0k
        }
7271
14
        bool finished = true;
7272
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7273
38.0k
        for (int r : rets) {
7274
38.0k
            if (r != 0) {
7275
2
                ret = -1;
7276
2
            }
7277
38.0k
        }
7278
7279
14
        ret = finished ? ret : -1;
7280
7281
        // Update metrics after all concurrent tasks completed
7282
14
        metrics_context.total_recycled_num = num_recycled.load();
7283
14
        metrics_context.report();
7284
7285
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7286
7287
14
        if (ret != 0) {
7288
6
            LOG_WARNING("recycle txn kv ret!=0")
7289
6
                    .tag("finished", finished)
7290
6
                    .tag("ret", ret)
7291
6
                    .tag("instance_id", instance_id_);
7292
6
            return ret;
7293
6
        }
7294
8
        return ret;
7295
14
    };
7296
7297
22
    if (config::enable_recycler_stats_metrics) {
7298
0
        scan_and_statistics_expired_txn_label();
7299
0
    }
7300
    // recycle_func and loop_done for scan and recycle
7301
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7302
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7303
22
}
7304
7305
struct CopyJobIdTuple {
7306
    std::string instance_id;
7307
    std::string stage_id;
7308
    long table_id;
7309
    std::string copy_id;
7310
    std::string stage_path;
7311
};
7312
struct BatchObjStoreAccessor {
7313
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7314
                          TxnKv* txn_kv)
7315
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7316
3
    ~BatchObjStoreAccessor() {
7317
3
        if (!paths_.empty()) {
7318
3
            consume();
7319
3
        }
7320
3
    }
7321
7322
    /**
7323
    * To implicitely do batch work and submit the batch delete task to s3
7324
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7325
    *
7326
    * @param copy_job The protubuf struct consists of the copy job files.
7327
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7328
    *            it would last until we finish the delete task, here we need pass one string value
7329
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7330
    */
7331
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7332
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7333
5
        auto& file_keys = copy_file_keys_[key];
7334
5
        file_keys.log_trace =
7335
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7336
5
                            instance_id, stage_id, table_id, copy_id, path);
7337
5
        std::string_view log_trace = file_keys.log_trace;
7338
2.03k
        for (const auto& file : copy_job.object_files()) {
7339
2.03k
            auto relative_path = file.relative_path();
7340
2.03k
            paths_.push_back(relative_path);
7341
2.03k
            file_keys.keys.push_back(copy_file_key(
7342
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7343
2.03k
            LOG_INFO(log_trace)
7344
2.03k
                    .tag("relative_path", relative_path)
7345
2.03k
                    .tag("batch_count", batch_count_);
7346
2.03k
        }
7347
5
        LOG_INFO(log_trace)
7348
5
                .tag("objects_num", copy_job.object_files().size())
7349
5
                .tag("batch_count", batch_count_);
7350
        // 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
7351
        // recommend using delete objects when objects num is less than 10)
7352
5
        if (paths_.size() < 1000) {
7353
3
            return;
7354
3
        }
7355
2
        consume();
7356
2
    }
7357
7358
private:
7359
5
    void consume() {
7360
5
        DORIS_CLOUD_DEFER {
7361
5
            paths_.clear();
7362
5
            copy_file_keys_.clear();
7363
5
            batch_count_++;
7364
7365
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7366
5
                        batch_count_);
7367
5
        };
7368
7369
5
        StopWatch sw;
7370
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7371
5
        if (0 != accessor_->delete_files(paths_)) {
7372
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7373
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7374
2
            return;
7375
2
        }
7376
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7377
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7378
        // delete fdb's keys
7379
3
        for (auto& file_keys : copy_file_keys_) {
7380
3
            auto& [log_trace, keys] = file_keys.second;
7381
3
            std::unique_ptr<Transaction> txn;
7382
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7383
0
                LOG(WARNING) << "failed to create txn";
7384
0
                continue;
7385
0
            }
7386
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7387
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7388
            // limited, should not cause the txn commit failed.
7389
1.02k
            for (const auto& key : keys) {
7390
1.02k
                txn->remove(key);
7391
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7392
1.02k
            }
7393
3
            txn->remove(file_keys.first);
7394
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7395
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7396
0
                continue;
7397
0
            }
7398
3
        }
7399
3
    }
7400
    std::shared_ptr<StorageVaultAccessor> accessor_;
7401
    // the path of the s3 files to be deleted
7402
    std::vector<std::string> paths_;
7403
    struct CopyFiles {
7404
        std::string log_trace;
7405
        std::vector<std::string> keys;
7406
    };
7407
    // pair<std::string, std::vector<std::string>>
7408
    // first: instance_id_ stage_id table_id query_id
7409
    // second: keys to be deleted
7410
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7411
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7412
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7413
    // which can together uniquely identifies different tasks for tracing log
7414
    uint64_t& batch_count_;
7415
    TxnKv* txn_kv_;
7416
};
7417
7418
13
int InstanceRecycler::recycle_copy_jobs() {
7419
13
    int64_t num_scanned = 0;
7420
13
    int64_t num_finished = 0;
7421
13
    int64_t num_expired = 0;
7422
13
    int64_t num_recycled = 0;
7423
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7424
13
    uint64_t batch_count = 0;
7425
13
    const std::string task_name = "recycle_copy_jobs";
7426
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7427
7428
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7429
7430
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7431
13
    register_recycle_task(task_name, start_time);
7432
7433
13
    DORIS_CLOUD_DEFER {
7434
13
        unregister_recycle_task(task_name);
7435
13
        int64_t cost =
7436
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7437
13
        metrics_context.finish_report();
7438
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7439
13
                .tag("instance_id", instance_id_)
7440
13
                .tag("num_scanned", num_scanned)
7441
13
                .tag("num_finished", num_finished)
7442
13
                .tag("num_expired", num_expired)
7443
13
                .tag("num_recycled", num_recycled);
7444
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7433
13
    DORIS_CLOUD_DEFER {
7434
13
        unregister_recycle_task(task_name);
7435
13
        int64_t cost =
7436
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7437
13
        metrics_context.finish_report();
7438
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7439
13
                .tag("instance_id", instance_id_)
7440
13
                .tag("num_scanned", num_scanned)
7441
13
                .tag("num_finished", num_finished)
7442
13
                .tag("num_expired", num_expired)
7443
13
                .tag("num_recycled", num_recycled);
7444
13
    };
7445
7446
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7447
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7448
13
    std::string key0;
7449
13
    std::string key1;
7450
13
    copy_job_key(key_info0, &key0);
7451
13
    copy_job_key(key_info1, &key1);
7452
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7453
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7454
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7455
16
                         this](std::string_view k, std::string_view v) -> int {
7456
16
        ++num_scanned;
7457
16
        CopyJobPB copy_job;
7458
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7459
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7460
0
            return -1;
7461
0
        }
7462
7463
        // decode copy job key
7464
16
        auto k1 = k;
7465
16
        k1.remove_prefix(1);
7466
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7467
16
        decode_key(&k1, &out);
7468
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7469
        // -> CopyJobPB
7470
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7471
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7472
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7473
7474
16
        bool check_storage = true;
7475
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7476
12
            ++num_finished;
7477
7478
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7479
7
                auto it = stage_accessor_map.find(stage_id);
7480
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7481
7
                std::string_view path;
7482
7
                if (it != stage_accessor_map.end()) {
7483
2
                    accessor = it->second;
7484
5
                } else {
7485
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7486
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7487
5
                                                      &inner_accessor);
7488
5
                    if (ret < 0) { // error
7489
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7490
0
                        return -1;
7491
5
                    } else if (ret == 0) {
7492
3
                        path = inner_accessor->uri();
7493
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7494
3
                                inner_accessor, batch_count, txn_kv_.get());
7495
3
                        stage_accessor_map.emplace(stage_id, accessor);
7496
3
                    } else { // stage not found, skip check storage
7497
2
                        check_storage = false;
7498
2
                    }
7499
5
                }
7500
7
                if (check_storage) {
7501
                    // TODO delete objects with key and etag is not supported
7502
5
                    accessor->add(std::move(copy_job), std::string(k),
7503
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7504
5
                    return 0;
7505
5
                }
7506
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7507
5
                int64_t current_time =
7508
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7509
5
                if (copy_job.finish_time_ms() > 0) {
7510
2
                    if (!config::force_immediate_recycle &&
7511
2
                        current_time < copy_job.finish_time_ms() +
7512
2
                                               config::copy_job_max_retention_second * 1000) {
7513
1
                        return 0;
7514
1
                    }
7515
3
                } else {
7516
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7517
3
                    if (!config::force_immediate_recycle &&
7518
3
                        current_time < copy_job.start_time_ms() +
7519
3
                                               config::copy_job_max_retention_second * 1000) {
7520
1
                        return 0;
7521
1
                    }
7522
3
                }
7523
5
            }
7524
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7525
4
            int64_t current_time =
7526
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7527
            // if copy job is timeout: delete all copy file kvs and copy job kv
7528
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7529
2
                return 0;
7530
2
            }
7531
2
            ++num_expired;
7532
2
        }
7533
7534
        // delete all copy files
7535
7
        std::vector<std::string> copy_file_keys;
7536
70
        for (auto& file : copy_job.object_files()) {
7537
70
            copy_file_keys.push_back(copy_file_key(
7538
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7539
70
        }
7540
7
        std::unique_ptr<Transaction> txn;
7541
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7542
0
            LOG(WARNING) << "failed to create txn";
7543
0
            return -1;
7544
0
        }
7545
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7546
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7547
        // limited, should not cause the txn commit failed.
7548
70
        for (const auto& key : copy_file_keys) {
7549
70
            txn->remove(key);
7550
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7551
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7552
70
                      << ", query_id=" << copy_id;
7553
70
        }
7554
7
        txn->remove(k);
7555
7
        TxnErrorCode err = txn->commit();
7556
7
        if (err != TxnErrorCode::TXN_OK) {
7557
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7558
0
            return -1;
7559
0
        }
7560
7561
7
        metrics_context.total_recycled_num = ++num_recycled;
7562
7
        metrics_context.report();
7563
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7564
7
        return 0;
7565
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
7455
16
                         this](std::string_view k, std::string_view v) -> int {
7456
16
        ++num_scanned;
7457
16
        CopyJobPB copy_job;
7458
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7459
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7460
0
            return -1;
7461
0
        }
7462
7463
        // decode copy job key
7464
16
        auto k1 = k;
7465
16
        k1.remove_prefix(1);
7466
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7467
16
        decode_key(&k1, &out);
7468
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7469
        // -> CopyJobPB
7470
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7471
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7472
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7473
7474
16
        bool check_storage = true;
7475
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7476
12
            ++num_finished;
7477
7478
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7479
7
                auto it = stage_accessor_map.find(stage_id);
7480
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7481
7
                std::string_view path;
7482
7
                if (it != stage_accessor_map.end()) {
7483
2
                    accessor = it->second;
7484
5
                } else {
7485
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7486
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7487
5
                                                      &inner_accessor);
7488
5
                    if (ret < 0) { // error
7489
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7490
0
                        return -1;
7491
5
                    } else if (ret == 0) {
7492
3
                        path = inner_accessor->uri();
7493
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7494
3
                                inner_accessor, batch_count, txn_kv_.get());
7495
3
                        stage_accessor_map.emplace(stage_id, accessor);
7496
3
                    } else { // stage not found, skip check storage
7497
2
                        check_storage = false;
7498
2
                    }
7499
5
                }
7500
7
                if (check_storage) {
7501
                    // TODO delete objects with key and etag is not supported
7502
5
                    accessor->add(std::move(copy_job), std::string(k),
7503
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7504
5
                    return 0;
7505
5
                }
7506
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7507
5
                int64_t current_time =
7508
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7509
5
                if (copy_job.finish_time_ms() > 0) {
7510
2
                    if (!config::force_immediate_recycle &&
7511
2
                        current_time < copy_job.finish_time_ms() +
7512
2
                                               config::copy_job_max_retention_second * 1000) {
7513
1
                        return 0;
7514
1
                    }
7515
3
                } else {
7516
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7517
3
                    if (!config::force_immediate_recycle &&
7518
3
                        current_time < copy_job.start_time_ms() +
7519
3
                                               config::copy_job_max_retention_second * 1000) {
7520
1
                        return 0;
7521
1
                    }
7522
3
                }
7523
5
            }
7524
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7525
4
            int64_t current_time =
7526
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7527
            // if copy job is timeout: delete all copy file kvs and copy job kv
7528
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7529
2
                return 0;
7530
2
            }
7531
2
            ++num_expired;
7532
2
        }
7533
7534
        // delete all copy files
7535
7
        std::vector<std::string> copy_file_keys;
7536
70
        for (auto& file : copy_job.object_files()) {
7537
70
            copy_file_keys.push_back(copy_file_key(
7538
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7539
70
        }
7540
7
        std::unique_ptr<Transaction> txn;
7541
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7542
0
            LOG(WARNING) << "failed to create txn";
7543
0
            return -1;
7544
0
        }
7545
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7546
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7547
        // limited, should not cause the txn commit failed.
7548
70
        for (const auto& key : copy_file_keys) {
7549
70
            txn->remove(key);
7550
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7551
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7552
70
                      << ", query_id=" << copy_id;
7553
70
        }
7554
7
        txn->remove(k);
7555
7
        TxnErrorCode err = txn->commit();
7556
7
        if (err != TxnErrorCode::TXN_OK) {
7557
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7558
0
            return -1;
7559
0
        }
7560
7561
7
        metrics_context.total_recycled_num = ++num_recycled;
7562
7
        metrics_context.report();
7563
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7564
7
        return 0;
7565
7
    };
7566
7567
13
    if (config::enable_recycler_stats_metrics) {
7568
0
        scan_and_statistics_copy_jobs();
7569
0
    }
7570
    // recycle_func and loop_done for scan and recycle
7571
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7572
13
}
7573
7574
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7575
                                             const StagePB::StageType& stage_type,
7576
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7577
5
#ifdef UNIT_TEST
7578
    // In unit test, external use the same accessor as the internal stage
7579
5
    auto it = accessor_map_.find(stage_id);
7580
5
    if (it != accessor_map_.end()) {
7581
3
        *accessor = it->second;
7582
3
    } else {
7583
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7584
2
        return 1;
7585
2
    }
7586
#else
7587
    // init s3 accessor and add to accessor map
7588
    auto stage_it =
7589
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7590
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7591
7592
    if (stage_it == instance_info_.stages().end()) {
7593
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7594
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7595
        return 1;
7596
    }
7597
7598
    const auto& object_store_info = stage_it->obj_info();
7599
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7600
7601
    S3Conf s3_conf;
7602
    if (stage_type == StagePB::EXTERNAL) {
7603
        if (stage_access_type == StagePB::AKSK) {
7604
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7605
            if (!conf) {
7606
                return -1;
7607
            }
7608
7609
            s3_conf = std::move(*conf);
7610
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7611
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7612
            if (!conf) {
7613
                return -1;
7614
            }
7615
7616
            s3_conf = std::move(*conf);
7617
            if (instance_info_.ram_user().has_encryption_info()) {
7618
                AkSkPair plain_ak_sk_pair;
7619
                int ret = decrypt_ak_sk_helper(
7620
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7621
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7622
                if (ret != 0) {
7623
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7624
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7625
                    return -1;
7626
                }
7627
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7628
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7629
            } else {
7630
                s3_conf.ak = instance_info_.ram_user().ak();
7631
                s3_conf.sk = instance_info_.ram_user().sk();
7632
            }
7633
        } else {
7634
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7635
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7636
            return -1;
7637
        }
7638
    } else if (stage_type == StagePB::INTERNAL) {
7639
        int idx = stoi(object_store_info.id());
7640
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7641
            LOG(WARNING) << "invalid idx: " << idx;
7642
            return -1;
7643
        }
7644
7645
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7646
        auto conf = S3Conf::from_obj_store_info(old_obj);
7647
        if (!conf) {
7648
            return -1;
7649
        }
7650
7651
        s3_conf = std::move(*conf);
7652
        s3_conf.prefix = object_store_info.prefix();
7653
    } else {
7654
        LOG(WARNING) << "unknown stage type " << stage_type;
7655
        return -1;
7656
    }
7657
7658
    std::shared_ptr<S3Accessor> s3_accessor;
7659
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7660
    if (ret != 0) {
7661
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7662
        return -1;
7663
    }
7664
7665
    *accessor = std::move(s3_accessor);
7666
#endif
7667
3
    return 0;
7668
5
}
7669
7670
11
int InstanceRecycler::recycle_stage() {
7671
11
    int64_t num_scanned = 0;
7672
11
    int64_t num_recycled = 0;
7673
11
    const std::string task_name = "recycle_stage";
7674
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7675
7676
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7677
7678
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7679
11
    register_recycle_task(task_name, start_time);
7680
7681
11
    DORIS_CLOUD_DEFER {
7682
11
        unregister_recycle_task(task_name);
7683
11
        int64_t cost =
7684
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7685
11
        metrics_context.finish_report();
7686
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7687
11
                .tag("instance_id", instance_id_)
7688
11
                .tag("num_scanned", num_scanned)
7689
11
                .tag("num_recycled", num_recycled);
7690
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7681
11
    DORIS_CLOUD_DEFER {
7682
11
        unregister_recycle_task(task_name);
7683
11
        int64_t cost =
7684
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7685
11
        metrics_context.finish_report();
7686
        LOG_WARNING("recycle stage, cost={}s", cost)
7687
11
                .tag("instance_id", instance_id_)
7688
11
                .tag("num_scanned", num_scanned)
7689
11
                .tag("num_recycled", num_recycled);
7690
11
    };
7691
7692
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7693
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7694
11
    std::string key0 = recycle_stage_key(key_info0);
7695
11
    std::string key1 = recycle_stage_key(key_info1);
7696
7697
11
    std::vector<std::string_view> stage_keys;
7698
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7699
11
                         this](std::string_view k, std::string_view v) -> int {
7700
1
        ++num_scanned;
7701
1
        RecycleStagePB recycle_stage;
7702
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7703
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7704
0
            return -1;
7705
0
        }
7706
7707
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7708
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7709
0
            LOG(WARNING) << "invalid idx: " << idx;
7710
0
            return -1;
7711
0
        }
7712
7713
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7714
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7715
1
                [&] {
7716
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7717
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7718
1
                    if (!s3_conf) {
7719
1
                        return -1;
7720
1
                    }
7721
7722
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7723
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7724
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7725
1
                    if (ret != 0) {
7726
1
                        return -1;
7727
1
                    }
7728
7729
1
                    accessor = std::move(s3_accessor);
7730
1
                    return 0;
7731
1
                }(),
7732
1
                "recycle_stage:get_accessor", &accessor);
7733
7734
1
        if (ret != 0) {
7735
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7736
0
            return ret;
7737
0
        }
7738
7739
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7740
1
                .tag("instance_id", instance_id_)
7741
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7742
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7743
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7744
1
                .tag("obj_info_id", idx)
7745
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7746
1
        ret = accessor->delete_all();
7747
1
        if (ret != 0) {
7748
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7749
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7750
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7751
0
                         << ", ret=" << ret;
7752
0
            return -1;
7753
0
        }
7754
1
        metrics_context.total_recycled_num = ++num_recycled;
7755
1
        metrics_context.report();
7756
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7757
1
        stage_keys.push_back(k);
7758
1
        return 0;
7759
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7699
1
                         this](std::string_view k, std::string_view v) -> int {
7700
1
        ++num_scanned;
7701
1
        RecycleStagePB recycle_stage;
7702
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7703
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7704
0
            return -1;
7705
0
        }
7706
7707
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7708
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7709
0
            LOG(WARNING) << "invalid idx: " << idx;
7710
0
            return -1;
7711
0
        }
7712
7713
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7714
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7715
1
                [&] {
7716
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7717
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7718
1
                    if (!s3_conf) {
7719
1
                        return -1;
7720
1
                    }
7721
7722
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7723
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7724
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7725
1
                    if (ret != 0) {
7726
1
                        return -1;
7727
1
                    }
7728
7729
1
                    accessor = std::move(s3_accessor);
7730
1
                    return 0;
7731
1
                }(),
7732
1
                "recycle_stage:get_accessor", &accessor);
7733
7734
1
        if (ret != 0) {
7735
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7736
0
            return ret;
7737
0
        }
7738
7739
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7740
1
                .tag("instance_id", instance_id_)
7741
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7742
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7743
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7744
1
                .tag("obj_info_id", idx)
7745
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7746
1
        ret = accessor->delete_all();
7747
1
        if (ret != 0) {
7748
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7749
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7750
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7751
0
                         << ", ret=" << ret;
7752
0
            return -1;
7753
0
        }
7754
1
        metrics_context.total_recycled_num = ++num_recycled;
7755
1
        metrics_context.report();
7756
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7757
1
        stage_keys.push_back(k);
7758
1
        return 0;
7759
1
    };
7760
7761
11
    auto loop_done = [&stage_keys, this]() -> int {
7762
1
        if (stage_keys.empty()) return 0;
7763
1
        DORIS_CLOUD_DEFER {
7764
1
            stage_keys.clear();
7765
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7763
1
        DORIS_CLOUD_DEFER {
7764
1
            stage_keys.clear();
7765
1
        };
7766
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7767
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7768
0
            return -1;
7769
0
        }
7770
1
        return 0;
7771
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7761
1
    auto loop_done = [&stage_keys, this]() -> int {
7762
1
        if (stage_keys.empty()) return 0;
7763
1
        DORIS_CLOUD_DEFER {
7764
1
            stage_keys.clear();
7765
1
        };
7766
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7767
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7768
0
            return -1;
7769
0
        }
7770
1
        return 0;
7771
1
    };
7772
11
    if (config::enable_recycler_stats_metrics) {
7773
0
        scan_and_statistics_stage();
7774
0
    }
7775
    // recycle_func and loop_done for scan and recycle
7776
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7777
11
}
7778
7779
10
int InstanceRecycler::recycle_expired_stage_objects() {
7780
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7781
7782
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7783
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7784
7785
10
    DORIS_CLOUD_DEFER {
7786
10
        int64_t cost =
7787
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7788
10
        metrics_context.finish_report();
7789
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7790
10
                .tag("instance_id", instance_id_);
7791
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7785
10
    DORIS_CLOUD_DEFER {
7786
10
        int64_t cost =
7787
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7788
10
        metrics_context.finish_report();
7789
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7790
10
                .tag("instance_id", instance_id_);
7791
10
    };
7792
7793
10
    int ret = 0;
7794
7795
10
    if (config::enable_recycler_stats_metrics) {
7796
0
        scan_and_statistics_expired_stage_objects();
7797
0
    }
7798
7799
10
    for (const auto& stage : instance_info_.stages()) {
7800
0
        std::stringstream ss;
7801
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7802
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7803
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7804
0
           << ", prefix=" << stage.obj_info().prefix();
7805
7806
0
        if (stopped()) {
7807
0
            break;
7808
0
        }
7809
0
        if (stage.type() == StagePB::EXTERNAL) {
7810
0
            continue;
7811
0
        }
7812
0
        int idx = stoi(stage.obj_info().id());
7813
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7814
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7815
0
            continue;
7816
0
        }
7817
7818
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7819
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7820
0
        if (!s3_conf) {
7821
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7822
0
            continue;
7823
0
        }
7824
7825
0
        s3_conf->prefix = stage.obj_info().prefix();
7826
0
        std::shared_ptr<S3Accessor> accessor;
7827
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7828
0
        if (ret1 != 0) {
7829
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7830
0
            ret = -1;
7831
0
            continue;
7832
0
        }
7833
7834
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7835
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7836
0
            ret = -1;
7837
0
            continue;
7838
0
        }
7839
7840
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7841
0
        int64_t expiration_time =
7842
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7843
0
                config::internal_stage_objects_expire_time_second;
7844
0
        if (config::force_immediate_recycle) {
7845
0
            expiration_time = INT64_MAX;
7846
0
        }
7847
0
        ret1 = accessor->delete_all(expiration_time);
7848
0
        if (ret1 != 0) {
7849
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7850
0
                         << ss.str();
7851
0
            ret = -1;
7852
0
            continue;
7853
0
        }
7854
0
        metrics_context.total_recycled_num++;
7855
0
        metrics_context.report();
7856
0
    }
7857
10
    return ret;
7858
10
}
7859
7860
247
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7861
247
    std::lock_guard lock(recycle_tasks_mutex);
7862
247
    running_recycle_tasks[task_name] = start_time;
7863
247
}
7864
7865
247
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7866
247
    std::lock_guard lock(recycle_tasks_mutex);
7867
247
    DCHECK(running_recycle_tasks[task_name] > 0);
7868
247
    running_recycle_tasks.erase(task_name);
7869
247
}
7870
7871
21
bool InstanceRecycler::check_recycle_tasks() {
7872
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7873
21
    {
7874
21
        std::lock_guard lock(recycle_tasks_mutex);
7875
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7876
21
    }
7877
7878
21
    bool found = false;
7879
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7880
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7881
20
        int64_t cost = now - start_time;
7882
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7883
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7884
20
                    .tag("instance_id", instance_id_)
7885
20
                    .tag("task", task_name);
7886
20
            found = true;
7887
20
        }
7888
20
    }
7889
7890
21
    return found;
7891
21
}
7892
7893
// Scan and statistics indexes that need to be recycled
7894
1
int InstanceRecycler::scan_and_statistics_indexes() {
7895
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7896
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7897
7898
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7899
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7900
1
    std::string index_key0;
7901
1
    std::string index_key1;
7902
1
    recycle_index_key(index_key_info0, &index_key0);
7903
1
    recycle_index_key(index_key_info1, &index_key1);
7904
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7905
7906
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7907
1
        RecycleIndexPB index_pb;
7908
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7909
0
            return 0;
7910
0
        }
7911
1
        int64_t current_time = ::time(nullptr);
7912
1
        if (current_time <
7913
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7914
0
            return 0;
7915
0
        }
7916
        // decode index_id
7917
1
        auto k1 = k;
7918
1
        k1.remove_prefix(1);
7919
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7920
1
        decode_key(&k1, &out);
7921
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7922
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7923
1
        std::unique_ptr<Transaction> txn;
7924
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7925
1
        if (err != TxnErrorCode::TXN_OK) {
7926
0
            return 0;
7927
0
        }
7928
1
        std::string val;
7929
1
        err = txn->get(k, &val);
7930
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7931
0
            return 0;
7932
0
        }
7933
1
        if (err != TxnErrorCode::TXN_OK) {
7934
0
            return 0;
7935
0
        }
7936
1
        index_pb.Clear();
7937
1
        if (!index_pb.ParseFromString(val)) {
7938
0
            return 0;
7939
0
        }
7940
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7941
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7942
0
                LOG_WARNING("table stream recycle index is missing binding")
7943
0
                        .tag("instance_id", instance_id_)
7944
0
                        .tag("stream_id", index_id);
7945
0
                return 0;
7946
0
            }
7947
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7948
2
                std::string end = prefix;
7949
2
                end.push_back('\xff');
7950
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7951
6
                                                              std::string_view value) {
7952
6
                    stream_metrics_context.total_need_recycle_num++;
7953
6
                    stream_metrics_context.total_need_recycle_data_size +=
7954
6
                            key.size() + value.size();
7955
6
                    return 0;
7956
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7951
6
                                                              std::string_view value) {
7952
6
                    stream_metrics_context.total_need_recycle_num++;
7953
6
                    stream_metrics_context.total_need_recycle_data_size +=
7954
6
                            key.size() + value.size();
7955
6
                    return 0;
7956
6
                };
7957
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7958
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7947
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7948
2
                std::string end = prefix;
7949
2
                end.push_back('\xff');
7950
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7951
2
                                                              std::string_view value) {
7952
2
                    stream_metrics_context.total_need_recycle_num++;
7953
2
                    stream_metrics_context.total_need_recycle_data_size +=
7954
2
                            key.size() + value.size();
7955
2
                    return 0;
7956
2
                };
7957
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7958
2
            };
7959
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7960
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7961
1
                    index_id);
7962
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7963
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7964
1
                    index_id);
7965
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7966
1
                scan_offset_prefix(versioned_prefix) != 0) {
7967
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7968
0
                        .tag("instance_id", instance_id_)
7969
0
                        .tag("stream_id", index_id);
7970
0
            }
7971
1
            return 0;
7972
1
        }
7973
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7974
0
            return 0;
7975
0
        }
7976
0
        metrics_context.total_need_recycle_num++;
7977
0
        return 0;
7978
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7906
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7907
1
        RecycleIndexPB index_pb;
7908
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7909
0
            return 0;
7910
0
        }
7911
1
        int64_t current_time = ::time(nullptr);
7912
1
        if (current_time <
7913
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7914
0
            return 0;
7915
0
        }
7916
        // decode index_id
7917
1
        auto k1 = k;
7918
1
        k1.remove_prefix(1);
7919
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7920
1
        decode_key(&k1, &out);
7921
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7922
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7923
1
        std::unique_ptr<Transaction> txn;
7924
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7925
1
        if (err != TxnErrorCode::TXN_OK) {
7926
0
            return 0;
7927
0
        }
7928
1
        std::string val;
7929
1
        err = txn->get(k, &val);
7930
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7931
0
            return 0;
7932
0
        }
7933
1
        if (err != TxnErrorCode::TXN_OK) {
7934
0
            return 0;
7935
0
        }
7936
1
        index_pb.Clear();
7937
1
        if (!index_pb.ParseFromString(val)) {
7938
0
            return 0;
7939
0
        }
7940
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7941
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7942
0
                LOG_WARNING("table stream recycle index is missing binding")
7943
0
                        .tag("instance_id", instance_id_)
7944
0
                        .tag("stream_id", index_id);
7945
0
                return 0;
7946
0
            }
7947
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7948
1
                std::string end = prefix;
7949
1
                end.push_back('\xff');
7950
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7951
1
                                                              std::string_view value) {
7952
1
                    stream_metrics_context.total_need_recycle_num++;
7953
1
                    stream_metrics_context.total_need_recycle_data_size +=
7954
1
                            key.size() + value.size();
7955
1
                    return 0;
7956
1
                };
7957
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7958
1
            };
7959
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7960
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7961
1
                    index_id);
7962
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7963
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7964
1
                    index_id);
7965
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7966
1
                scan_offset_prefix(versioned_prefix) != 0) {
7967
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7968
0
                        .tag("instance_id", instance_id_)
7969
0
                        .tag("stream_id", index_id);
7970
0
            }
7971
1
            return 0;
7972
1
        }
7973
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7974
0
            return 0;
7975
0
        }
7976
0
        metrics_context.total_need_recycle_num++;
7977
0
        return 0;
7978
0
    };
7979
7980
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7981
1
    metrics_context.report(true);
7982
1
    stream_metrics_context.report(true);
7983
1
    segment_metrics_context_.report(true);
7984
1
    tablet_metrics_context_.report(true);
7985
1
    return ret;
7986
1
}
7987
7988
// Scan and statistics partitions that need to be recycled
7989
0
int InstanceRecycler::scan_and_statistics_partitions() {
7990
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7991
7992
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7993
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7994
0
    std::string part_key0;
7995
0
    std::string part_key1;
7996
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7997
7998
0
    recycle_partition_key(part_key_info0, &part_key0);
7999
0
    recycle_partition_key(part_key_info1, &part_key1);
8000
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
8001
0
        RecyclePartitionPB part_pb;
8002
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
8003
0
            return 0;
8004
0
        }
8005
0
        int64_t current_time = ::time(nullptr);
8006
0
        if (current_time <
8007
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
8008
0
            return 0;
8009
0
        }
8010
        // decode partition_id
8011
0
        auto k1 = k;
8012
0
        k1.remove_prefix(1);
8013
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8014
0
        decode_key(&k1, &out);
8015
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
8016
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
8017
        // Change state to RECYCLING
8018
0
        std::unique_ptr<Transaction> txn;
8019
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8020
0
        if (err != TxnErrorCode::TXN_OK) {
8021
0
            return 0;
8022
0
        }
8023
0
        std::string val;
8024
0
        err = txn->get(k, &val);
8025
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8026
0
            return 0;
8027
0
        }
8028
0
        if (err != TxnErrorCode::TXN_OK) {
8029
0
            return 0;
8030
0
        }
8031
0
        part_pb.Clear();
8032
0
        if (!part_pb.ParseFromString(val)) {
8033
0
            return 0;
8034
0
        }
8035
        // Partitions with PREPARED state MUST have no data
8036
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
8037
0
        int ret = 0;
8038
0
        for (int64_t index_id : part_pb.index_id()) {
8039
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
8040
0
                                            partition_id, is_empty_tablet) != 0) {
8041
0
                ret = 0;
8042
0
            }
8043
0
        }
8044
0
        metrics_context.total_need_recycle_num++;
8045
0
        return ret;
8046
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_
8047
8048
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
8049
0
    metrics_context.report(true);
8050
0
    segment_metrics_context_.report(true);
8051
0
    tablet_metrics_context_.report(true);
8052
0
    return ret;
8053
0
}
8054
8055
// Scan and statistics rowsets that need to be recycled
8056
0
int InstanceRecycler::scan_and_statistics_rowsets() {
8057
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
8058
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
8059
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
8060
0
    std::string recyc_rs_key0;
8061
0
    std::string recyc_rs_key1;
8062
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
8063
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
8064
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8065
8066
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
8067
0
        RecycleRowsetPB rowset;
8068
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8069
0
            return 0;
8070
0
        }
8071
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
8072
0
        int64_t current_time = ::time(nullptr);
8073
0
        if (current_time <
8074
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
8075
0
            return 0;
8076
0
        }
8077
8078
0
        if (!rowset.has_type()) {
8079
0
            if (!rowset.has_resource_id()) [[unlikely]] {
8080
0
                return 0;
8081
0
            }
8082
0
            if (rowset.resource_id().empty()) [[unlikely]] {
8083
0
                return 0;
8084
0
            }
8085
0
            metrics_context.total_need_recycle_num++;
8086
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8087
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
8088
0
            segment_metrics_context_.total_need_recycle_data_size +=
8089
0
                    rowset.rowset_meta().total_disk_size();
8090
0
            return 0;
8091
0
        }
8092
8093
0
        if (config::enable_mark_delete_rowset_before_recycle &&
8094
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
8095
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
8096
0
            return 0;
8097
0
        }
8098
8099
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
8100
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
8101
0
                return 0;
8102
0
            }
8103
0
        }
8104
0
        metrics_context.total_need_recycle_num++;
8105
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
8106
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
8107
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8108
0
        return 0;
8109
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_
8110
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8111
0
    metrics_context.report(true);
8112
0
    segment_metrics_context_.report(true);
8113
0
    return ret;
8114
0
}
8115
8116
// Scan and statistics tmp_rowsets that need to be recycled
8117
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8118
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8119
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8120
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8121
0
    std::string tmp_rs_key0;
8122
0
    std::string tmp_rs_key1;
8123
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8124
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8125
8126
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8127
8128
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8129
0
        doris::RowsetMetaCloudPB rowset;
8130
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8131
0
            return 0;
8132
0
        }
8133
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8134
0
        int64_t current_time = ::time(nullptr);
8135
0
        if (current_time < expiration) {
8136
0
            return 0;
8137
0
        }
8138
8139
0
        DCHECK_GT(rowset.txn_id(), 0)
8140
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8141
8142
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
8143
0
            return 0;
8144
0
        }
8145
8146
0
        if (!rowset.has_resource_id()) {
8147
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8148
0
                return 0;
8149
0
            }
8150
0
            return 0;
8151
0
        }
8152
8153
0
        metrics_context.total_need_recycle_num++;
8154
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8155
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8156
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8157
0
        return 0;
8158
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_
8159
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8160
0
    metrics_context.report(true);
8161
0
    segment_metrics_context_.report(true);
8162
0
    return ret;
8163
0
}
8164
8165
// Scan and statistics abort_timeout_txn that need to be recycled
8166
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8167
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8168
8169
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8170
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8171
0
    std::string begin_txn_running_key;
8172
0
    std::string end_txn_running_key;
8173
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8174
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8175
8176
0
    int64_t current_time =
8177
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8178
8179
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8180
0
                                               std::string_view k, std::string_view v) -> int {
8181
0
        std::unique_ptr<Transaction> txn;
8182
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8183
0
        if (err != TxnErrorCode::TXN_OK) {
8184
0
            return 0;
8185
0
        }
8186
0
        std::string_view k1 = k;
8187
0
        k1.remove_prefix(1);
8188
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8189
0
        if (decode_key(&k1, &out) != 0) {
8190
0
            return 0;
8191
0
        }
8192
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8193
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8194
        // Update txn_info
8195
0
        std::string txn_inf_key, txn_inf_val;
8196
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8197
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8198
0
        if (err != TxnErrorCode::TXN_OK) {
8199
0
            return 0;
8200
0
        }
8201
0
        TxnInfoPB txn_info;
8202
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8203
0
            return 0;
8204
0
        }
8205
8206
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8207
0
            TxnRunningPB txn_running_pb;
8208
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8209
0
                return 0;
8210
0
            }
8211
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8212
0
                return 0;
8213
0
            }
8214
0
            metrics_context.total_need_recycle_num++;
8215
0
        }
8216
0
        return 0;
8217
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_
8218
8219
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
8220
0
                               std::move(handle_abort_timeout_txn_kv));
8221
0
    metrics_context.report(true);
8222
0
    return ret;
8223
0
}
8224
8225
// Scan and statistics expired_txn_label that need to be recycled
8226
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8227
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8228
8229
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8230
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8231
0
    std::string begin_recycle_txn_key;
8232
0
    std::string end_recycle_txn_key;
8233
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8234
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8235
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8236
0
    int64_t current_time_ms =
8237
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8238
8239
    // for calculate the total num or bytes of recyled objects
8240
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8241
0
        RecycleTxnPB recycle_txn_pb;
8242
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8243
0
            return 0;
8244
0
        }
8245
0
        if ((config::force_immediate_recycle) ||
8246
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8247
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8248
0
             current_time_ms)) {
8249
0
            metrics_context.total_need_recycle_num++;
8250
0
        }
8251
0
        return 0;
8252
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_
8253
8254
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
8255
0
                               std::move(handle_expired_txn_label_kv));
8256
0
    metrics_context.report(true);
8257
0
    return ret;
8258
0
}
8259
8260
// Scan and statistics copy_jobs that need to be recycled
8261
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8262
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8263
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8264
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8265
0
    std::string key0;
8266
0
    std::string key1;
8267
0
    copy_job_key(key_info0, &key0);
8268
0
    copy_job_key(key_info1, &key1);
8269
8270
    // for calculate the total num or bytes of recyled objects
8271
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8272
0
        CopyJobPB copy_job;
8273
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8274
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8275
0
            return 0;
8276
0
        }
8277
8278
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8279
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8280
0
                int64_t current_time =
8281
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8282
0
                if (copy_job.finish_time_ms() > 0) {
8283
0
                    if (!config::force_immediate_recycle &&
8284
0
                        current_time < copy_job.finish_time_ms() +
8285
0
                                               config::copy_job_max_retention_second * 1000) {
8286
0
                        return 0;
8287
0
                    }
8288
0
                } else {
8289
0
                    if (!config::force_immediate_recycle &&
8290
0
                        current_time < copy_job.start_time_ms() +
8291
0
                                               config::copy_job_max_retention_second * 1000) {
8292
0
                        return 0;
8293
0
                    }
8294
0
                }
8295
0
            }
8296
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8297
0
            int64_t current_time =
8298
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8299
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8300
0
                return 0;
8301
0
            }
8302
0
        }
8303
0
        metrics_context.total_need_recycle_num++;
8304
0
        return 0;
8305
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_
8306
8307
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8308
0
    metrics_context.report(true);
8309
0
    return ret;
8310
0
}
8311
8312
// Scan and statistics stage that need to be recycled
8313
0
int InstanceRecycler::scan_and_statistics_stage() {
8314
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8315
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8316
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8317
0
    std::string key0 = recycle_stage_key(key_info0);
8318
0
    std::string key1 = recycle_stage_key(key_info1);
8319
8320
    // for calculate the total num or bytes of recyled objects
8321
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8322
0
                                                        std::string_view v) -> int {
8323
0
        RecycleStagePB recycle_stage;
8324
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8325
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8326
0
            return 0;
8327
0
        }
8328
8329
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8330
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8331
0
            LOG(WARNING) << "invalid idx: " << idx;
8332
0
            return 0;
8333
0
        }
8334
8335
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8336
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8337
0
                [&] {
8338
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8339
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8340
0
                    if (!s3_conf) {
8341
0
                        return 0;
8342
0
                    }
8343
8344
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8345
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8346
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8347
0
                    if (ret != 0) {
8348
0
                        return 0;
8349
0
                    }
8350
8351
0
                    accessor = std::move(s3_accessor);
8352
0
                    return 0;
8353
0
                }(),
8354
0
                "recycle_stage:get_accessor", &accessor);
8355
8356
0
        if (ret != 0) {
8357
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8358
0
            return 0;
8359
0
        }
8360
8361
0
        metrics_context.total_need_recycle_num++;
8362
0
        return 0;
8363
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_
8364
8365
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8366
0
    metrics_context.report(true);
8367
0
    return ret;
8368
0
}
8369
8370
// Scan and statistics expired_stage_objects that need to be recycled
8371
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8372
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8373
8374
    // for calculate the total num or bytes of recyled objects
8375
0
    auto scan_and_statistics = [&metrics_context, this]() {
8376
0
        for (const auto& stage : instance_info_.stages()) {
8377
0
            if (stopped()) {
8378
0
                break;
8379
0
            }
8380
0
            if (stage.type() == StagePB::EXTERNAL) {
8381
0
                continue;
8382
0
            }
8383
0
            int idx = stoi(stage.obj_info().id());
8384
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8385
0
                continue;
8386
0
            }
8387
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8388
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8389
0
            if (!s3_conf) {
8390
0
                continue;
8391
0
            }
8392
0
            s3_conf->prefix = stage.obj_info().prefix();
8393
0
            std::shared_ptr<S3Accessor> accessor;
8394
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8395
0
            if (ret1 != 0) {
8396
0
                continue;
8397
0
            }
8398
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8399
0
                continue;
8400
0
            }
8401
0
            metrics_context.total_need_recycle_num++;
8402
0
        }
8403
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8404
8405
0
    scan_and_statistics();
8406
0
    metrics_context.report(true);
8407
0
    return 0;
8408
0
}
8409
8410
// Scan and statistics versions that need to be recycled
8411
0
int InstanceRecycler::scan_and_statistics_versions() {
8412
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8413
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8414
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8415
8416
0
    int64_t last_scanned_table_id = 0;
8417
0
    bool is_recycled = false; // Is last scanned kv recycled
8418
    // for calculate the total num or bytes of recyled objects
8419
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8420
0
                                       std::string_view k, std::string_view) {
8421
0
        auto k1 = k;
8422
0
        k1.remove_prefix(1);
8423
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8424
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8425
0
        decode_key(&k1, &out);
8426
0
        DCHECK_EQ(out.size(), 6) << k;
8427
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8428
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8429
0
            metrics_context.total_need_recycle_num +=
8430
0
                    is_recycled; // Version kv of this table has been recycled
8431
0
            return 0;
8432
0
        }
8433
0
        last_scanned_table_id = table_id;
8434
0
        is_recycled = false;
8435
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8436
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8437
0
        std::unique_ptr<Transaction> txn;
8438
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8439
0
        if (err != TxnErrorCode::TXN_OK) {
8440
0
            return 0;
8441
0
        }
8442
0
        std::unique_ptr<RangeGetIterator> iter;
8443
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8444
0
        if (err != TxnErrorCode::TXN_OK) {
8445
0
            return 0;
8446
0
        }
8447
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8448
0
            return 0;
8449
0
        }
8450
0
        metrics_context.total_need_recycle_num++;
8451
0
        is_recycled = true;
8452
0
        return 0;
8453
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_
8454
8455
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8456
0
    metrics_context.report(true);
8457
0
    return ret;
8458
0
}
8459
8460
// Scan and statistics restore jobs that need to be recycled
8461
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8462
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8463
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8464
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8465
0
    std::string restore_job_key0;
8466
0
    std::string restore_job_key1;
8467
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8468
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8469
8470
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8471
8472
    // for calculate the total num or bytes of recyled objects
8473
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8474
0
        RestoreJobCloudPB restore_job_pb;
8475
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8476
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8477
0
            return 0;
8478
0
        }
8479
0
        int64_t expiration =
8480
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8481
0
        int64_t current_time = ::time(nullptr);
8482
0
        if (current_time < expiration) { // not expired
8483
0
            return 0;
8484
0
        }
8485
0
        metrics_context.total_need_recycle_num++;
8486
0
        if (restore_job_pb.need_recycle_data()) {
8487
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8488
0
        }
8489
0
        return 0;
8490
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_
8491
8492
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8493
0
    metrics_context.report(true);
8494
0
    return ret;
8495
0
}
8496
8497
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8498
3
    if (!should_recycle_versioned_keys()) {
8499
0
        return;
8500
0
    }
8501
8502
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8503
8504
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8505
3
    if (recycle_checker.init() != 0) {
8506
0
        return;
8507
0
    }
8508
8509
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8510
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8511
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8512
8513
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8514
8
    for (; iter->valid(); iter->next()) {
8515
5
        OperationLogPB operation_log;
8516
5
        if (!iter->parse_value(&operation_log)) {
8517
0
            continue;
8518
0
        }
8519
8520
5
        std::string_view key = iter->key();
8521
5
        Versionstamp log_versionstamp;
8522
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8523
0
            continue;
8524
0
        }
8525
8526
5
        OperationLogReferenceInfo ref_info;
8527
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8528
5
                                        &ref_info)) {
8529
4
            metrics_context.total_need_recycle_num++;
8530
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8531
4
        }
8532
5
    }
8533
8534
3
    metrics_context.report(true);
8535
3
}
8536
8537
int InstanceRecycler::classify_rowset_task_by_ref_count(
8538
61
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8539
61
    constexpr int MAX_RETRY = 10;
8540
61
    const auto& rowset_meta = task.rowset_meta;
8541
61
    int64_t tablet_id = rowset_meta.tablet_id();
8542
61
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8543
61
    std::string_view reference_instance_id = instance_id_;
8544
61
    if (rowset_meta.has_reference_instance_id()) {
8545
5
        reference_instance_id = rowset_meta.reference_instance_id();
8546
5
    }
8547
8548
62
    for (int i = 0; i < MAX_RETRY; ++i) {
8549
62
        std::unique_ptr<Transaction> txn;
8550
62
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8551
62
        if (err != TxnErrorCode::TXN_OK) {
8552
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8553
0
                    .tag("instance_id", instance_id_)
8554
0
                    .tag("tablet_id", tablet_id)
8555
0
                    .tag("rowset_id", rowset_id)
8556
0
                    .tag("err", err);
8557
0
            return -1;
8558
0
        }
8559
8560
62
        std::string rowset_ref_count_key =
8561
62
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8562
62
        task.rowset_ref_count_key = rowset_ref_count_key;
8563
8564
62
        int64_t ref_count = 0;
8565
62
        {
8566
62
            std::string value;
8567
62
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8568
62
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8569
0
                ref_count = 1;
8570
62
            } else if (err != TxnErrorCode::TXN_OK) {
8571
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8572
0
                        .tag("instance_id", instance_id_)
8573
0
                        .tag("tablet_id", tablet_id)
8574
0
                        .tag("rowset_id", rowset_id)
8575
0
                        .tag("err", err);
8576
0
                return -1;
8577
62
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8578
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8579
0
                        .tag("instance_id", instance_id_)
8580
0
                        .tag("tablet_id", tablet_id)
8581
0
                        .tag("rowset_id", rowset_id)
8582
0
                        .tag("value", hex(value));
8583
0
                return -1;
8584
0
            }
8585
62
        }
8586
8587
62
        if (ref_count > 1) {
8588
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8589
12
            txn->atomic_add(rowset_ref_count_key, -1);
8590
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8591
12
                    .tag("instance_id", instance_id_)
8592
12
                    .tag("tablet_id", tablet_id)
8593
12
                    .tag("rowset_id", rowset_id)
8594
12
                    .tag("ref_count", ref_count - 1)
8595
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8596
8597
12
            if (!task.recycle_rowset_key.empty()) {
8598
0
                txn->remove(task.recycle_rowset_key);
8599
0
                LOG_INFO("remove recycle rowset key in classification phase")
8600
0
                        .tag("key", hex(task.recycle_rowset_key));
8601
0
            }
8602
12
            if (!task.non_versioned_rowset_key.empty()) {
8603
12
                txn->remove(task.non_versioned_rowset_key);
8604
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8605
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8606
12
            }
8607
8608
12
            err = txn->commit();
8609
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8610
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8611
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8612
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8613
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8614
1
                continue;
8615
11
            } else if (err != TxnErrorCode::TXN_OK) {
8616
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8617
0
                        .tag("instance_id", instance_id_)
8618
0
                        .tag("tablet_id", tablet_id)
8619
0
                        .tag("rowset_id", rowset_id)
8620
0
                        .tag("err", err);
8621
0
                return -1;
8622
0
            }
8623
11
            return 1; // handled, not added to batch delete
8624
50
        } else {
8625
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8626
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8627
50
            LOG_INFO("add rowset to batch delete plan")
8628
50
                    .tag("instance_id", instance_id_)
8629
50
                    .tag("tablet_id", tablet_id)
8630
50
                    .tag("rowset_id", rowset_id)
8631
50
                    .tag("resource_id", rowset_meta.resource_id())
8632
50
                    .tag("ref_count", ref_count);
8633
8634
50
            batch_delete_tasks.push_back(std::move(task));
8635
50
            return 0; // added to batch delete
8636
50
        }
8637
62
    }
8638
8639
0
    LOG_WARNING("failed to classify rowset task after retry")
8640
0
            .tag("instance_id", instance_id_)
8641
0
            .tag("tablet_id", tablet_id)
8642
0
            .tag("rowset_id", rowset_id)
8643
0
            .tag("retry", MAX_RETRY);
8644
0
    return -1;
8645
61
}
8646
8647
11
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8648
11
    int ret = 0;
8649
50
    for (const auto& task : tasks) {
8650
50
        int64_t tablet_id = task.rowset_meta.tablet_id();
8651
50
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8652
8653
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8654
        // so we don't need to call it again here.
8655
8656
        // Remove all metadata keys in one transaction
8657
50
        std::unique_ptr<Transaction> txn;
8658
50
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8659
50
        if (err != TxnErrorCode::TXN_OK) {
8660
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8661
0
                    .tag("instance_id", instance_id_)
8662
0
                    .tag("tablet_id", tablet_id)
8663
0
                    .tag("rowset_id", rowset_id)
8664
0
                    .tag("err", err);
8665
0
            ret = -1;
8666
0
            continue;
8667
0
        }
8668
8669
50
        std::string_view reference_instance_id = instance_id_;
8670
50
        if (task.rowset_meta.has_reference_instance_id()) {
8671
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8672
0
        }
8673
8674
50
        txn->remove(task.rowset_ref_count_key);
8675
50
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8676
50
                .tag("instance_id", instance_id_)
8677
50
                .tag("tablet_id", tablet_id)
8678
50
                .tag("rowset_id", rowset_id)
8679
50
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8680
8681
50
        std::string dbm_start_key =
8682
50
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8683
50
        std::string dbm_end_key = meta_delete_bitmap_key(
8684
50
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8685
50
                 std::numeric_limits<int64_t>::max()});
8686
50
        txn->remove(dbm_start_key, dbm_end_key);
8687
50
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8688
50
                .tag("instance_id", instance_id_)
8689
50
                .tag("tablet_id", tablet_id)
8690
50
                .tag("rowset_id", rowset_id)
8691
50
                .tag("begin", hex(dbm_start_key))
8692
50
                .tag("end", hex(dbm_end_key));
8693
8694
50
        std::string versioned_dbm_start_key =
8695
50
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8696
50
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8697
50
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8698
50
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8699
50
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8700
50
                .tag("instance_id", instance_id_)
8701
50
                .tag("tablet_id", tablet_id)
8702
50
                .tag("rowset_id", rowset_id)
8703
50
                .tag("begin", hex(versioned_dbm_start_key))
8704
50
                .tag("end", hex(versioned_dbm_end_key));
8705
8706
        // Remove versioned meta rowset key
8707
50
        if (!task.versioned_rowset_key.empty()) {
8708
50
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8709
50
                                                          task.versionstamp);
8710
50
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8711
50
                    .tag("instance_id", instance_id_)
8712
50
                    .tag("tablet_id", tablet_id)
8713
50
                    .tag("rowset_id", rowset_id)
8714
50
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8715
50
        }
8716
8717
50
        if (!task.non_versioned_rowset_key.empty()) {
8718
50
            txn->remove(task.non_versioned_rowset_key);
8719
50
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8720
50
                    .tag("instance_id", instance_id_)
8721
50
                    .tag("tablet_id", tablet_id)
8722
50
                    .tag("rowset_id", rowset_id)
8723
50
                    .tag("key", hex(task.non_versioned_rowset_key));
8724
50
        }
8725
8726
        // Remove recycle_rowset_key last to ensure retry safety:
8727
        // if cleanup fails, this key remains and triggers next round retry.
8728
50
        if (!task.recycle_rowset_key.empty()) {
8729
0
            txn->remove(task.recycle_rowset_key);
8730
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8731
0
                    .tag("instance_id", instance_id_)
8732
0
                    .tag("tablet_id", tablet_id)
8733
0
                    .tag("rowset_id", rowset_id)
8734
0
                    .tag("key", hex(task.recycle_rowset_key));
8735
0
        }
8736
8737
50
        err = txn->commit();
8738
50
        if (err != TxnErrorCode::TXN_OK) {
8739
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8740
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8741
0
                    .tag("instance_id", instance_id_)
8742
0
                    .tag("tablet_id", tablet_id)
8743
0
                    .tag("rowset_id", rowset_id)
8744
0
                    .tag("err", err);
8745
0
            ret = -1;
8746
0
            continue;
8747
0
        }
8748
8749
50
        LOG_INFO("cleanup rowset metadata success")
8750
50
                .tag("instance_id", instance_id_)
8751
50
                .tag("tablet_id", tablet_id)
8752
50
                .tag("rowset_id", rowset_id);
8753
50
    }
8754
11
    return ret;
8755
11
}
8756
8757
} // namespace doris::cloud