Coverage Report

Created: 2026-10-15 11:08

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
18
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
18
    std::unique_ptr<Transaction> txn;
133
18
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
18
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
18
    switch (txn->get(key, &val, true)) {
138
8
    case TxnErrorCode::TXN_OK:
139
8
        return 0;
140
10
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
10
        return 1;
142
0
    default:
143
0
        return -1;
144
18
    };
145
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
10
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
10
    std::unique_ptr<Transaction> txn;
133
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
10
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
10
    switch (txn->get(key, &val, true)) {
138
3
    case TxnErrorCode::TXN_OK:
139
3
        return 0;
140
7
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
7
        return 1;
142
0
    default:
143
0
        return -1;
144
10
    };
145
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
8
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
8
    std::unique_ptr<Transaction> txn;
133
8
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
8
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
8
    switch (txn->get(key, &val, true)) {
138
5
    case TxnErrorCode::TXN_OK:
139
5
        return 0;
140
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
3
        return 1;
142
0
    default:
143
0
        return -1;
144
8
    };
145
0
}
146
147
// 0 for success, negative for error
148
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
149
726
                   std::unique_ptr<RangeGetIterator>& it) {
150
726
    std::unique_ptr<Transaction> txn;
151
726
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
726
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
726
    switch (txn->get(begin, end, &it, true)) {
156
726
    case TxnErrorCode::TXN_OK:
157
726
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
726
    };
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
687
                   std::unique_ptr<RangeGetIterator>& it) {
150
687
    std::unique_ptr<Transaction> txn;
151
687
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
687
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
687
    switch (txn->get(begin, end, &it, true)) {
156
687
    case TxnErrorCode::TXN_OK:
157
687
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
687
    };
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
53
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
53
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
52
    size_t idx = 0;
239
105
    while (idx < rowset_dbm_key_groups.size()) {
240
53
        std::unique_ptr<Transaction> txn;
241
53
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
53
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
53
        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
53
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
53
        err = txn->commit();
267
53
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
53
    }
272
52
    return 0;
273
52
}
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
53
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
53
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
52
    size_t idx = 0;
239
105
    while (idx < rowset_dbm_key_groups.size()) {
240
53
        std::unique_ptr<Transaction> txn;
241
53
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
53
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
53
        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
53
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
53
        err = txn->commit();
267
53
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
53
    }
272
52
    return 0;
273
52
}
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
682
    while (!stopped()) {
331
677
        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
674
        } else {
354
674
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
355
674
        }
356
677
        {
357
677
            std::unique_lock lock(mtx_);
358
677
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
359
1.35k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
359
1.35k
                               [&]() { return stopped(); });
360
677
        }
361
677
    }
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
188
            : 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.50k
            LOG(WARNING) << "failed to get schema, err=" << err;
613
5.50k
            return static_cast<int>(err);
614
5.50k
        }
615
4.93k
        doris::TabletSchemaCloudPB schema;
616
4.93k
        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.93k
        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.93k
        insert(index_id, schema_version, res);
634
4.93k
        return 0;
635
4.93k
    }
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
188
        : txn_kv_(std::move(txn_kv)),
674
188
          instance_id_(instance.instance_id()),
675
188
          instance_info_(instance),
676
188
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
677
188
          _thread_pool_group(std::move(thread_pool_group)),
678
188
          txn_lazy_committer_(std::move(txn_lazy_committer)),
679
188
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
680
188
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
681
188
    delete_bitmap_lock_white_list_->init();
682
188
    resource_mgr_->init();
683
684
188
    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
188
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
689
188
};
690
691
188
InstanceRecycler::~InstanceRecycler() = default;
692
693
154
int InstanceRecycler::init_obj_store_accessors() {
694
154
    for (const auto& obj_info : instance_info_.obj_info()) {
695
106
#ifdef UNIT_TEST
696
106
        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
106
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
713
106
    }
714
715
154
    return 0;
716
154
}
717
718
154
int InstanceRecycler::init_storage_vault_accessors() {
719
154
    if (instance_info_.resource_ids().empty()) {
720
147
        return 0;
721
147
    }
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
155
int InstanceRecycler::init() {
815
155
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
816
155
        (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
154
    int ret = init_obj_store_accessors();
822
154
    if (ret != 0) {
823
0
        return ret;
824
0
    }
825
826
154
    return init_storage_vault_accessors();
827
154
}
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.50k
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1416
7.48k
            return {hint, it->second};
1417
7.48k
        }
1418
7.50k
    }
1419
1420
11
    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.98k
    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.98k
    req.set_txn_id(owner_txn_id);
2088
9.98k
    req.set_db_id(db_id);
2089
2090
9.98k
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2091
9.98k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2092
9.98k
                 << " txn_info=" << txn_info.ShortDebugString();
2093
2094
9.98k
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2095
9.98k
    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.98k
    err = txn->commit();
2103
9.98k
    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.98k
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2111
9.98k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2112
9.98k
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2113
9.98k
                 << " msg=" << msg;
2114
2115
9.98k
    return 0;
2116
9.98k
}
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.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
19.8k
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
19.8k
}
_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
19.9k
    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
19.9k
}
_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.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
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
4
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
4
                                                     abort_task.job_id);
2541
4
        }
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
10.2k
        } 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
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.60k
        LOG_WARNING("instance has no such resource id")
3915
1.60k
                .tag("instance_id", instance_id_)
3916
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3917
1.60k
        return -1;
3918
1.60k
    }
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
    // Process delete bitmap - check where it's stored.
3943
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3944
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3945
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3946
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3947
0
                .tag("instance_id", instance_id_)
3948
0
                .tag("tablet_id", tablet_id)
3949
0
                .tag("rowset_id", rowset_id);
3950
0
        return -1;
3951
0
    }
3952
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3953
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3954
2.00k
    }
3955
    // TODO(AlexYue): seems could do do batch
3956
4.01k
    return accessor->delete_files(file_paths);
3957
4.01k
}
3958
3959
102k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3960
102k
    LOG_INFO("begin process_packed_file_location_index")
3961
102k
            .tag("instance_id", instance_id_)
3962
102k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3963
102k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3964
102k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3965
102k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3966
102k
    if (index_map.empty()) {
3967
87.5k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3968
87.5k
                .tag("instance_id", instance_id_)
3969
87.5k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3970
87.5k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3971
87.5k
        return 0;
3972
87.5k
    }
3973
3974
15.0k
    struct PackedSmallFileInfo {
3975
15.0k
        std::string small_file_path;
3976
15.0k
    };
3977
15.0k
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3978
15.0k
    packed_file_updates.reserve(index_map.size());
3979
29.9k
    for (const auto& [small_path, index_pb] : index_map) {
3980
29.9k
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3981
0
            continue;
3982
0
        }
3983
29.9k
        packed_file_updates[index_pb.packed_file_path()].push_back(
3984
29.9k
                PackedSmallFileInfo {small_path});
3985
29.9k
    }
3986
15.0k
    if (packed_file_updates.empty()) {
3987
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3988
0
                .tag("instance_id", instance_id_)
3989
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3990
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3991
0
                .tag("index_map_size", index_map.size());
3992
0
        return 0;
3993
0
    }
3994
3995
15.0k
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3996
15.0k
    int ret = 0;
3997
15.0k
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3998
15.0k
        if (small_files.empty()) {
3999
0
            continue;
4000
0
        }
4001
4002
15.0k
        bool success = false;
4003
15.0k
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4004
14.9k
            std::unique_ptr<Transaction> txn;
4005
14.9k
            TxnErrorCode err = txn_kv_->create_txn(&txn);
4006
14.9k
            if (err != TxnErrorCode::TXN_OK) {
4007
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
4008
0
                        .tag("instance_id", instance_id_)
4009
0
                        .tag("packed_file_path", packed_file_path)
4010
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4011
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4012
0
                        .tag("err", err);
4013
0
                ret = -1;
4014
0
                break;
4015
0
            }
4016
4017
14.9k
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4018
14.9k
            std::string packed_val;
4019
14.9k
            err = txn->get(packed_key, &packed_val);
4020
14.9k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4021
0
                LOG_WARNING("packed file info not found when recycling rowset")
4022
0
                        .tag("instance_id", instance_id_)
4023
0
                        .tag("packed_file_path", packed_file_path)
4024
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4025
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4026
0
                        .tag("key", hex(packed_key))
4027
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
4028
                // Skip this packed file entry and continue with others
4029
0
                success = true;
4030
0
                break;
4031
0
            }
4032
14.9k
            if (err != TxnErrorCode::TXN_OK) {
4033
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
4034
0
                        .tag("instance_id", instance_id_)
4035
0
                        .tag("packed_file_path", packed_file_path)
4036
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4037
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4038
0
                        .tag("err", err);
4039
0
                ret = -1;
4040
0
                break;
4041
0
            }
4042
4043
14.9k
            cloud::PackedFileInfoPB packed_info;
4044
14.9k
            if (!packed_info.ParseFromString(packed_val)) {
4045
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
4046
0
                        .tag("instance_id", instance_id_)
4047
0
                        .tag("packed_file_path", packed_file_path)
4048
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4049
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4050
0
                ret = -1;
4051
0
                break;
4052
0
            }
4053
4054
14.9k
            LOG_INFO("packed file update check")
4055
14.9k
                    .tag("instance_id", instance_id_)
4056
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4057
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4058
14.9k
                    .tag("merged_file_path", packed_file_path)
4059
14.9k
                    .tag("requested_small_files", small_files.size())
4060
14.9k
                    .tag("merge_entries", packed_info.slices_size());
4061
4062
14.9k
            auto* small_file_entries = packed_info.mutable_slices();
4063
14.9k
            int64_t changed_files = 0;
4064
14.9k
            int64_t missing_entries = 0;
4065
14.9k
            int64_t already_deleted = 0;
4066
29.9k
            for (const auto& small_file_info : small_files) {
4067
29.9k
                bool found = false;
4068
74.8k
                for (auto& small_file_entry : *small_file_entries) {
4069
74.8k
                    if (small_file_entry.path() == small_file_info.small_file_path) {
4070
29.9k
                        if (!small_file_entry.deleted()) {
4071
29.9k
                            small_file_entry.set_deleted(true);
4072
29.9k
                            if (!small_file_entry.corrected()) {
4073
29.9k
                                small_file_entry.set_corrected(true);
4074
29.9k
                            }
4075
29.9k
                            ++changed_files;
4076
29.9k
                        } else {
4077
11
                            ++already_deleted;
4078
11
                        }
4079
29.9k
                        found = true;
4080
29.9k
                        break;
4081
29.9k
                    }
4082
74.8k
                }
4083
29.9k
                if (!found) {
4084
0
                    ++missing_entries;
4085
0
                    LOG_WARNING("packed file info missing small file entry")
4086
0
                            .tag("instance_id", instance_id_)
4087
0
                            .tag("packed_file_path", packed_file_path)
4088
0
                            .tag("small_file_path", small_file_info.small_file_path)
4089
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4090
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4091
0
                }
4092
29.9k
            }
4093
4094
14.9k
            if (changed_files == 0) {
4095
0
                LOG_INFO("skip merge file update: no merge entries changed")
4096
0
                        .tag("instance_id", instance_id_)
4097
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4098
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4099
0
                        .tag("merged_file_path", packed_file_path)
4100
0
                        .tag("missing_entries", missing_entries)
4101
0
                        .tag("already_deleted", already_deleted)
4102
0
                        .tag("requested_small_files", small_files.size())
4103
0
                        .tag("merge_entries", packed_info.slices_size());
4104
0
                success = true;
4105
0
                break;
4106
0
            }
4107
4108
            // Calculate remaining files
4109
14.9k
            int64_t left_file_count = 0;
4110
14.9k
            int64_t left_file_bytes = 0;
4111
60.0k
            for (const auto& small_file_entry : packed_info.slices()) {
4112
60.0k
                if (!small_file_entry.deleted()) {
4113
15.0k
                    ++left_file_count;
4114
15.0k
                    left_file_bytes += small_file_entry.size();
4115
15.0k
                }
4116
60.0k
            }
4117
14.9k
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4118
14.9k
            packed_info.set_ref_cnt(left_file_count);
4119
14.9k
            LOG_INFO("updated packed file reference info")
4120
14.9k
                    .tag("instance_id", instance_id_)
4121
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4122
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4123
14.9k
                    .tag("packed_file_path", packed_file_path)
4124
14.9k
                    .tag("ref_cnt", left_file_count)
4125
14.9k
                    .tag("left_file_bytes", left_file_bytes);
4126
4127
14.9k
            if (left_file_count == 0) {
4128
7.50k
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4129
7.50k
            }
4130
4131
14.9k
            std::string updated_val;
4132
14.9k
            if (!packed_info.SerializeToString(&updated_val)) {
4133
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4134
0
                        .tag("instance_id", instance_id_)
4135
0
                        .tag("packed_file_path", packed_file_path)
4136
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4137
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4138
0
                ret = -1;
4139
0
                break;
4140
0
            }
4141
4142
14.9k
            txn->put(packed_key, updated_val);
4143
14.9k
            err = txn->commit();
4144
15.0k
            if (err == TxnErrorCode::TXN_OK) {
4145
15.0k
                success = true;
4146
15.0k
                if (left_file_count == 0) {
4147
7.50k
                    LOG_INFO("packed file ready to delete, deleting immediately")
4148
7.50k
                            .tag("instance_id", instance_id_)
4149
7.50k
                            .tag("packed_file_path", packed_file_path);
4150
7.50k
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4151
0
                        ret = -1;
4152
0
                    }
4153
7.50k
                }
4154
15.0k
                break;
4155
15.0k
            }
4156
18.4E
            if (err == TxnErrorCode::TXN_CONFLICT) {
4157
0
                if (attempt >= max_retry_times) {
4158
0
                    LOG_WARNING("packed file info update conflict after max retry")
4159
0
                            .tag("instance_id", instance_id_)
4160
0
                            .tag("packed_file_path", packed_file_path)
4161
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4162
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4163
0
                            .tag("changed_files", changed_files)
4164
0
                            .tag("attempt", attempt);
4165
0
                    ret = -1;
4166
0
                    break;
4167
0
                }
4168
0
                LOG_WARNING("packed file info update conflict, retrying")
4169
0
                        .tag("instance_id", instance_id_)
4170
0
                        .tag("packed_file_path", packed_file_path)
4171
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4172
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4173
0
                        .tag("changed_files", changed_files)
4174
0
                        .tag("attempt", attempt);
4175
0
                sleep_for_packed_file_retry();
4176
0
                continue;
4177
0
            }
4178
4179
18.4E
            LOG_WARNING("failed to commit packed file info update")
4180
18.4E
                    .tag("instance_id", instance_id_)
4181
18.4E
                    .tag("packed_file_path", packed_file_path)
4182
18.4E
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4183
18.4E
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4184
18.4E
                    .tag("err", err)
4185
18.4E
                    .tag("changed_files", changed_files);
4186
18.4E
            ret = -1;
4187
18.4E
            break;
4188
18.4E
        }
4189
4190
15.0k
        if (!success) {
4191
0
            ret = -1;
4192
0
        }
4193
15.0k
    }
4194
4195
15.0k
    return ret;
4196
15.0k
}
4197
4198
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4199
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
4200
100k
        std::vector<std::string>* keys) {
4201
100k
    if (out_storage_type) {
4202
98.3k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4203
98.3k
    }
4204
4205
    // Get delete bitmap storage info from FDB
4206
100k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4207
100k
    std::unique_ptr<Transaction> txn;
4208
100k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4209
100k
    if (err != TxnErrorCode::TXN_OK) {
4210
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4211
0
                .tag("instance_id", instance_id_)
4212
0
                .tag("tablet_id", tablet_id)
4213
0
                .tag("rowset_id", rowset_id)
4214
0
                .tag("err", err);
4215
0
        return -1;
4216
0
    }
4217
4218
100k
    ValueBuf dbm_val;
4219
100k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4220
100k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4221
        // No delete bitmap for this rowset, nothing to do
4222
36.1k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4223
36.1k
                .tag("instance_id", instance_id_)
4224
36.1k
                .tag("tablet_id", tablet_id)
4225
36.1k
                .tag("rowset_id", rowset_id);
4226
36.1k
        return 0;
4227
36.1k
    }
4228
64.6k
    if (err != TxnErrorCode::TXN_OK) {
4229
0
        LOG_WARNING("failed to get delete bitmap storage")
4230
0
                .tag("instance_id", instance_id_)
4231
0
                .tag("tablet_id", tablet_id)
4232
0
                .tag("rowset_id", rowset_id)
4233
0
                .tag("err", err);
4234
0
        return -1;
4235
0
    }
4236
4237
64.6k
    if (keys) {
4238
11.5k
        for (auto& key : dbm_val.keys()) {
4239
11.5k
            keys->push_back(std::move(key));
4240
11.5k
        }
4241
11.5k
    }
4242
4243
64.6k
    DeleteBitmapStoragePB storage;
4244
64.6k
    if (!dbm_val.to_pb(&storage)) {
4245
0
        LOG_WARNING("failed to parse delete bitmap storage")
4246
0
                .tag("instance_id", instance_id_)
4247
0
                .tag("tablet_id", tablet_id)
4248
0
                .tag("rowset_id", rowset_id);
4249
0
        return -1;
4250
0
    }
4251
4252
64.6k
    if (storage.store_in_fdb()) {
4253
1
        if (out_storage_type) {
4254
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4255
1
        }
4256
1
        return 0;
4257
1
    }
4258
4259
    // Check if delete bitmap is stored in standalone file.
4260
64.6k
    if (!storage.has_packed_slice_location() ||
4261
64.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4262
64.8k
        if (out_storage_type) {
4263
63.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4264
63.5k
        }
4265
64.8k
        return 0;
4266
64.8k
    }
4267
4268
18.4E
    if (out_storage_type) {
4269
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4270
0
    }
4271
4272
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4273
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4274
4275
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4276
18.4E
            .tag("instance_id", instance_id_)
4277
18.4E
            .tag("tablet_id", tablet_id)
4278
18.4E
            .tag("rowset_id", rowset_id)
4279
18.4E
            .tag("packed_file_path", packed_file_path);
4280
4281
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4282
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4283
1
        std::unique_ptr<Transaction> update_txn;
4284
1
        err = txn_kv_->create_txn(&update_txn);
4285
1
        if (err != TxnErrorCode::TXN_OK) {
4286
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4287
0
                    .tag("instance_id", instance_id_)
4288
0
                    .tag("tablet_id", tablet_id)
4289
0
                    .tag("rowset_id", rowset_id)
4290
0
                    .tag("err", err);
4291
0
            return -1;
4292
0
        }
4293
4294
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4295
1
        std::string packed_val;
4296
1
        err = update_txn->get(packed_key, &packed_val);
4297
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4298
0
            LOG_WARNING("packed file info not found for delete bitmap")
4299
0
                    .tag("instance_id", instance_id_)
4300
0
                    .tag("tablet_id", tablet_id)
4301
0
                    .tag("rowset_id", rowset_id)
4302
0
                    .tag("packed_file_path", packed_file_path);
4303
0
            return 0;
4304
0
        }
4305
1
        if (err != TxnErrorCode::TXN_OK) {
4306
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4307
0
                    .tag("instance_id", instance_id_)
4308
0
                    .tag("tablet_id", tablet_id)
4309
0
                    .tag("rowset_id", rowset_id)
4310
0
                    .tag("packed_file_path", packed_file_path)
4311
0
                    .tag("err", err);
4312
0
            return -1;
4313
0
        }
4314
4315
1
        cloud::PackedFileInfoPB packed_info;
4316
1
        if (!packed_info.ParseFromString(packed_val)) {
4317
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4318
0
                    .tag("instance_id", instance_id_)
4319
0
                    .tag("tablet_id", tablet_id)
4320
0
                    .tag("rowset_id", rowset_id)
4321
0
                    .tag("packed_file_path", packed_file_path);
4322
0
            return -1;
4323
0
        }
4324
4325
        // Find and mark the small file entry as deleted
4326
        // Use tablet_id and rowset_id to match entry instead of path,
4327
        // because path format may vary with path_version (with or without shard prefix)
4328
1
        auto* entries = packed_info.mutable_slices();
4329
1
        bool found = false;
4330
1
        bool already_deleted = false;
4331
1
        for (auto& entry : *entries) {
4332
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4333
1
                if (!entry.deleted()) {
4334
1
                    entry.set_deleted(true);
4335
1
                    if (!entry.corrected()) {
4336
1
                        entry.set_corrected(true);
4337
1
                    }
4338
1
                } else {
4339
0
                    already_deleted = true;
4340
0
                }
4341
1
                found = true;
4342
1
                break;
4343
1
            }
4344
1
        }
4345
4346
1
        if (!found) {
4347
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4348
0
                    .tag("instance_id", instance_id_)
4349
0
                    .tag("tablet_id", tablet_id)
4350
0
                    .tag("rowset_id", rowset_id)
4351
0
                    .tag("packed_file_path", packed_file_path);
4352
0
            return 0;
4353
0
        }
4354
4355
1
        if (already_deleted) {
4356
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4357
0
                    .tag("instance_id", instance_id_)
4358
0
                    .tag("tablet_id", tablet_id)
4359
0
                    .tag("rowset_id", rowset_id)
4360
0
                    .tag("packed_file_path", packed_file_path);
4361
0
            return 0;
4362
0
        }
4363
4364
        // Calculate remaining files
4365
1
        int64_t left_file_count = 0;
4366
1
        int64_t left_file_bytes = 0;
4367
1
        for (const auto& entry : packed_info.slices()) {
4368
1
            if (!entry.deleted()) {
4369
0
                ++left_file_count;
4370
0
                left_file_bytes += entry.size();
4371
0
            }
4372
1
        }
4373
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4374
1
        packed_info.set_ref_cnt(left_file_count);
4375
4376
1
        if (left_file_count == 0) {
4377
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4378
1
        }
4379
4380
1
        std::string updated_val;
4381
1
        if (!packed_info.SerializeToString(&updated_val)) {
4382
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4383
0
                    .tag("instance_id", instance_id_)
4384
0
                    .tag("tablet_id", tablet_id)
4385
0
                    .tag("rowset_id", rowset_id)
4386
0
                    .tag("packed_file_path", packed_file_path);
4387
0
            return -1;
4388
0
        }
4389
4390
1
        update_txn->put(packed_key, updated_val);
4391
1
        err = update_txn->commit();
4392
1
        if (err == TxnErrorCode::TXN_OK) {
4393
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4394
1
                    .tag("instance_id", instance_id_)
4395
1
                    .tag("tablet_id", tablet_id)
4396
1
                    .tag("rowset_id", rowset_id)
4397
1
                    .tag("packed_file_path", packed_file_path)
4398
1
                    .tag("left_file_count", left_file_count);
4399
1
            if (left_file_count == 0) {
4400
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4401
0
                    return -1;
4402
0
                }
4403
1
            }
4404
1
            return 0;
4405
1
        }
4406
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4407
0
            if (attempt >= max_retry_times) {
4408
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4409
0
                        .tag("instance_id", instance_id_)
4410
0
                        .tag("tablet_id", tablet_id)
4411
0
                        .tag("rowset_id", rowset_id)
4412
0
                        .tag("packed_file_path", packed_file_path)
4413
0
                        .tag("attempt", attempt);
4414
0
                return -1;
4415
0
            }
4416
0
            sleep_for_packed_file_retry();
4417
0
            continue;
4418
0
        }
4419
4420
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4421
0
                .tag("instance_id", instance_id_)
4422
0
                .tag("tablet_id", tablet_id)
4423
0
                .tag("rowset_id", rowset_id)
4424
0
                .tag("packed_file_path", packed_file_path)
4425
0
                .tag("err", err);
4426
0
        return -1;
4427
0
    }
4428
4429
18.4E
    return -1;
4430
18.4E
}
4431
4432
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4433
                                                const std::string& packed_key,
4434
7.50k
                                                const cloud::PackedFileInfoPB& packed_info) {
4435
7.50k
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4436
0
        LOG_WARNING("packed file missing resource id when recycling")
4437
0
                .tag("instance_id", instance_id_)
4438
0
                .tag("packed_file_path", packed_file_path);
4439
0
        return -1;
4440
0
    }
4441
4442
7.50k
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4443
7.50k
    if (!accessor) {
4444
0
        LOG_WARNING("no accessor available to delete packed file")
4445
0
                .tag("instance_id", instance_id_)
4446
0
                .tag("packed_file_path", packed_file_path)
4447
0
                .tag("resource_id", packed_info.resource_id());
4448
0
        return -1;
4449
0
    }
4450
4451
7.50k
    int del_ret = accessor->delete_file(packed_file_path);
4452
7.50k
    if (del_ret != 0 && del_ret != 1) {
4453
0
        LOG_WARNING("failed to delete packed file")
4454
0
                .tag("instance_id", instance_id_)
4455
0
                .tag("packed_file_path", packed_file_path)
4456
0
                .tag("resource_id", resource_id)
4457
0
                .tag("ret", del_ret);
4458
0
        return -1;
4459
0
    }
4460
7.50k
    if (del_ret == 1) {
4461
0
        LOG_INFO("packed file already removed")
4462
0
                .tag("instance_id", instance_id_)
4463
0
                .tag("packed_file_path", packed_file_path)
4464
0
                .tag("resource_id", resource_id);
4465
7.50k
    } else {
4466
7.50k
        LOG_INFO("deleted packed file")
4467
7.50k
                .tag("instance_id", instance_id_)
4468
7.50k
                .tag("packed_file_path", packed_file_path)
4469
7.50k
                .tag("resource_id", resource_id);
4470
7.50k
    }
4471
4472
7.50k
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4473
7.50k
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4474
7.50k
        std::unique_ptr<Transaction> del_txn;
4475
7.50k
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4476
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4477
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4478
0
                    .tag("instance_id", instance_id_)
4479
0
                    .tag("packed_file_path", packed_file_path)
4480
0
                    .tag("attempt", attempt)
4481
0
                    .tag("err", err);
4482
0
            return -1;
4483
0
        }
4484
4485
7.50k
        std::string latest_val;
4486
7.50k
        err = del_txn->get(packed_key, &latest_val);
4487
7.50k
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4488
0
            return 0;
4489
0
        }
4490
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4491
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4492
0
                    .tag("instance_id", instance_id_)
4493
0
                    .tag("packed_file_path", packed_file_path)
4494
0
                    .tag("attempt", attempt)
4495
0
                    .tag("err", err);
4496
0
            return -1;
4497
0
        }
4498
4499
7.50k
        cloud::PackedFileInfoPB latest_info;
4500
7.50k
        if (!latest_info.ParseFromString(latest_val)) {
4501
0
            LOG_WARNING("failed to parse packed file info before removal")
4502
0
                    .tag("instance_id", instance_id_)
4503
0
                    .tag("packed_file_path", packed_file_path)
4504
0
                    .tag("attempt", attempt);
4505
0
            return -1;
4506
0
        }
4507
4508
7.50k
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4509
7.50k
              latest_info.ref_cnt() == 0)) {
4510
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4511
0
                    .tag("instance_id", instance_id_)
4512
0
                    .tag("packed_file_path", packed_file_path)
4513
0
                    .tag("attempt", attempt);
4514
0
            return 0;
4515
0
        }
4516
4517
7.50k
        del_txn->remove(packed_key);
4518
7.50k
        err = del_txn->commit();
4519
7.50k
        if (err == TxnErrorCode::TXN_OK) {
4520
7.50k
            LOG_INFO("removed packed file metadata")
4521
7.50k
                    .tag("instance_id", instance_id_)
4522
7.50k
                    .tag("packed_file_path", packed_file_path);
4523
7.50k
            return 0;
4524
7.50k
        }
4525
18.4E
        if (err == TxnErrorCode::TXN_CONFLICT) {
4526
0
            if (attempt >= max_retry_times) {
4527
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4528
0
                        .tag("instance_id", instance_id_)
4529
0
                        .tag("packed_file_path", packed_file_path)
4530
0
                        .tag("attempt", attempt);
4531
0
                return -1;
4532
0
            }
4533
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4534
0
                    .tag("instance_id", instance_id_)
4535
0
                    .tag("packed_file_path", packed_file_path)
4536
0
                    .tag("attempt", attempt);
4537
0
            sleep_for_packed_file_retry();
4538
0
            continue;
4539
0
        }
4540
18.4E
        LOG_WARNING("failed to remove packed file kv")
4541
18.4E
                .tag("instance_id", instance_id_)
4542
18.4E
                .tag("packed_file_path", packed_file_path)
4543
18.4E
                .tag("attempt", attempt)
4544
18.4E
                .tag("err", err);
4545
18.4E
        return -1;
4546
18.4E
    }
4547
18.4E
    return -1;
4548
7.50k
}
4549
4550
int InstanceRecycler::delete_rowset_data(
4551
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4552
        RecyclerMetricsContext& metrics_context,
4553
440
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4554
440
    int ret = 0;
4555
    // resource_id -> file_paths
4556
440
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4557
    // (resource_id, tablet_id, rowset_id)
4558
440
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4559
440
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4560
4561
106k
    for (const auto& [_, rs] : rowsets) {
4562
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4563
        // due to aborted schema change.
4564
106k
        if (is_formal_rowset) {
4565
53.1k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4566
                // Tablet has been recycled and this rowset has no packed slices, so file data
4567
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4568
                // slice info must still run to decrement packed file ref counts.
4569
0
                continue;
4570
0
            }
4571
53.1k
        }
4572
4573
106k
        int64_t num_segments = rs.num_segments();
4574
        // Check num_segments before accessor lookup, because empty rowsets
4575
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4576
        // set. Skipping them early avoids a spurious "no such resource id" error
4577
        // that marks the entire batch as failed and prevents txn_remove from
4578
        // cleaning up recycle KV keys.
4579
106k
        if (num_segments <= 0) {
4580
10.0k
            metrics_context.total_recycled_num++;
4581
10.0k
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4582
10.0k
            continue;
4583
10.0k
        }
4584
4585
96.4k
        auto it = accessor_map_.find(rs.resource_id());
4586
        // possible if the accessor is not initilized correctly
4587
96.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4588
2.00k
            LOG_WARNING("instance has no such resource id")
4589
2.00k
                    .tag("instance_id", instance_id_)
4590
2.00k
                    .tag("resource_id", rs.resource_id());
4591
2.00k
            ret = -1;
4592
2.00k
            continue;
4593
2.00k
        }
4594
4595
94.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4596
94.4k
        const auto& rowset_id = rs.rowset_id_v2();
4597
94.4k
        int64_t tablet_id = rs.tablet_id();
4598
94.4k
        LOG_INFO("recycle rowset merge index size")
4599
94.4k
                .tag("instance_id", instance_id_)
4600
94.4k
                .tag("tablet_id", tablet_id)
4601
94.4k
                .tag("rowset_id", rowset_id)
4602
94.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4603
94.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4604
0
            ret = -1;
4605
0
            continue;
4606
0
        }
4607
4608
94.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4609
94.4k
        std::vector<std::string> rowset_dbm_keys;
4610
94.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4611
94.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4612
94.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4613
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4614
0
                    .tag("instance_id", instance_id_)
4615
0
                    .tag("tablet_id", tablet_id)
4616
0
                    .tag("rowset_id", rowset_id);
4617
0
            ret = -1;
4618
0
            continue;
4619
0
        }
4620
94.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4621
11.5k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4622
11.5k
        }
4623
94.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4624
61.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4625
61.5k
        }
4626
4627
        // Process inverted indexes
4628
94.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4629
        // default format as v1.
4630
94.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4631
94.4k
                                                            ? rs.inverted_index_storage_format()
4632
94.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4633
94.4k
        int inverted_index_get_ret = 0;
4634
94.4k
        if (rs.has_tablet_schema()) {
4635
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4636
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4637
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4638
53.5k
                }
4639
53.5k
            }
4640
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4641
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4642
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4643
26.5k
            }
4644
67.5k
        } else {
4645
67.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4646
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4647
0
                                "instance_id="
4648
0
                             << instance_id_ << " tablet_id=" << tablet_id
4649
0
                             << " rowset_id=" << rowset_id;
4650
0
                ret = -1;
4651
0
                continue;
4652
0
            }
4653
67.5k
            InvertedIndexInfo index_info;
4654
67.5k
            inverted_index_get_ret =
4655
67.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4656
67.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4657
67.5k
                                     &inverted_index_get_ret);
4658
67.5k
            if (inverted_index_get_ret == 0) {
4659
62.0k
                if (!rs.has_inverted_index_storage_format()) {
4660
62.0k
                    index_format = index_info.first;
4661
62.0k
                }
4662
62.0k
                index_ids = index_info.second;
4663
62.0k
            } else if (inverted_index_get_ret == 1) {
4664
                // 1. Schema kv not found means tablet has been recycled
4665
                // Maybe some tablet recycle failed by some bugs
4666
                // We need to delete again to double check
4667
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4668
                // because we are uncertain about the inverted index information.
4669
                // If there are inverted indexes, some data might not be deleted,
4670
                // but this is acceptable as we have made our best effort to delete the data.
4671
5.50k
                LOG_INFO(
4672
5.50k
                        "delete rowset data schema kv not found, need to delete again to "
4673
5.50k
                        "double "
4674
5.50k
                        "check")
4675
5.50k
                        .tag("instance_id", instance_id_)
4676
5.50k
                        .tag("tablet_id", tablet_id)
4677
5.50k
                        .tag("rowset", rs.ShortDebugString());
4678
                // Currently index_ids is guaranteed to be empty,
4679
                // but we clear it again here as a safeguard against future code changes
4680
                // that might cause index_ids to no longer be empty
4681
5.50k
                index_format = InvertedIndexStorageFormatPB::V2;
4682
5.50k
                index_ids.clear();
4683
18.4E
            } else {
4684
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4685
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4686
18.4E
                ret = -1;
4687
18.4E
                continue;
4688
18.4E
            }
4689
67.5k
        }
4690
94.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE && !is_formal_rowset) {
4691
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4692
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4693
6
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4694
6
            continue;
4695
6
        }
4696
405k
        for (int64_t i = 0; i < num_segments; ++i) {
4697
310k
            auto segment_id = rowset_segment_id(rs, i);
4698
310k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4699
310k
                                             &file_paths);
4700
310k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4701
572k
                for (const auto& index_id : index_ids) {
4702
572k
                    add_file_to_delete_if_not_packed(
4703
572k
                            rs,
4704
572k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4705
572k
                                                   index_id.second),
4706
572k
                            &file_paths);
4707
572k
                }
4708
302k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4709
                // try to recycle inverted index v2 when get_ret == 1
4710
                // we treat schema not found as if it has a v2 format inverted index
4711
                // to reduce chance of data leakage
4712
7.50k
                if (inverted_index_get_ret == 1) {
4713
7.49k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4714
7.49k
                            .tag("instance_id", instance_id_)
4715
7.49k
                            .tag("inverted index v2 path",
4716
7.49k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4717
7.49k
                }
4718
7.50k
                add_file_to_delete_if_not_packed(
4719
7.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4720
7.50k
            }
4721
310k
        }
4722
94.4k
    }
4723
4724
440
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4725
440
                                                 "delete_rowset_data",
4726
440
                                                 [](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
4726
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
4726
199
                                                 [](const int& ret) { return ret != 0; });
4727
440
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4728
199
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4729
199
            DCHECK(accessor_map_.count(*rid))
4730
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4731
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4732
199
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4733
199
                                     &accessor_map_);
4734
199
            if (!accessor_map_.contains(*rid)) {
4735
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4736
0
                        .tag("resource_id", resource_id)
4737
0
                        .tag("instance_id", instance_id_);
4738
0
                return -1;
4739
0
            }
4740
199
            auto& accessor = accessor_map_[*rid];
4741
199
            int ret = accessor->delete_files(*paths);
4742
199
            if (!ret) {
4743
                // deduplication of different files with the same rowset id
4744
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4745
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4746
199
                std::set<std::string> deleted_rowset_id;
4747
4748
199
                std::for_each(paths->begin(), paths->end(),
4749
199
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4750
922k
                               this](const std::string& path) {
4751
922k
                                  std::vector<std::string> str;
4752
922k
                                  butil::SplitString(path, '/', &str);
4753
922k
                                  std::string rowset_id;
4754
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4755
921k
                                      rowset_id = str.back().substr(0, pos);
4756
921k
                                  } else {
4757
1.68k
                                      if (path.find("packed_file/") != std::string::npos) {
4758
0
                                          return; // packed files do not have rowset_id encoded
4759
0
                                      }
4760
1.68k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4761
1.68k
                                      return;
4762
1.68k
                                  }
4763
921k
                                  auto rs_meta = rowsets.find(rowset_id);
4764
921k
                                  if (rs_meta != rowsets.end() &&
4765
921k
                                      !deleted_rowset_id.contains(rowset_id)) {
4766
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4767
84.4k
                                      metrics_context.total_recycled_data_size +=
4768
84.4k
                                              rs_meta->second.total_disk_size();
4769
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4770
84.4k
                                              rs_meta->second.num_segments();
4771
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4772
84.4k
                                              rs_meta->second.total_disk_size();
4773
84.4k
                                      metrics_context.total_recycled_num++;
4774
84.4k
                                  }
4775
921k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4750
7
                               this](const std::string& path) {
4751
7
                                  std::vector<std::string> str;
4752
7
                                  butil::SplitString(path, '/', &str);
4753
7
                                  std::string rowset_id;
4754
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4755
7
                                      rowset_id = str.back().substr(0, pos);
4756
7
                                  } else {
4757
0
                                      if (path.find("packed_file/") != std::string::npos) {
4758
0
                                          return; // packed files do not have rowset_id encoded
4759
0
                                      }
4760
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4761
0
                                      return;
4762
0
                                  }
4763
7
                                  auto rs_meta = rowsets.find(rowset_id);
4764
7
                                  if (rs_meta != rowsets.end() &&
4765
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4766
7
                                      deleted_rowset_id.emplace(rowset_id);
4767
7
                                      metrics_context.total_recycled_data_size +=
4768
7
                                              rs_meta->second.total_disk_size();
4769
7
                                      segment_metrics_context_.total_recycled_num +=
4770
7
                                              rs_meta->second.num_segments();
4771
7
                                      segment_metrics_context_.total_recycled_data_size +=
4772
7
                                              rs_meta->second.total_disk_size();
4773
7
                                      metrics_context.total_recycled_num++;
4774
7
                                  }
4775
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
4750
922k
                               this](const std::string& path) {
4751
922k
                                  std::vector<std::string> str;
4752
922k
                                  butil::SplitString(path, '/', &str);
4753
922k
                                  std::string rowset_id;
4754
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4755
921k
                                      rowset_id = str.back().substr(0, pos);
4756
921k
                                  } else {
4757
1.68k
                                      if (path.find("packed_file/") != std::string::npos) {
4758
0
                                          return; // packed files do not have rowset_id encoded
4759
0
                                      }
4760
1.68k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4761
1.68k
                                      return;
4762
1.68k
                                  }
4763
921k
                                  auto rs_meta = rowsets.find(rowset_id);
4764
921k
                                  if (rs_meta != rowsets.end() &&
4765
921k
                                      !deleted_rowset_id.contains(rowset_id)) {
4766
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4767
84.4k
                                      metrics_context.total_recycled_data_size +=
4768
84.4k
                                              rs_meta->second.total_disk_size();
4769
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4770
84.4k
                                              rs_meta->second.num_segments();
4771
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4772
84.4k
                                              rs_meta->second.total_disk_size();
4773
84.4k
                                      metrics_context.total_recycled_num++;
4774
84.4k
                                  }
4775
921k
                              });
4776
199
            }
4777
199
            return ret;
4778
199
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4728
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4729
6
            DCHECK(accessor_map_.count(*rid))
4730
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4731
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4732
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4733
6
                                     &accessor_map_);
4734
6
            if (!accessor_map_.contains(*rid)) {
4735
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4736
0
                        .tag("resource_id", resource_id)
4737
0
                        .tag("instance_id", instance_id_);
4738
0
                return -1;
4739
0
            }
4740
6
            auto& accessor = accessor_map_[*rid];
4741
6
            int ret = accessor->delete_files(*paths);
4742
6
            if (!ret) {
4743
                // deduplication of different files with the same rowset id
4744
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4745
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4746
6
                std::set<std::string> deleted_rowset_id;
4747
4748
6
                std::for_each(paths->begin(), paths->end(),
4749
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4750
6
                               this](const std::string& path) {
4751
6
                                  std::vector<std::string> str;
4752
6
                                  butil::SplitString(path, '/', &str);
4753
6
                                  std::string rowset_id;
4754
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4755
6
                                      rowset_id = str.back().substr(0, pos);
4756
6
                                  } else {
4757
6
                                      if (path.find("packed_file/") != std::string::npos) {
4758
6
                                          return; // packed files do not have rowset_id encoded
4759
6
                                      }
4760
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4761
6
                                      return;
4762
6
                                  }
4763
6
                                  auto rs_meta = rowsets.find(rowset_id);
4764
6
                                  if (rs_meta != rowsets.end() &&
4765
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4766
6
                                      deleted_rowset_id.emplace(rowset_id);
4767
6
                                      metrics_context.total_recycled_data_size +=
4768
6
                                              rs_meta->second.total_disk_size();
4769
6
                                      segment_metrics_context_.total_recycled_num +=
4770
6
                                              rs_meta->second.num_segments();
4771
6
                                      segment_metrics_context_.total_recycled_data_size +=
4772
6
                                              rs_meta->second.total_disk_size();
4773
6
                                      metrics_context.total_recycled_num++;
4774
6
                                  }
4775
6
                              });
4776
6
            }
4777
6
            return ret;
4778
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4728
193
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4729
193
            DCHECK(accessor_map_.count(*rid))
4730
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4731
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4732
193
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4733
193
                                     &accessor_map_);
4734
193
            if (!accessor_map_.contains(*rid)) {
4735
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4736
0
                        .tag("resource_id", resource_id)
4737
0
                        .tag("instance_id", instance_id_);
4738
0
                return -1;
4739
0
            }
4740
193
            auto& accessor = accessor_map_[*rid];
4741
193
            int ret = accessor->delete_files(*paths);
4742
193
            if (!ret) {
4743
                // deduplication of different files with the same rowset id
4744
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4745
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4746
193
                std::set<std::string> deleted_rowset_id;
4747
4748
193
                std::for_each(paths->begin(), paths->end(),
4749
193
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4750
193
                               this](const std::string& path) {
4751
193
                                  std::vector<std::string> str;
4752
193
                                  butil::SplitString(path, '/', &str);
4753
193
                                  std::string rowset_id;
4754
193
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4755
193
                                      rowset_id = str.back().substr(0, pos);
4756
193
                                  } else {
4757
193
                                      if (path.find("packed_file/") != std::string::npos) {
4758
193
                                          return; // packed files do not have rowset_id encoded
4759
193
                                      }
4760
193
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4761
193
                                      return;
4762
193
                                  }
4763
193
                                  auto rs_meta = rowsets.find(rowset_id);
4764
193
                                  if (rs_meta != rowsets.end() &&
4765
193
                                      !deleted_rowset_id.contains(rowset_id)) {
4766
193
                                      deleted_rowset_id.emplace(rowset_id);
4767
193
                                      metrics_context.total_recycled_data_size +=
4768
193
                                              rs_meta->second.total_disk_size();
4769
193
                                      segment_metrics_context_.total_recycled_num +=
4770
193
                                              rs_meta->second.num_segments();
4771
193
                                      segment_metrics_context_.total_recycled_data_size +=
4772
193
                                              rs_meta->second.total_disk_size();
4773
193
                                      metrics_context.total_recycled_num++;
4774
193
                                  }
4775
193
                              });
4776
193
            }
4777
193
            return ret;
4778
193
        });
4779
199
    }
4780
440
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4781
6
        LOG_INFO(
4782
6
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4783
6
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4784
6
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4785
6
        concurrent_delete_executor.add([&]() -> int {
4786
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4787
6
            if (!ret) {
4788
6
                auto rs = rowsets.at(rowset_id);
4789
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4790
6
                metrics_context.total_recycled_num++;
4791
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4792
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4793
6
            }
4794
6
            return ret;
4795
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
4785
6
        concurrent_delete_executor.add([&]() -> int {
4786
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4787
6
            if (!ret) {
4788
6
                auto rs = rowsets.at(rowset_id);
4789
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4790
6
                metrics_context.total_recycled_num++;
4791
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4792
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4793
6
            }
4794
6
            return ret;
4795
6
        });
4796
6
    }
4797
4798
440
    bool finished = true;
4799
440
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4800
440
    for (int r : rets) {
4801
205
        if (r != 0) {
4802
0
            ret = -1;
4803
0
            break;
4804
0
        }
4805
205
    }
4806
440
    ret = finished ? ret : -1;
4807
440
    return ret;
4808
440
}
4809
4810
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4811
43.5k
                                         const std::string& rowset_id) {
4812
43.5k
    auto it = accessor_map_.find(resource_id);
4813
43.5k
    if (it == accessor_map_.end()) {
4814
400
        LOG_WARNING("instance has no such resource id")
4815
400
                .tag("instance_id", instance_id_)
4816
400
                .tag("resource_id", resource_id)
4817
400
                .tag("tablet_id", tablet_id)
4818
400
                .tag("rowset_id", rowset_id);
4819
400
        return -1;
4820
400
    }
4821
43.1k
    auto& accessor = it->second;
4822
43.1k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4823
43.5k
}
4824
4825
145k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4826
145k
    std::lock_guard lock(recycled_tablets_mtx_);
4827
145k
    return recycled_tablets_.contains(tablet_id);
4828
145k
}
4829
4830
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4831
92.4k
                                                                int64_t tablet_id) {
4832
92.4k
    bool is_mow = true;
4833
92.4k
    if (partition_id != -1) {
4834
82.1k
        std::lock_guard lock(partition_mow_cache_mutex);
4835
82.1k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4836
            // cache hit
4837
1
            is_mow = it->second;
4838
1
            return is_mow ? 1 : 0;
4839
1
        }
4840
82.1k
    }
4841
4842
92.4k
    TabletIndexPB tablet_index;
4843
92.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4844
92.4k
    if (ret == 1) {
4845
        // maybe recycled
4846
92.2k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4847
92.2k
    }
4848
187
    if (ret != 0) {
4849
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4850
0
                     << ", tablet_id=" << tablet_id;
4851
0
        return ret;
4852
0
    }
4853
4854
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4855
    // obtaining its partition ID from the tablet index.
4856
187
    if (partition_id == -1) {
4857
0
        partition_id = tablet_index.partition_id();
4858
0
        std::lock_guard lock(partition_mow_cache_mutex);
4859
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4860
0
            is_mow = it->second;
4861
0
            return is_mow ? 1 : 0;
4862
0
        }
4863
0
    }
4864
4865
187
    std::string tablet_meta_key =
4866
187
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4867
187
                             partition_id, tablet_id});
4868
187
    std::string tablet_meta_value;
4869
187
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4870
187
    if (ret == 1) {
4871
        // maybe recycled
4872
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4873
10
    }
4874
177
    if (ret != 0) {
4875
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4876
0
                     << ", tablet_id=" << tablet_id;
4877
0
        return ret;
4878
0
    }
4879
4880
177
    TabletMetaCloudPB tablet_meta;
4881
177
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4882
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4883
0
                     << ", tablet_id=" << tablet_id;
4884
0
        return -1;
4885
0
    }
4886
    // The row-binlog companion of a MoW data tablet stores versioned delete bitmaps copied from
4887
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4888
    // false value as the MoW state of the whole partition.
4889
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isRowBinlogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4890
177
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_ROW_BINLOG) {
4891
1
        return 1;
4892
1
    }
4893
176
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4894
176
    std::lock_guard lock(partition_mow_cache_mutex);
4895
176
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4896
176
    return it->second ? 1 : 0;
4897
177
}
4898
4899
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4900
92.4k
                                                         const std::string& rowset_id) {
4901
92.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4902
92.4k
    if (ret <= 0) {
4903
1.00k
        return ret;
4904
1.00k
    }
4905
4906
91.4k
    std::string dbm_start_key =
4907
91.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4908
91.4k
    std::string dbm_end_key = dbm_start_key;
4909
91.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4910
91.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4911
91.4k
    if (ret != 0) {
4912
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4913
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4914
0
                     << " rowset_id=" << rowset_id;
4915
0
    }
4916
91.4k
    return ret;
4917
92.4k
}
4918
4919
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4920
51.2k
    std::string delete_bitmap_start =
4921
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4922
51.2k
    std::string delete_bitmap_end =
4923
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4924
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4925
51.2k
    if (ret != 0) {
4926
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4927
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4928
0
    }
4929
51.2k
    return ret;
4930
51.2k
}
4931
4932
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4933
4
    if (key.empty()) {
4934
0
        return false;
4935
0
    }
4936
4
    std::string_view key_view = key;
4937
4
    key_view.remove_prefix(1); // remove keyspace prefix
4938
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4939
4
    if (decode_key(&key_view, &decoded) != 0) {
4940
0
        return false;
4941
0
    }
4942
4
    if (decoded.size() < 4) {
4943
0
        return false;
4944
0
    }
4945
4
    try {
4946
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4947
4
    } catch (const std::bad_variant_access&) {
4948
0
        return false;
4949
0
    }
4950
4
    return true;
4951
4
}
4952
4953
14
int InstanceRecycler::recycle_packed_files() {
4954
14
    const std::string task_name = "recycle_packed_files";
4955
14
    auto start_tp = steady_clock::now();
4956
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4957
14
    int ret = 0;
4958
14
    PackedFileRecycleStats stats;
4959
4960
14
    register_recycle_task(task_name, start_time);
4961
14
    DORIS_CLOUD_DEFER {
4962
14
        unregister_recycle_task(task_name);
4963
14
        int64_t cost =
4964
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4965
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4966
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4967
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4968
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4969
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4970
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4971
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4972
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4973
14
                                                             stats.bytes_object_deleted);
4974
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4975
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4976
14
                .tag("instance_id", instance_id_)
4977
14
                .tag("num_scanned", stats.num_scanned)
4978
14
                .tag("num_corrected", stats.num_corrected)
4979
14
                .tag("num_deleted", stats.num_deleted)
4980
14
                .tag("num_failed", stats.num_failed)
4981
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4982
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4983
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4984
14
                .tag("bytes_deleted", stats.bytes_deleted)
4985
14
                .tag("ret", ret);
4986
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4961
14
    DORIS_CLOUD_DEFER {
4962
14
        unregister_recycle_task(task_name);
4963
14
        int64_t cost =
4964
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4965
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4966
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4967
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4968
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4969
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4970
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4971
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4972
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4973
14
                                                             stats.bytes_object_deleted);
4974
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4975
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4976
14
                .tag("instance_id", instance_id_)
4977
14
                .tag("num_scanned", stats.num_scanned)
4978
14
                .tag("num_corrected", stats.num_corrected)
4979
14
                .tag("num_deleted", stats.num_deleted)
4980
14
                .tag("num_failed", stats.num_failed)
4981
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4982
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4983
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4984
14
                .tag("bytes_deleted", stats.bytes_deleted)
4985
14
                .tag("ret", ret);
4986
14
    };
4987
4988
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4989
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4990
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4991
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
4988
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4989
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4990
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4991
4
    };
4992
4993
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4994
4995
14
    std::string begin = packed_file_key({instance_id_, ""});
4996
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4997
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4998
0
        ret = -1;
4999
0
    }
5000
5001
14
    return ret;
5002
14
}
5003
5004
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
5005
                                                  RecyclerMetricsContext& metrics_context,
5006
0
                                                  int64_t partition_id, bool is_empty_tablet) {
5007
0
    std::string tablet_key_begin, tablet_key_end;
5008
5009
0
    if (partition_id > 0) {
5010
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
5011
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
5012
0
    } else {
5013
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
5014
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
5015
0
    }
5016
    // for calculate the total num or bytes of recyled objects
5017
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
5018
0
                                                          std::string_view v) -> int {
5019
0
        doris::TabletMetaCloudPB tablet_meta_pb;
5020
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
5021
0
            return 0;
5022
0
        }
5023
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
5024
5025
0
        if (config::enable_recycler_check_lazy_txn_finished &&
5026
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
5027
0
            return 0;
5028
0
        }
5029
5030
0
        if (!is_empty_tablet) {
5031
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
5032
0
                return 0;
5033
0
            }
5034
0
            tablet_metrics_context_.total_need_recycle_num++;
5035
0
        }
5036
0
        return 0;
5037
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_
5038
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
5039
0
    metrics_context.report(true);
5040
0
    tablet_metrics_context_.report(true);
5041
0
    segment_metrics_context_.report(true);
5042
0
    return ret;
5043
0
}
5044
5045
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
5046
0
                                                 RecyclerMetricsContext& metrics_context) {
5047
0
    int ret = 0;
5048
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
5049
0
    std::unique_ptr<Transaction> txn;
5050
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5051
0
        LOG_WARNING("failed to recycle tablet ")
5052
0
                .tag("tablet id", tablet_id)
5053
0
                .tag("instance_id", instance_id_)
5054
0
                .tag("reason", "failed to create txn");
5055
0
        ret = -1;
5056
0
    }
5057
0
    GetRowsetResponse resp;
5058
0
    std::string msg;
5059
0
    MetaServiceCode code = MetaServiceCode::OK;
5060
    // get rowsets in tablet
5061
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5062
0
                        tablet_id, code, msg, &resp);
5063
0
    if (code != MetaServiceCode::OK) {
5064
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5065
0
                .tag("tablet id", tablet_id)
5066
0
                .tag("msg", msg)
5067
0
                .tag("code", code)
5068
0
                .tag("instance id", instance_id_);
5069
0
        ret = -1;
5070
0
    }
5071
0
    for (const auto& rs_meta : resp.rowset_meta()) {
5072
        /*
5073
        * For compatibility, we skip the loop for [0-1] here.
5074
        * The purpose of this loop is to delete object files,
5075
        * and since [0-1] only has meta and doesn't have object files,
5076
        * skipping it doesn't affect system correctness.
5077
        *
5078
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
5079
        * would return error -1 directly, causing the recycle operation to fail.
5080
        *
5081
        * [0-1] doesn't have resource id is a bug.
5082
        * In the future, we will fix this problem, after that,
5083
        * we can remove this if statement.
5084
        *
5085
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
5086
        */
5087
5088
0
        if (rs_meta.end_version() == 1) {
5089
            // Assert that [0-1] has no resource_id to make sure
5090
            // this if statement will not be forgetted to remove
5091
            // when the resource id bug is fixed
5092
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5093
0
            continue;
5094
0
        }
5095
0
        if (!rs_meta.has_resource_id()) {
5096
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5097
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5098
0
                    .tag("instance_id", instance_id_)
5099
0
                    .tag("tablet_id", tablet_id);
5100
0
            continue;
5101
0
        }
5102
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5103
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5104
        // possible if the accessor is not initilized correctly
5105
0
        if (it == accessor_map_.end()) [[unlikely]] {
5106
0
            LOG_WARNING(
5107
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5108
0
                    "recycle process")
5109
0
                    .tag("tablet id", tablet_id)
5110
0
                    .tag("instance_id", instance_id_)
5111
0
                    .tag("resource_id", rs_meta.resource_id())
5112
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5113
0
            continue;
5114
0
        }
5115
5116
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
5117
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5118
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5119
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
5120
0
    }
5121
0
    return ret;
5122
0
}
5123
5124
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5125
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5126
4.26k
            .tag("instance_id", instance_id_)
5127
4.26k
            .tag("tablet_id", tablet_id);
5128
5129
4.26k
    if (should_recycle_versioned_keys()) {
5130
16
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5131
16
        if (ret != 0) {
5132
0
            return ret;
5133
0
        }
5134
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5135
        // during the recycle_versioned_tablet process.
5136
        //
5137
        // .. And remove restore job rowsets of this tablet too
5138
16
    }
5139
5140
4.26k
    int ret = 0;
5141
4.26k
    auto start_time = steady_clock::now();
5142
5143
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5144
5145
    // collect resource ids
5146
263
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5147
263
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5148
263
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5149
263
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5150
263
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5151
263
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5152
5153
263
    std::set<std::string> resource_ids;
5154
263
    int64_t recycle_rowsets_number = 0;
5155
263
    int64_t recycle_segments_number = 0;
5156
263
    int64_t recycle_rowsets_data_size = 0;
5157
263
    int64_t recycle_rowsets_index_size = 0;
5158
263
    int64_t recycle_restore_job_rowsets_number = 0;
5159
263
    int64_t recycle_restore_job_segments_number = 0;
5160
263
    int64_t recycle_restore_job_rowsets_data_size = 0;
5161
263
    int64_t recycle_restore_job_rowsets_index_size = 0;
5162
263
    int64_t max_rowset_version = 0;
5163
263
    int64_t min_rowset_creation_time = INT64_MAX;
5164
263
    int64_t max_rowset_creation_time = 0;
5165
263
    int64_t min_rowset_expiration_time = INT64_MAX;
5166
263
    int64_t max_rowset_expiration_time = 0;
5167
5168
263
    DORIS_CLOUD_DEFER {
5169
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5170
262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5171
262
                .tag("instance_id", instance_id_)
5172
262
                .tag("tablet_id", tablet_id)
5173
262
                .tag("recycle rowsets number", recycle_rowsets_number)
5174
262
                .tag("recycle segments number", recycle_segments_number)
5175
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5176
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5177
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5178
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5179
262
                .tag("all restore job rowsets recycle data size",
5180
262
                     recycle_restore_job_rowsets_data_size)
5181
262
                .tag("all restore job rowsets recycle index size",
5182
262
                     recycle_restore_job_rowsets_index_size)
5183
262
                .tag("max rowset version", max_rowset_version)
5184
262
                .tag("min rowset creation time", min_rowset_creation_time)
5185
262
                .tag("max rowset creation time", max_rowset_creation_time)
5186
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
5187
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
5188
262
                .tag("task type", metrics_context.operation_type)
5189
262
                .tag("ret", ret);
5190
262
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5168
262
    DORIS_CLOUD_DEFER {
5169
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5170
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5171
262
                .tag("instance_id", instance_id_)
5172
262
                .tag("tablet_id", tablet_id)
5173
262
                .tag("recycle rowsets number", recycle_rowsets_number)
5174
262
                .tag("recycle segments number", recycle_segments_number)
5175
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5176
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5177
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5178
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5179
262
                .tag("all restore job rowsets recycle data size",
5180
262
                     recycle_restore_job_rowsets_data_size)
5181
262
                .tag("all restore job rowsets recycle index size",
5182
262
                     recycle_restore_job_rowsets_index_size)
5183
262
                .tag("max rowset version", max_rowset_version)
5184
262
                .tag("min rowset creation time", min_rowset_creation_time)
5185
262
                .tag("max rowset creation time", max_rowset_creation_time)
5186
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
5187
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
5188
262
                .tag("task type", metrics_context.operation_type)
5189
262
                .tag("ret", ret);
5190
262
    };
5191
5192
263
    std::unique_ptr<Transaction> txn;
5193
263
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5194
0
        LOG_WARNING("failed to recycle tablet ")
5195
0
                .tag("tablet id", tablet_id)
5196
0
                .tag("instance_id", instance_id_)
5197
0
                .tag("reason", "failed to create txn");
5198
0
        ret = -1;
5199
0
    }
5200
263
    GetRowsetResponse resp;
5201
263
    std::string msg;
5202
263
    MetaServiceCode code = MetaServiceCode::OK;
5203
    // get rowsets in tablet
5204
263
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5205
263
                        tablet_id, code, msg, &resp);
5206
263
    if (code != MetaServiceCode::OK) {
5207
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5208
0
                .tag("tablet id", tablet_id)
5209
0
                .tag("msg", msg)
5210
0
                .tag("code", code)
5211
0
                .tag("instance id", instance_id_);
5212
0
        ret = -1;
5213
0
    }
5214
263
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5215
5216
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5217
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5218
3
            if (rs_meta.num_segments() <= 0) {
5219
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5220
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5221
2
                        .tag("instance_id", instance_id_)
5222
2
                        .tag("tablet_id", tablet_id);
5223
2
                recycle_rowsets_number += 1;
5224
2
                continue;
5225
2
            }
5226
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5227
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5228
1
                    .tag("instance_id", instance_id_)
5229
1
                    .tag("tablet_id", tablet_id);
5230
1
            return -1;
5231
3
        }
5232
18.4E
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5233
18.4E
                << "rs_meta" << rs_meta.ShortDebugString();
5234
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5235
        // possible if the accessor is not initilized correctly
5236
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5237
1
            LOG_WARNING(
5238
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5239
1
                    "recycle process")
5240
1
                    .tag("tablet id", tablet_id)
5241
1
                    .tag("instance_id", instance_id_)
5242
1
                    .tag("resource_id", rs_meta.resource_id())
5243
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5244
1
            return -1;
5245
1
        }
5246
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5247
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5248
0
                    .tag("instance_id", instance_id_)
5249
0
                    .tag("tablet_id", tablet_id)
5250
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5251
0
            return -1;
5252
0
        }
5253
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5254
2.54k
                                                           nullptr) != 0) {
5255
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5256
0
                    .tag("instance_id", instance_id_)
5257
0
                    .tag("tablet_id", tablet_id)
5258
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5259
0
            return -1;
5260
0
        }
5261
2.54k
        recycle_rowsets_number += 1;
5262
2.54k
        recycle_segments_number += rs_meta.num_segments();
5263
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5264
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5265
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5266
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5267
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5268
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5269
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5270
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5271
2.54k
    }
5272
5273
    // get restore job rowset in tablet
5274
261
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5275
261
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5276
261
    if (code != MetaServiceCode::OK) {
5277
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5278
0
                .tag("tablet id", tablet_id)
5279
0
                .tag("msg", msg)
5280
0
                .tag("code", code)
5281
0
                .tag("instance id", instance_id_);
5282
0
        return -1;
5283
0
    }
5284
5285
261
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5286
0
        if (!rs_meta.has_resource_id()) {
5287
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5288
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5289
0
                    .tag("instance_id", instance_id_)
5290
0
                    .tag("tablet_id", tablet_id);
5291
0
            return -1;
5292
0
        }
5293
5294
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5295
        // possible if the accessor is not initilized correctly
5296
0
        if (it == accessor_map_.end()) [[unlikely]] {
5297
0
            LOG_WARNING(
5298
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5299
0
                    "recycle process")
5300
0
                    .tag("tablet id", tablet_id)
5301
0
                    .tag("instance_id", instance_id_)
5302
0
                    .tag("resource_id", rs_meta.resource_id())
5303
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5304
0
            return -1;
5305
0
        }
5306
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5307
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5308
0
                    .tag("instance_id", instance_id_)
5309
0
                    .tag("tablet_id", tablet_id)
5310
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5311
0
            return -1;
5312
0
        }
5313
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5314
0
                                                           nullptr) != 0) {
5315
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5316
0
                    .tag("instance_id", instance_id_)
5317
0
                    .tag("tablet_id", tablet_id)
5318
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5319
0
            return -1;
5320
0
        }
5321
0
        recycle_restore_job_rowsets_number += 1;
5322
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5323
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5324
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5325
0
        resource_ids.emplace(rs_meta.resource_id());
5326
0
    }
5327
5328
261
    LOG_INFO("recycle tablet start to delete object")
5329
261
            .tag("instance id", instance_id_)
5330
261
            .tag("tablet id", tablet_id)
5331
261
            .tag("recycle tablet resource ids are",
5332
261
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5333
261
                                 [](std::string rs_id, const auto& it) {
5334
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5335
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
5333
217
                                 [](std::string rs_id, const auto& it) {
5334
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5335
217
                                 }));
5336
5337
261
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5338
261
            _thread_pool_group.s3_producer_pool,
5339
261
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5340
261
            [](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
5340
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5341
5342
    // delete all rowset data in this tablet
5343
    // ATTN: there may be data leak if not all accessor initilized successfully
5344
    //       partial data deleted if the tablet is stored cross-storage vault
5345
    //       vault id is not attached to TabletMeta...
5346
261
    for (const auto& resource_id : resource_ids) {
5347
216
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5348
216
        concurrent_delete_executor.add(
5349
216
                [&, rs_id = resource_id,
5350
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5351
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5352
217
                    if (res != 0) {
5353
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5354
3
                                     << " path=" << accessor_ptr->uri()
5355
3
                                     << " task type=" << metrics_context.operation_type;
5356
3
                        return std::make_pair(-1, rs_id);
5357
3
                    }
5358
214
                    return std::make_pair(0, rs_id);
5359
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5350
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5351
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5352
217
                    if (res != 0) {
5353
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5354
3
                                     << " path=" << accessor_ptr->uri()
5355
3
                                     << " task type=" << metrics_context.operation_type;
5356
3
                        return std::make_pair(-1, rs_id);
5357
3
                    }
5358
214
                    return std::make_pair(0, rs_id);
5359
217
                });
5360
216
    }
5361
5362
261
    bool finished = true;
5363
261
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5364
261
    for (auto& r : rets) {
5365
217
        if (r.first != 0) {
5366
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5367
3
            ret = -1;
5368
3
        }
5369
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5370
217
    }
5371
261
    ret = finished ? ret : -1;
5372
5373
261
    if (ret != 0) { // failed recycle tablet data
5374
3
        LOG_WARNING("ret!=0")
5375
3
                .tag("finished", finished)
5376
3
                .tag("ret", ret)
5377
3
                .tag("instance_id", instance_id_)
5378
3
                .tag("tablet_id", tablet_id);
5379
3
        return ret;
5380
3
    }
5381
5382
258
    tablet_metrics_context_.total_recycled_data_size +=
5383
258
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5384
258
    tablet_metrics_context_.total_recycled_num += 1;
5385
258
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5386
258
    segment_metrics_context_.total_recycled_data_size +=
5387
258
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5388
258
    metrics_context.total_recycled_data_size +=
5389
258
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5390
258
    tablet_metrics_context_.report();
5391
258
    segment_metrics_context_.report();
5392
258
    metrics_context.report();
5393
5394
258
    txn.reset();
5395
258
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5396
0
        LOG_WARNING("failed to recycle tablet ")
5397
0
                .tag("tablet id", tablet_id)
5398
0
                .tag("instance_id", instance_id_)
5399
0
                .tag("reason", "failed to create txn");
5400
0
        ret = -1;
5401
0
    }
5402
    // delete all rowset kv in this tablet
5403
258
    txn->remove(rs_key0, rs_key1);
5404
258
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5405
258
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5406
5407
    // remove delete bitmap for MoW table
5408
258
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5409
258
    txn->remove(pending_key);
5410
258
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5411
258
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5412
258
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5413
5414
258
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5415
258
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5416
258
    txn->remove(dbm_start_key, dbm_end_key);
5417
258
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5418
258
              << " end=" << hex(dbm_end_key);
5419
5420
258
    TxnErrorCode err = txn->commit();
5421
258
    if (err != TxnErrorCode::TXN_OK) {
5422
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5423
0
        ret = -1;
5424
0
    }
5425
5426
258
    if (ret == 0) {
5427
        // All object files under tablet have been deleted
5428
257
        std::lock_guard lock(recycled_tablets_mtx_);
5429
257
        recycled_tablets_.insert(tablet_id);
5430
257
    }
5431
5432
258
    return ret;
5433
261
}
5434
5435
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5436
16
                                               RecyclerMetricsContext& metrics_context) {
5437
16
    int ret = 0;
5438
16
    auto start_time = steady_clock::now();
5439
5440
16
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5441
5442
    // collect resource ids
5443
13
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5444
13
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5445
13
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5446
13
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5447
5448
13
    int64_t recycle_rowsets_number = 0;
5449
13
    int64_t recycle_segments_number = 0;
5450
13
    int64_t recycle_rowsets_data_size = 0;
5451
13
    int64_t recycle_rowsets_index_size = 0;
5452
13
    int64_t max_rowset_version = 0;
5453
13
    int64_t min_rowset_creation_time = INT64_MAX;
5454
13
    int64_t max_rowset_creation_time = 0;
5455
13
    int64_t min_rowset_expiration_time = INT64_MAX;
5456
13
    int64_t max_rowset_expiration_time = 0;
5457
5458
13
    DORIS_CLOUD_DEFER {
5459
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5460
13
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5461
13
                .tag("instance_id", instance_id_)
5462
13
                .tag("tablet_id", tablet_id)
5463
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5464
13
                .tag("recycle segments number", recycle_segments_number)
5465
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5466
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5467
13
                .tag("max rowset version", max_rowset_version)
5468
13
                .tag("min rowset creation time", min_rowset_creation_time)
5469
13
                .tag("max rowset creation time", max_rowset_creation_time)
5470
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5471
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5472
13
                .tag("ret", ret);
5473
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5458
13
    DORIS_CLOUD_DEFER {
5459
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5460
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5461
13
                .tag("instance_id", instance_id_)
5462
13
                .tag("tablet_id", tablet_id)
5463
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5464
13
                .tag("recycle segments number", recycle_segments_number)
5465
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5466
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5467
13
                .tag("max rowset version", max_rowset_version)
5468
13
                .tag("min rowset creation time", min_rowset_creation_time)
5469
13
                .tag("max rowset creation time", max_rowset_creation_time)
5470
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5471
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5472
13
                .tag("ret", ret);
5473
13
    };
5474
5475
13
    std::unique_ptr<Transaction> txn;
5476
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5477
0
        LOG_WARNING("failed to recycle tablet ")
5478
0
                .tag("tablet id", tablet_id)
5479
0
                .tag("instance_id", instance_id_)
5480
0
                .tag("reason", "failed to create txn");
5481
0
        ret = -1;
5482
0
    }
5483
5484
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5485
    // by the related operation logs.
5486
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5487
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5488
13
    MetaReader meta_reader(instance_id_);
5489
13
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5490
13
    if (err == TxnErrorCode::TXN_OK) {
5491
13
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5492
13
    }
5493
13
    if (err != TxnErrorCode::TXN_OK) {
5494
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5495
0
                .tag("tablet id", tablet_id)
5496
0
                .tag("err", err)
5497
0
                .tag("instance id", instance_id_);
5498
0
        ret = -1;
5499
0
    }
5500
5501
13
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5502
13
             load_rowset_metas.size(), compact_rowset_metas.size())
5503
13
            .tag("instance_id", instance_id_)
5504
13
            .tag("tablet_id", tablet_id);
5505
5506
13
    SyncExecutor<int> concurrent_delete_executor(
5507
13
            _thread_pool_group.s3_producer_pool,
5508
13
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5509
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
5510
5511
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5512
61
        recycle_rowsets_number += 1;
5513
61
        recycle_segments_number += rs_meta.num_segments();
5514
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5515
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5516
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5517
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5518
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5519
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5520
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5521
61
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5511
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5512
61
        recycle_rowsets_number += 1;
5513
61
        recycle_segments_number += rs_meta.num_segments();
5514
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5515
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5516
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5517
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5518
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5519
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5520
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5521
61
    };
5522
5523
13
    std::vector<RowsetDeleteTask> all_tasks;
5524
61
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5525
61
        update_rowset_stats(rs_meta);
5526
        // Version 0-1 rowset has no resource_id and no actual data files,
5527
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5528
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5529
61
        RowsetDeleteTask task;
5530
61
        task.rowset_meta = rs_meta;
5531
61
        task.versioned_rowset_key =
5532
61
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5533
61
        task.non_versioned_rowset_key =
5534
61
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5535
61
        task.versionstamp = versionstamp;
5536
61
        all_tasks.push_back(std::move(task));
5537
61
    }
5538
5539
13
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5540
0
        update_rowset_stats(rs_meta);
5541
        // Version 0-1 rowset has no resource_id and no actual data files,
5542
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5543
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5544
0
        RowsetDeleteTask task;
5545
0
        task.rowset_meta = rs_meta;
5546
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5547
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5548
0
        task.non_versioned_rowset_key =
5549
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5550
0
        task.versionstamp = versionstamp;
5551
0
        all_tasks.push_back(std::move(task));
5552
0
    }
5553
5554
13
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5555
0
        RecycleRowsetPB recycle_rowset;
5556
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5557
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5558
0
            return -1;
5559
0
        }
5560
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5561
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5562
                // in old version, keep this key-value pair and it needs to be checked manually
5563
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5564
0
                return -1;
5565
0
            }
5566
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5567
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5568
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5569
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5570
0
                return -1;
5571
0
            }
5572
            // decode rowset_id
5573
0
            auto k1 = k;
5574
0
            k1.remove_prefix(1);
5575
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5576
0
            decode_key(&k1, &out);
5577
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5578
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5579
0
            LOG_INFO("delete old-version rowset data")
5580
0
                    .tag("instance_id", instance_id_)
5581
0
                    .tag("tablet_id", tablet_id)
5582
0
                    .tag("rowset_id", rowset_id);
5583
5584
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5585
            // so we must use prefix deletion directly instead of batch delete.
5586
0
            concurrent_delete_executor.add(
5587
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5588
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5589
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5590
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
5591
0
        } else {
5592
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5593
            // Version 0-1 rowset has no resource_id and no actual data files,
5594
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5595
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5596
0
            RowsetDeleteTask task;
5597
0
            task.rowset_meta = rowset_meta;
5598
0
            task.recycle_rowset_key = k;
5599
0
            all_tasks.push_back(std::move(task));
5600
0
        }
5601
0
        return 0;
5602
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_
5603
5604
13
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5605
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5606
0
                .tag("tablet id", tablet_id)
5607
0
                .tag("instance_id", instance_id_)
5608
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5609
0
        ret = -1;
5610
0
    }
5611
5612
    // Phase 1: Classify tasks by ref_count
5613
13
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5614
61
    for (auto& task : all_tasks) {
5615
61
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5616
61
        if (classify_ret < 0) {
5617
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5618
0
                    .tag("instance_id", instance_id_)
5619
0
                    .tag("tablet_id", tablet_id)
5620
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5621
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5622
0
                return recycle_rowset_meta_and_data(t);
5623
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5624
0
        }
5625
61
    }
5626
5627
13
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5628
5629
13
    LOG_INFO("batch delete plan created")
5630
13
            .tag("instance_id", instance_id_)
5631
13
            .tag("tablet_id", tablet_id)
5632
13
            .tag("plan_count", batch_delete_tasks.size());
5633
5634
    // Phase 2: Execute batch delete using existing delete_rowset_data
5635
13
    if (!batch_delete_tasks.empty()) {
5636
11
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5637
50
        for (const auto& task : batch_delete_tasks) {
5638
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5639
50
            if (task.rowset_meta.resource_id().empty()) {
5640
11
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5641
11
                        .tag("instance_id", instance_id_)
5642
11
                        .tag("tablet_id", tablet_id)
5643
11
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5644
11
                continue;
5645
11
            }
5646
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5647
39
        }
5648
5649
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5650
11
        bool delete_success = true;
5651
11
        if (!rowsets_to_delete.empty()) {
5652
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5653
9
                                                         "batch_delete_versioned_tablet");
5654
9
            int delete_ret = delete_rowset_data(
5655
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5656
9
            if (delete_ret != 0) {
5657
0
                LOG_WARNING("batch delete execution failed")
5658
0
                        .tag("instance_id", instance_id_)
5659
0
                        .tag("tablet_id", tablet_id);
5660
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5661
0
                ret = -1;
5662
0
                delete_success = false;
5663
0
            }
5664
9
        }
5665
5666
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5667
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5668
11
        if (delete_success) {
5669
11
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5670
11
            if (cleanup_ret != 0) {
5671
0
                LOG_WARNING("batch delete cleanup failed")
5672
0
                        .tag("instance_id", instance_id_)
5673
0
                        .tag("tablet_id", tablet_id);
5674
0
                ret = -1;
5675
0
            }
5676
11
        }
5677
11
    }
5678
5679
    // Always wait for fallback tasks to complete before returning
5680
13
    bool finished = true;
5681
13
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5682
13
    for (int r : rets) {
5683
0
        if (r != 0) {
5684
0
            ret = -1;
5685
0
        }
5686
0
    }
5687
5688
13
    ret = finished ? ret : -1;
5689
5690
13
    if (ret != 0) { // failed recycle tablet data
5691
0
        LOG_WARNING("recycle versioned tablet failed")
5692
0
                .tag("finished", finished)
5693
0
                .tag("ret", ret)
5694
0
                .tag("instance_id", instance_id_)
5695
0
                .tag("tablet_id", tablet_id);
5696
0
        return ret;
5697
0
    }
5698
5699
13
    tablet_metrics_context_.total_recycled_data_size +=
5700
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5701
13
    tablet_metrics_context_.total_recycled_num += 1;
5702
13
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5703
13
    segment_metrics_context_.total_recycled_data_size +=
5704
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5705
13
    metrics_context.total_recycled_data_size +=
5706
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5707
13
    tablet_metrics_context_.report();
5708
13
    segment_metrics_context_.report();
5709
13
    metrics_context.report();
5710
5711
13
    txn.reset();
5712
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5713
0
        LOG_WARNING("failed to recycle tablet ")
5714
0
                .tag("tablet id", tablet_id)
5715
0
                .tag("instance_id", instance_id_)
5716
0
                .tag("reason", "failed to create txn");
5717
0
        ret = -1;
5718
0
    }
5719
    // delete all rowset kv in this tablet
5720
13
    txn->remove(rs_key0, rs_key1);
5721
13
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5722
5723
    // remove delete bitmap for MoW table
5724
13
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5725
13
    txn->remove(pending_key);
5726
13
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5727
13
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5728
13
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5729
5730
13
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5731
13
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5732
13
    txn->remove(dbm_start_key, dbm_end_key);
5733
13
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5734
13
              << " end=" << hex(dbm_end_key);
5735
5736
13
    err = txn->commit();
5737
13
    if (err != TxnErrorCode::TXN_OK) {
5738
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5739
0
        ret = -1;
5740
0
    }
5741
5742
13
    if (ret == 0) {
5743
        // All object files under tablet have been deleted
5744
13
        std::lock_guard lock(recycled_tablets_mtx_);
5745
13
        recycled_tablets_.insert(tablet_id);
5746
13
    }
5747
5748
13
    return ret;
5749
13
}
5750
5751
66
int InstanceRecycler::recycle_rowsets() {
5752
66
    if (should_recycle_versioned_keys()) {
5753
5
        return recycle_versioned_rowsets();
5754
5
    }
5755
5756
61
    const std::string task_name = "recycle_rowsets";
5757
61
    int64_t num_scanned = 0;
5758
61
    int64_t num_expired = 0;
5759
61
    int64_t num_prepare = 0;
5760
61
    int64_t num_compacted = 0;
5761
61
    int64_t num_empty_rowset = 0;
5762
61
    size_t total_rowset_key_size = 0;
5763
61
    size_t total_rowset_value_size = 0;
5764
61
    size_t expired_rowset_size = 0;
5765
61
    std::atomic_long num_recycled = 0;
5766
61
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5767
5768
61
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5769
61
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5770
61
    std::string recyc_rs_key0;
5771
61
    std::string recyc_rs_key1;
5772
61
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5773
61
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5774
5775
61
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5776
5777
61
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5778
61
    register_recycle_task(task_name, start_time);
5779
5780
61
    DORIS_CLOUD_DEFER {
5781
61
        unregister_recycle_task(task_name);
5782
61
        int64_t cost =
5783
61
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5784
61
        metrics_context.finish_report();
5785
61
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5786
61
                .tag("instance_id", instance_id_)
5787
61
                .tag("num_scanned", num_scanned)
5788
61
                .tag("num_expired", num_expired)
5789
61
                .tag("num_recycled", num_recycled)
5790
61
                .tag("num_recycled.prepare", num_prepare)
5791
61
                .tag("num_recycled.compacted", num_compacted)
5792
61
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5793
61
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5794
61
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5795
61
                .tag("expired_rowset_meta_size", expired_rowset_size);
5796
61
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5780
7
    DORIS_CLOUD_DEFER {
5781
7
        unregister_recycle_task(task_name);
5782
7
        int64_t cost =
5783
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5784
7
        metrics_context.finish_report();
5785
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5786
7
                .tag("instance_id", instance_id_)
5787
7
                .tag("num_scanned", num_scanned)
5788
7
                .tag("num_expired", num_expired)
5789
7
                .tag("num_recycled", num_recycled)
5790
7
                .tag("num_recycled.prepare", num_prepare)
5791
7
                .tag("num_recycled.compacted", num_compacted)
5792
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5793
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5794
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5795
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5796
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5780
54
    DORIS_CLOUD_DEFER {
5781
54
        unregister_recycle_task(task_name);
5782
54
        int64_t cost =
5783
54
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5784
54
        metrics_context.finish_report();
5785
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5786
54
                .tag("instance_id", instance_id_)
5787
54
                .tag("num_scanned", num_scanned)
5788
54
                .tag("num_expired", num_expired)
5789
54
                .tag("num_recycled", num_recycled)
5790
54
                .tag("num_recycled.prepare", num_prepare)
5791
54
                .tag("num_recycled.compacted", num_compacted)
5792
54
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5793
54
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5794
54
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5795
54
                .tag("expired_rowset_meta_size", expired_rowset_size);
5796
54
    };
5797
5798
61
    std::vector<std::string> rowset_keys;
5799
61
    std::vector<std::string> rowset_keys_to_mark_recycled;
5800
61
    std::vector<std::string> rowset_keys_to_abort_job;
5801
    // rowset_id -> rowset_meta
5802
    // store rowset id and meta for statistics rs size when delete
5803
61
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5804
5805
61
    std::mutex async_recycled_rowset_keys_mutex;
5806
61
    std::vector<std::string> async_recycled_rowset_keys;
5807
61
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5808
61
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5809
61
    worker_pool->start();
5810
61
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5811
61
                                            int64_t partition_id, int64_t tablet_id,
5812
30.9k
                                            const std::string& rowset_id) {
5813
        // Try to delete rowset data in background thread
5814
30.9k
        int ret = worker_pool->submit_with_timeout(
5815
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5816
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5817
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5818
0
                        return;
5819
0
                    }
5820
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5821
28.4k
                        0) {
5822
0
                        return;
5823
0
                    }
5824
28.4k
                    std::vector<std::string> keys;
5825
28.4k
                    {
5826
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5827
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5828
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5829
278
                            keys.swap(async_recycled_rowset_keys);
5830
278
                        }
5831
28.4k
                    }
5832
28.4k
                    if (keys.empty()) return;
5833
285
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5834
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5835
0
                                     << instance_id_;
5836
285
                    } else {
5837
285
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5838
285
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5839
285
                                           num_recycled, start_time);
5840
285
                    }
5841
285
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5815
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5816
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5817
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5818
0
                        return;
5819
0
                    }
5820
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5821
1
                        0) {
5822
0
                        return;
5823
0
                    }
5824
1
                    std::vector<std::string> keys;
5825
1
                    {
5826
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5827
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5828
1
                        if (async_recycled_rowset_keys.size() > 100) {
5829
0
                            keys.swap(async_recycled_rowset_keys);
5830
0
                        }
5831
1
                    }
5832
1
                    if (keys.empty()) return;
5833
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5834
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5835
0
                                     << instance_id_;
5836
0
                    } else {
5837
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5838
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5839
0
                                           num_recycled, start_time);
5840
0
                    }
5841
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5815
28.4k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5816
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5817
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5818
0
                        return;
5819
0
                    }
5820
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5821
28.4k
                        0) {
5822
0
                        return;
5823
0
                    }
5824
28.4k
                    std::vector<std::string> keys;
5825
28.4k
                    {
5826
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5827
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5828
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5829
278
                            keys.swap(async_recycled_rowset_keys);
5830
278
                        }
5831
28.4k
                    }
5832
28.4k
                    if (keys.empty()) return;
5833
285
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5834
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5835
0
                                     << instance_id_;
5836
285
                    } else {
5837
285
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5838
285
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5839
285
                                           num_recycled, start_time);
5840
285
                    }
5841
285
                },
5842
30.9k
                0);
5843
30.9k
        if (ret == 0) return 0;
5844
        // Submit task failed, delete rowset data in current thread
5845
2.42k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5846
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5847
0
            return -1;
5848
0
        }
5849
2.42k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5850
0
            return -1;
5851
0
        }
5852
2.42k
        rowset_keys.push_back(std::move(key));
5853
2.42k
        return 0;
5854
2.42k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5812
1
                                            const std::string& rowset_id) {
5813
        // Try to delete rowset data in background thread
5814
1
        int ret = worker_pool->submit_with_timeout(
5815
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5816
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5817
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5818
1
                        return;
5819
1
                    }
5820
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5821
1
                        0) {
5822
1
                        return;
5823
1
                    }
5824
1
                    std::vector<std::string> keys;
5825
1
                    {
5826
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5827
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5828
1
                        if (async_recycled_rowset_keys.size() > 100) {
5829
1
                            keys.swap(async_recycled_rowset_keys);
5830
1
                        }
5831
1
                    }
5832
1
                    if (keys.empty()) return;
5833
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5834
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5835
1
                                     << instance_id_;
5836
1
                    } else {
5837
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5838
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5839
1
                                           num_recycled, start_time);
5840
1
                    }
5841
1
                },
5842
1
                0);
5843
1
        if (ret == 0) return 0;
5844
        // Submit task failed, delete rowset data in current thread
5845
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5846
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5847
0
            return -1;
5848
0
        }
5849
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5850
0
            return -1;
5851
0
        }
5852
0
        rowset_keys.push_back(std::move(key));
5853
0
        return 0;
5854
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5812
30.9k
                                            const std::string& rowset_id) {
5813
        // Try to delete rowset data in background thread
5814
30.9k
        int ret = worker_pool->submit_with_timeout(
5815
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5816
30.9k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5817
30.9k
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5818
30.9k
                        return;
5819
30.9k
                    }
5820
30.9k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5821
30.9k
                        0) {
5822
30.9k
                        return;
5823
30.9k
                    }
5824
30.9k
                    std::vector<std::string> keys;
5825
30.9k
                    {
5826
30.9k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5827
30.9k
                        async_recycled_rowset_keys.push_back(std::move(key));
5828
30.9k
                        if (async_recycled_rowset_keys.size() > 100) {
5829
30.9k
                            keys.swap(async_recycled_rowset_keys);
5830
30.9k
                        }
5831
30.9k
                    }
5832
30.9k
                    if (keys.empty()) return;
5833
30.9k
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5834
30.9k
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5835
30.9k
                                     << instance_id_;
5836
30.9k
                    } else {
5837
30.9k
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5838
30.9k
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5839
30.9k
                                           num_recycled, start_time);
5840
30.9k
                    }
5841
30.9k
                },
5842
30.9k
                0);
5843
30.9k
        if (ret == 0) return 0;
5844
        // Submit task failed, delete rowset data in current thread
5845
2.42k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5846
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5847
0
            return -1;
5848
0
        }
5849
2.42k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5850
0
            return -1;
5851
0
        }
5852
2.42k
        rowset_keys.push_back(std::move(key));
5853
2.42k
        return 0;
5854
2.42k
    };
5855
5856
61
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5857
5858
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5859
124k
        ++num_scanned;
5860
124k
        total_rowset_key_size += k.size();
5861
124k
        total_rowset_value_size += v.size();
5862
124k
        RecycleRowsetPB rowset;
5863
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5864
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5865
0
            return -1;
5866
0
        }
5867
5868
124k
        int64_t current_time = ::time(nullptr);
5869
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5870
5871
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5872
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5873
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5874
124k
        if (current_time < expiration) { // not expired
5875
0
            return 0;
5876
0
        }
5877
124k
        ++num_expired;
5878
124k
        expired_rowset_size += v.size();
5879
5880
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5881
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5882
                // in old version, keep this key-value pair and it needs to be checked manually
5883
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5884
0
                return -1;
5885
0
            }
5886
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5887
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5888
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5889
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5890
10.0k
                rowset_keys.emplace_back(k);
5891
10.0k
                return 0;
5892
10.0k
            }
5893
            // decode rowset_id
5894
10.2k
            auto k1 = k;
5895
10.2k
            k1.remove_prefix(1);
5896
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5897
10.2k
            decode_key(&k1, &out);
5898
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5899
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5900
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5901
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5902
10.2k
                      << " task_type=" << metrics_context.operation_type;
5903
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5904
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5905
0
                return -1;
5906
0
            }
5907
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5908
10.2k
            metrics_context.total_recycled_num++;
5909
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5910
10.2k
                    rowset.rowset_meta().total_disk_size();
5911
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5912
10.2k
            return 0;
5913
10.2k
        }
5914
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5915
5916
        // TODO(plat1ko): check rowset not referenced
5917
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5918
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5919
0
                LOG_INFO("recycle rowset that has empty resource id");
5920
0
            } else {
5921
                // other situations, keep this key-value pair and it needs to be checked manually
5922
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5923
0
                return -1;
5924
0
            }
5925
0
        }
5926
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5927
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5928
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5929
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5930
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5931
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5932
104k
                  << " rowset_meta_size=" << v.size()
5933
104k
                  << " creation_time=" << rowset_meta->creation_time()
5934
104k
                  << " task_type=" << metrics_context.operation_type;
5935
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5936
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5937
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5938
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5939
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5940
20.0k
                                 "kv "
5941
20.0k
                                 "at next turn, instance_id="
5942
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5943
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5944
20.0k
                              << rowset_meta->end_version() << "]";
5945
20.0k
                    return 0;
5946
20.0k
                }
5947
50.0k
            }
5948
5949
30.9k
            num_prepare += 1;
5950
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5951
30.9k
                rowset_meta->end_version() != 1) {
5952
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5953
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5954
10.2k
                                 "instance_id="
5955
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5956
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5957
10.2k
                              << rowset_meta->end_version() << "]";
5958
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5959
10.2k
                    return 0;
5960
10.2k
                }
5961
30.2k
            }
5962
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5963
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5964
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5965
0
                return -1;
5966
0
            }
5967
53.1k
        } else {
5968
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5969
53.1k
            rowset_keys.emplace_back(k);
5970
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5971
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5972
53.1k
                ++num_empty_rowset;
5973
53.1k
            }
5974
53.1k
        }
5975
73.7k
        return 0;
5976
104k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5858
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5859
7
        ++num_scanned;
5860
7
        total_rowset_key_size += k.size();
5861
7
        total_rowset_value_size += v.size();
5862
7
        RecycleRowsetPB rowset;
5863
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5864
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5865
0
            return -1;
5866
0
        }
5867
5868
7
        int64_t current_time = ::time(nullptr);
5869
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5870
5871
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5872
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5873
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5874
7
        if (current_time < expiration) { // not expired
5875
0
            return 0;
5876
0
        }
5877
7
        ++num_expired;
5878
7
        expired_rowset_size += v.size();
5879
5880
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5881
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5882
                // in old version, keep this key-value pair and it needs to be checked manually
5883
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5884
0
                return -1;
5885
0
            }
5886
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5887
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5888
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5889
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5890
0
                rowset_keys.emplace_back(k);
5891
0
                return 0;
5892
0
            }
5893
            // decode rowset_id
5894
0
            auto k1 = k;
5895
0
            k1.remove_prefix(1);
5896
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5897
0
            decode_key(&k1, &out);
5898
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5899
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5900
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5901
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5902
0
                      << " task_type=" << metrics_context.operation_type;
5903
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5904
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5905
0
                return -1;
5906
0
            }
5907
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5908
0
            metrics_context.total_recycled_num++;
5909
0
            segment_metrics_context_.total_recycled_data_size +=
5910
0
                    rowset.rowset_meta().total_disk_size();
5911
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5912
0
            return 0;
5913
0
        }
5914
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5915
5916
        // TODO(plat1ko): check rowset not referenced
5917
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5918
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5919
0
                LOG_INFO("recycle rowset that has empty resource id");
5920
0
            } else {
5921
                // other situations, keep this key-value pair and it needs to be checked manually
5922
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5923
0
                return -1;
5924
0
            }
5925
0
        }
5926
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5927
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5928
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5929
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5930
7
                  << "] txn_id=" << rowset_meta->txn_id()
5931
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5932
7
                  << " rowset_meta_size=" << v.size()
5933
7
                  << " creation_time=" << rowset_meta->creation_time()
5934
7
                  << " task_type=" << metrics_context.operation_type;
5935
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5936
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5937
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5938
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5939
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5940
4
                                 "kv "
5941
4
                                 "at next turn, instance_id="
5942
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5943
4
                              << " version=[" << rowset_meta->start_version() << '-'
5944
4
                              << rowset_meta->end_version() << "]";
5945
4
                    return 0;
5946
4
                }
5947
6
            }
5948
5949
3
            num_prepare += 1;
5950
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5951
3
                rowset_meta->end_version() != 1) {
5952
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5953
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5954
2
                                 "instance_id="
5955
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5956
2
                              << " version=[" << rowset_meta->start_version() << '-'
5957
2
                              << rowset_meta->end_version() << "]";
5958
2
                    rowset_keys_to_abort_job.emplace_back(k);
5959
2
                    return 0;
5960
2
                }
5961
2
            }
5962
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5963
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5964
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5965
0
                return -1;
5966
0
            }
5967
1
        } else {
5968
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5969
0
            rowset_keys.emplace_back(k);
5970
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5971
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5972
0
                ++num_empty_rowset;
5973
0
            }
5974
0
        }
5975
1
        return 0;
5976
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5858
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5859
124k
        ++num_scanned;
5860
124k
        total_rowset_key_size += k.size();
5861
124k
        total_rowset_value_size += v.size();
5862
124k
        RecycleRowsetPB rowset;
5863
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5864
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5865
0
            return -1;
5866
0
        }
5867
5868
124k
        int64_t current_time = ::time(nullptr);
5869
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5870
5871
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5872
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5873
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5874
124k
        if (current_time < expiration) { // not expired
5875
0
            return 0;
5876
0
        }
5877
124k
        ++num_expired;
5878
124k
        expired_rowset_size += v.size();
5879
5880
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5881
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5882
                // in old version, keep this key-value pair and it needs to be checked manually
5883
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5884
0
                return -1;
5885
0
            }
5886
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5887
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5888
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5889
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5890
10.0k
                rowset_keys.emplace_back(k);
5891
10.0k
                return 0;
5892
10.0k
            }
5893
            // decode rowset_id
5894
10.2k
            auto k1 = k;
5895
10.2k
            k1.remove_prefix(1);
5896
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5897
10.2k
            decode_key(&k1, &out);
5898
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5899
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5900
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5901
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5902
10.2k
                      << " task_type=" << metrics_context.operation_type;
5903
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5904
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5905
0
                return -1;
5906
0
            }
5907
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5908
10.2k
            metrics_context.total_recycled_num++;
5909
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5910
10.2k
                    rowset.rowset_meta().total_disk_size();
5911
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5912
10.2k
            return 0;
5913
10.2k
        }
5914
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5915
5916
        // TODO(plat1ko): check rowset not referenced
5917
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5918
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5919
0
                LOG_INFO("recycle rowset that has empty resource id");
5920
0
            } else {
5921
                // other situations, keep this key-value pair and it needs to be checked manually
5922
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5923
0
                return -1;
5924
0
            }
5925
0
        }
5926
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5927
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5928
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5929
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5930
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5931
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5932
104k
                  << " rowset_meta_size=" << v.size()
5933
104k
                  << " creation_time=" << rowset_meta->creation_time()
5934
104k
                  << " task_type=" << metrics_context.operation_type;
5935
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5936
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5937
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5938
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5939
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5940
20.0k
                                 "kv "
5941
20.0k
                                 "at next turn, instance_id="
5942
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5943
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5944
20.0k
                              << rowset_meta->end_version() << "]";
5945
20.0k
                    return 0;
5946
20.0k
                }
5947
50.0k
            }
5948
5949
30.9k
            num_prepare += 1;
5950
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5951
30.9k
                rowset_meta->end_version() != 1) {
5952
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5953
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5954
10.2k
                                 "instance_id="
5955
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5956
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5957
10.2k
                              << rowset_meta->end_version() << "]";
5958
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5959
10.2k
                    return 0;
5960
10.2k
                }
5961
30.2k
            }
5962
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5963
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5964
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5965
0
                return -1;
5966
0
            }
5967
53.1k
        } else {
5968
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5969
53.1k
            rowset_keys.emplace_back(k);
5970
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5971
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5972
53.1k
                ++num_empty_rowset;
5973
53.1k
            }
5974
53.1k
        }
5975
73.7k
        return 0;
5976
104k
    };
5977
5978
390
    auto loop_done = [&]() -> int {
5979
390
        std::vector<std::string> rowset_keys_to_delete;
5980
        // rowset_id -> rowset_meta
5981
        // store rowset id and meta for statistics rs size when delete
5982
390
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5983
390
        std::vector<std::string> mark_keys_to_process;
5984
390
        std::vector<std::string> abort_job_keys_to_process;
5985
390
        rowset_keys_to_delete.swap(rowset_keys);
5986
390
        rowsets_to_delete.swap(rowsets);
5987
390
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5988
390
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5989
390
        if (!mark_keys_to_process.empty()) {
5990
69
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5991
69
                    *worker_pool, std::move(mark_keys_to_process));
5992
69
        }
5993
390
        if (!abort_job_keys_to_process.empty()) {
5994
46
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5995
46
                                               &num_recycled);
5996
46
        }
5997
390
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5998
390
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5999
390
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6000
390
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6001
390
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6002
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6003
0
                return;
6004
0
            }
6005
390
            if (!versioned_delete_bitmap_key_groups.empty() &&
6006
390
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6007
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
6008
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6009
0
                             << instance_id_;
6010
0
                return;
6011
0
            }
6012
390
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6013
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6014
0
                return;
6015
0
            }
6016
390
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6017
390
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5998
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5999
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6000
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6001
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6002
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6003
0
                return;
6004
0
            }
6005
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
6006
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6007
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
6008
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6009
0
                             << instance_id_;
6010
0
                return;
6011
0
            }
6012
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6013
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6014
0
                return;
6015
0
            }
6016
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6017
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5998
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5999
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6000
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6001
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6002
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6003
0
                return;
6004
0
            }
6005
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
6006
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6007
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
6008
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6009
0
                             << instance_id_;
6010
0
                return;
6011
0
            }
6012
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6013
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6014
0
                return;
6015
0
            }
6016
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6017
383
        });
6018
390
        return 0;
6019
390
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5978
7
    auto loop_done = [&]() -> int {
5979
7
        std::vector<std::string> rowset_keys_to_delete;
5980
        // rowset_id -> rowset_meta
5981
        // store rowset id and meta for statistics rs size when delete
5982
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5983
7
        std::vector<std::string> mark_keys_to_process;
5984
7
        std::vector<std::string> abort_job_keys_to_process;
5985
7
        rowset_keys_to_delete.swap(rowset_keys);
5986
7
        rowsets_to_delete.swap(rowsets);
5987
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5988
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5989
7
        if (!mark_keys_to_process.empty()) {
5990
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5991
4
                    *worker_pool, std::move(mark_keys_to_process));
5992
4
        }
5993
7
        if (!abort_job_keys_to_process.empty()) {
5994
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5995
2
                                               &num_recycled);
5996
2
        }
5997
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5998
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5999
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6000
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6001
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6002
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6003
7
                return;
6004
7
            }
6005
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
6006
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6007
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
6008
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6009
7
                             << instance_id_;
6010
7
                return;
6011
7
            }
6012
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6013
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6014
7
                return;
6015
7
            }
6016
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6017
7
        });
6018
7
        return 0;
6019
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5978
383
    auto loop_done = [&]() -> int {
5979
383
        std::vector<std::string> rowset_keys_to_delete;
5980
        // rowset_id -> rowset_meta
5981
        // store rowset id and meta for statistics rs size when delete
5982
383
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5983
383
        std::vector<std::string> mark_keys_to_process;
5984
383
        std::vector<std::string> abort_job_keys_to_process;
5985
383
        rowset_keys_to_delete.swap(rowset_keys);
5986
383
        rowsets_to_delete.swap(rowsets);
5987
383
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5988
383
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5989
383
        if (!mark_keys_to_process.empty()) {
5990
65
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5991
65
                    *worker_pool, std::move(mark_keys_to_process));
5992
65
        }
5993
383
        if (!abort_job_keys_to_process.empty()) {
5994
44
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5995
44
                                               &num_recycled);
5996
44
        }
5997
383
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5998
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5999
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
6000
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
6001
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
6002
383
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
6003
383
                return;
6004
383
            }
6005
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
6006
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
6007
383
                                                         versioned_delete_bitmap_key_groups) != 0) {
6008
383
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6009
383
                             << instance_id_;
6010
383
                return;
6011
383
            }
6012
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6013
383
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6014
383
                return;
6015
383
            }
6016
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6017
383
        });
6018
383
        return 0;
6019
383
    };
6020
6021
61
    if (config::enable_recycler_stats_metrics) {
6022
0
        scan_and_statistics_rowsets();
6023
0
    }
6024
    // recycle_func and loop_done for scan and recycle
6025
61
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6026
61
                               std::move(loop_done));
6027
6028
61
    worker_pool->stop();
6029
6030
61
    if (!async_recycled_rowset_keys.empty()) {
6031
9
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6032
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6033
0
            return -1;
6034
9
        } else {
6035
9
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6036
9
        }
6037
9
    }
6038
6039
    // Report final metrics after all concurrent tasks completed
6040
61
    segment_metrics_context_.report();
6041
61
    metrics_context.report();
6042
6043
61
    return ret;
6044
61
}
6045
6046
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
6047
0
                                                     int64_t tablet_id, std::string* next_key) {
6048
0
    DCHECK(next_key != nullptr);
6049
0
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
6050
0
        return -1;
6051
0
    }
6052
0
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
6053
0
    return 0;
6054
0
}
6055
6056
13
int InstanceRecycler::recycle_restore_jobs() {
6057
13
    const std::string task_name = "recycle_restore_jobs";
6058
13
    int64_t num_scanned = 0;
6059
13
    int64_t num_expired = 0;
6060
13
    int64_t num_recycled = 0;
6061
13
    int64_t num_aborted = 0;
6062
6063
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6064
6065
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6066
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6067
13
    std::string restore_job_key0;
6068
13
    std::string restore_job_key1;
6069
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6070
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6071
6072
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6073
6074
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6075
13
    register_recycle_task(task_name, start_time);
6076
6077
13
    DORIS_CLOUD_DEFER {
6078
13
        unregister_recycle_task(task_name);
6079
13
        int64_t cost =
6080
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6081
13
        metrics_context.finish_report();
6082
6083
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6084
13
                .tag("instance_id", instance_id_)
6085
13
                .tag("num_scanned", num_scanned)
6086
13
                .tag("num_expired", num_expired)
6087
13
                .tag("num_recycled", num_recycled)
6088
13
                .tag("num_aborted", num_aborted);
6089
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6077
13
    DORIS_CLOUD_DEFER {
6078
13
        unregister_recycle_task(task_name);
6079
13
        int64_t cost =
6080
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6081
13
        metrics_context.finish_report();
6082
6083
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6084
13
                .tag("instance_id", instance_id_)
6085
13
                .tag("num_scanned", num_scanned)
6086
13
                .tag("num_expired", num_expired)
6087
13
                .tag("num_recycled", num_recycled)
6088
13
                .tag("num_aborted", num_aborted);
6089
13
    };
6090
6091
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6092
6093
13
    std::vector<std::string_view> restore_job_keys;
6094
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6095
41
        ++num_scanned;
6096
41
        RestoreJobCloudPB restore_job_pb;
6097
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6098
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
41
        int64_t expiration =
6102
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6103
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6104
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6105
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6106
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6107
0
                   << " state=" << restore_job_pb.state();
6108
41
        int64_t current_time = ::time(nullptr);
6109
41
        if (current_time < expiration) { // not expired
6110
0
            return 0;
6111
0
        }
6112
41
        ++num_expired;
6113
6114
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6115
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6116
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6117
6118
41
        std::unique_ptr<Transaction> txn;
6119
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6120
41
        if (err != TxnErrorCode::TXN_OK) {
6121
0
            LOG_WARNING("failed to recycle restore job")
6122
0
                    .tag("err", err)
6123
0
                    .tag("tablet id", tablet_id)
6124
0
                    .tag("instance_id", instance_id_)
6125
0
                    .tag("reason", "failed to create txn");
6126
0
            return -1;
6127
0
        }
6128
6129
41
        std::string val;
6130
41
        err = txn->get(k, &val);
6131
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6132
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6133
0
            return 0;
6134
0
        }
6135
41
        if (err != TxnErrorCode::TXN_OK) {
6136
0
            LOG_WARNING("failed to get kv");
6137
0
            return -1;
6138
0
        }
6139
41
        restore_job_pb.Clear();
6140
41
        if (!restore_job_pb.ParseFromString(val)) {
6141
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6142
0
            return -1;
6143
0
        }
6144
6145
        // PREPARED or COMMITTED, change state to DROPPED and return
6146
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6147
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6148
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6149
0
            restore_job_pb.set_need_recycle_data(true);
6150
0
            txn->put(k, restore_job_pb.SerializeAsString());
6151
0
            err = txn->commit();
6152
0
            if (err != TxnErrorCode::TXN_OK) {
6153
0
                LOG_WARNING("failed to commit txn: {}", err);
6154
0
                return -1;
6155
0
            }
6156
0
            num_aborted++;
6157
0
            return 0;
6158
0
        }
6159
6160
        // Change state to RECYCLING
6161
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6162
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6163
21
            txn->put(k, restore_job_pb.SerializeAsString());
6164
21
            err = txn->commit();
6165
21
            if (err != TxnErrorCode::TXN_OK) {
6166
0
                LOG_WARNING("failed to commit txn: {}", err);
6167
0
                return -1;
6168
0
            }
6169
21
            return 0;
6170
21
        }
6171
6172
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6173
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6174
6175
        // Recycle all data associated with the restore job.
6176
        // This includes rowsets, segments, and related resources.
6177
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6178
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6179
0
            LOG_WARNING("failed to recycle tablet")
6180
0
                    .tag("tablet_id", tablet_id)
6181
0
                    .tag("instance_id", instance_id_);
6182
0
            return -1;
6183
0
        }
6184
6185
        // delete all restore job rowset kv
6186
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6187
6188
20
        err = txn->commit();
6189
20
        if (err != TxnErrorCode::TXN_OK) {
6190
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6191
0
                    .tag("err", err)
6192
0
                    .tag("tablet id", tablet_id)
6193
0
                    .tag("instance_id", instance_id_)
6194
0
                    .tag("reason", "failed to commit txn");
6195
0
            return -1;
6196
0
        }
6197
6198
20
        metrics_context.total_recycled_num = ++num_recycled;
6199
20
        metrics_context.report();
6200
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6201
20
        restore_job_keys.push_back(k);
6202
6203
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6204
20
                  << " tablet_id=" << tablet_id;
6205
20
        return 0;
6206
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
6094
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6095
41
        ++num_scanned;
6096
41
        RestoreJobCloudPB restore_job_pb;
6097
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6098
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6099
0
            return -1;
6100
0
        }
6101
41
        int64_t expiration =
6102
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6103
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6104
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6105
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6106
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6107
0
                   << " state=" << restore_job_pb.state();
6108
41
        int64_t current_time = ::time(nullptr);
6109
41
        if (current_time < expiration) { // not expired
6110
0
            return 0;
6111
0
        }
6112
41
        ++num_expired;
6113
6114
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6115
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6116
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6117
6118
41
        std::unique_ptr<Transaction> txn;
6119
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6120
41
        if (err != TxnErrorCode::TXN_OK) {
6121
0
            LOG_WARNING("failed to recycle restore job")
6122
0
                    .tag("err", err)
6123
0
                    .tag("tablet id", tablet_id)
6124
0
                    .tag("instance_id", instance_id_)
6125
0
                    .tag("reason", "failed to create txn");
6126
0
            return -1;
6127
0
        }
6128
6129
41
        std::string val;
6130
41
        err = txn->get(k, &val);
6131
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6132
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6133
0
            return 0;
6134
0
        }
6135
41
        if (err != TxnErrorCode::TXN_OK) {
6136
0
            LOG_WARNING("failed to get kv");
6137
0
            return -1;
6138
0
        }
6139
41
        restore_job_pb.Clear();
6140
41
        if (!restore_job_pb.ParseFromString(val)) {
6141
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6142
0
            return -1;
6143
0
        }
6144
6145
        // PREPARED or COMMITTED, change state to DROPPED and return
6146
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6147
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6148
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6149
0
            restore_job_pb.set_need_recycle_data(true);
6150
0
            txn->put(k, restore_job_pb.SerializeAsString());
6151
0
            err = txn->commit();
6152
0
            if (err != TxnErrorCode::TXN_OK) {
6153
0
                LOG_WARNING("failed to commit txn: {}", err);
6154
0
                return -1;
6155
0
            }
6156
0
            num_aborted++;
6157
0
            return 0;
6158
0
        }
6159
6160
        // Change state to RECYCLING
6161
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6162
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6163
21
            txn->put(k, restore_job_pb.SerializeAsString());
6164
21
            err = txn->commit();
6165
21
            if (err != TxnErrorCode::TXN_OK) {
6166
0
                LOG_WARNING("failed to commit txn: {}", err);
6167
0
                return -1;
6168
0
            }
6169
21
            return 0;
6170
21
        }
6171
6172
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6173
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6174
6175
        // Recycle all data associated with the restore job.
6176
        // This includes rowsets, segments, and related resources.
6177
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6178
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6179
0
            LOG_WARNING("failed to recycle tablet")
6180
0
                    .tag("tablet_id", tablet_id)
6181
0
                    .tag("instance_id", instance_id_);
6182
0
            return -1;
6183
0
        }
6184
6185
        // delete all restore job rowset kv
6186
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6187
6188
20
        err = txn->commit();
6189
20
        if (err != TxnErrorCode::TXN_OK) {
6190
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6191
0
                    .tag("err", err)
6192
0
                    .tag("tablet id", tablet_id)
6193
0
                    .tag("instance_id", instance_id_)
6194
0
                    .tag("reason", "failed to commit txn");
6195
0
            return -1;
6196
0
        }
6197
6198
20
        metrics_context.total_recycled_num = ++num_recycled;
6199
20
        metrics_context.report();
6200
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6201
20
        restore_job_keys.push_back(k);
6202
6203
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6204
20
                  << " tablet_id=" << tablet_id;
6205
20
        return 0;
6206
20
    };
6207
6208
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6209
3
        if (restore_job_keys.empty()) return 0;
6210
1
        DORIS_CLOUD_DEFER {
6211
1
            restore_job_keys.clear();
6212
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6210
1
        DORIS_CLOUD_DEFER {
6211
1
            restore_job_keys.clear();
6212
1
        };
6213
6214
1
        std::unique_ptr<Transaction> txn;
6215
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6216
1
        if (err != TxnErrorCode::TXN_OK) {
6217
0
            LOG_WARNING("failed to recycle restore job")
6218
0
                    .tag("err", err)
6219
0
                    .tag("instance_id", instance_id_)
6220
0
                    .tag("reason", "failed to create txn");
6221
0
            return -1;
6222
0
        }
6223
20
        for (auto& k : restore_job_keys) {
6224
20
            txn->remove(k);
6225
20
        }
6226
1
        err = txn->commit();
6227
1
        if (err != TxnErrorCode::TXN_OK) {
6228
0
            LOG_WARNING("failed to recycle restore job")
6229
0
                    .tag("err", err)
6230
0
                    .tag("instance_id", instance_id_)
6231
0
                    .tag("reason", "failed to commit txn");
6232
0
            return -1;
6233
0
        }
6234
1
        return 0;
6235
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6208
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6209
3
        if (restore_job_keys.empty()) return 0;
6210
1
        DORIS_CLOUD_DEFER {
6211
1
            restore_job_keys.clear();
6212
1
        };
6213
6214
1
        std::unique_ptr<Transaction> txn;
6215
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6216
1
        if (err != TxnErrorCode::TXN_OK) {
6217
0
            LOG_WARNING("failed to recycle restore job")
6218
0
                    .tag("err", err)
6219
0
                    .tag("instance_id", instance_id_)
6220
0
                    .tag("reason", "failed to create txn");
6221
0
            return -1;
6222
0
        }
6223
20
        for (auto& k : restore_job_keys) {
6224
20
            txn->remove(k);
6225
20
        }
6226
1
        err = txn->commit();
6227
1
        if (err != TxnErrorCode::TXN_OK) {
6228
0
            LOG_WARNING("failed to recycle restore job")
6229
0
                    .tag("err", err)
6230
0
                    .tag("instance_id", instance_id_)
6231
0
                    .tag("reason", "failed to commit txn");
6232
0
            return -1;
6233
0
        }
6234
1
        return 0;
6235
1
    };
6236
6237
13
    if (config::enable_recycler_stats_metrics) {
6238
0
        scan_and_statistics_restore_jobs();
6239
0
    }
6240
6241
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6242
13
                            std::move(loop_done));
6243
13
}
6244
6245
11
int InstanceRecycler::recycle_versioned_rowsets() {
6246
11
    const std::string task_name = "recycle_rowsets";
6247
11
    int64_t num_scanned = 0;
6248
11
    int64_t num_expired = 0;
6249
11
    int64_t num_prepare = 0;
6250
11
    int64_t num_compacted = 0;
6251
11
    int64_t num_empty_rowset = 0;
6252
11
    size_t total_rowset_key_size = 0;
6253
11
    size_t total_rowset_value_size = 0;
6254
11
    size_t expired_rowset_size = 0;
6255
11
    std::atomic_long num_recycled = 0;
6256
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6257
6258
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6259
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6260
11
    std::string recyc_rs_key0;
6261
11
    std::string recyc_rs_key1;
6262
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6263
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6264
6265
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6266
6267
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6268
11
    register_recycle_task(task_name, start_time);
6269
6270
11
    DORIS_CLOUD_DEFER {
6271
11
        unregister_recycle_task(task_name);
6272
11
        int64_t cost =
6273
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6274
11
        metrics_context.finish_report();
6275
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6276
11
                .tag("instance_id", instance_id_)
6277
11
                .tag("num_scanned", num_scanned)
6278
11
                .tag("num_expired", num_expired)
6279
11
                .tag("num_recycled", num_recycled)
6280
11
                .tag("num_recycled.prepare", num_prepare)
6281
11
                .tag("num_recycled.compacted", num_compacted)
6282
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6283
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6284
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6285
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6286
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6270
11
    DORIS_CLOUD_DEFER {
6271
11
        unregister_recycle_task(task_name);
6272
11
        int64_t cost =
6273
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6274
11
        metrics_context.finish_report();
6275
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6276
11
                .tag("instance_id", instance_id_)
6277
11
                .tag("num_scanned", num_scanned)
6278
11
                .tag("num_expired", num_expired)
6279
11
                .tag("num_recycled", num_recycled)
6280
11
                .tag("num_recycled.prepare", num_prepare)
6281
11
                .tag("num_recycled.compacted", num_compacted)
6282
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6283
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6284
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6285
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6286
11
    };
6287
6288
11
    std::vector<std::string> orphan_rowset_keys;
6289
6290
    // Store keys of rowset recycled by background workers
6291
11
    std::mutex async_recycled_rowset_keys_mutex;
6292
11
    std::vector<std::string> async_recycled_rowset_keys;
6293
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6294
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6295
11
    worker_pool->start();
6296
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6297
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6298
        // Try to delete rowset data in background thread
6299
400
        int ret = worker_pool->submit_with_timeout(
6300
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6301
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6302
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6303
400
                        return;
6304
400
                    }
6305
                    // The async recycled rowsets are staled format or has not been used,
6306
                    // so we don't need to check the rowset ref count key.
6307
0
                    std::vector<std::string> keys;
6308
0
                    {
6309
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6310
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6311
0
                        if (async_recycled_rowset_keys.size() > 100) {
6312
0
                            keys.swap(async_recycled_rowset_keys);
6313
0
                        }
6314
0
                    }
6315
0
                    if (keys.empty()) return;
6316
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6317
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6318
0
                                     << instance_id_;
6319
0
                    } else {
6320
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6321
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6322
0
                                           num_recycled, start_time);
6323
0
                    }
6324
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
6300
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6301
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6302
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6303
400
                        return;
6304
400
                    }
6305
                    // The async recycled rowsets are staled format or has not been used,
6306
                    // so we don't need to check the rowset ref count key.
6307
0
                    std::vector<std::string> keys;
6308
0
                    {
6309
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6310
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6311
0
                        if (async_recycled_rowset_keys.size() > 100) {
6312
0
                            keys.swap(async_recycled_rowset_keys);
6313
0
                        }
6314
0
                    }
6315
0
                    if (keys.empty()) return;
6316
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6317
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6318
0
                                     << instance_id_;
6319
0
                    } else {
6320
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6321
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6322
0
                                           num_recycled, start_time);
6323
0
                    }
6324
0
                },
6325
400
                0);
6326
400
        if (ret == 0) return 0;
6327
        // Submit task failed, delete rowset data in current thread
6328
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6329
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6330
0
            return -1;
6331
0
        }
6332
0
        orphan_rowset_keys.push_back(std::move(key));
6333
0
        return 0;
6334
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
6297
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6298
        // Try to delete rowset data in background thread
6299
400
        int ret = worker_pool->submit_with_timeout(
6300
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6301
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6302
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6303
400
                        return;
6304
400
                    }
6305
                    // The async recycled rowsets are staled format or has not been used,
6306
                    // so we don't need to check the rowset ref count key.
6307
400
                    std::vector<std::string> keys;
6308
400
                    {
6309
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6310
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6311
400
                        if (async_recycled_rowset_keys.size() > 100) {
6312
400
                            keys.swap(async_recycled_rowset_keys);
6313
400
                        }
6314
400
                    }
6315
400
                    if (keys.empty()) return;
6316
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6317
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6318
400
                                     << instance_id_;
6319
400
                    } else {
6320
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6321
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6322
400
                                           num_recycled, start_time);
6323
400
                    }
6324
400
                },
6325
400
                0);
6326
400
        if (ret == 0) return 0;
6327
        // Submit task failed, delete rowset data in current thread
6328
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6329
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6330
0
            return -1;
6331
0
        }
6332
0
        orphan_rowset_keys.push_back(std::move(key));
6333
0
        return 0;
6334
0
    };
6335
6336
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6337
6338
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6339
2.01k
        ++num_scanned;
6340
2.01k
        total_rowset_key_size += k.size();
6341
2.01k
        total_rowset_value_size += v.size();
6342
2.01k
        RecycleRowsetPB rowset;
6343
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6344
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6345
0
            return -1;
6346
0
        }
6347
6348
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6349
6350
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6351
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6352
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6353
2.01k
        int64_t current_time = ::time(nullptr);
6354
2.01k
        if (current_time < final_expiration) { // not expired
6355
0
            return 0;
6356
0
        }
6357
2.01k
        ++num_expired;
6358
2.01k
        expired_rowset_size += v.size();
6359
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6360
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6361
                // in old version, keep this key-value pair and it needs to be checked manually
6362
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6363
0
                return -1;
6364
0
            }
6365
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6366
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6367
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6368
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6369
0
                orphan_rowset_keys.emplace_back(k);
6370
0
                return -1;
6371
0
            }
6372
            // decode rowset_id
6373
0
            auto k1 = k;
6374
0
            k1.remove_prefix(1);
6375
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6376
0
            decode_key(&k1, &out);
6377
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6378
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6379
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6380
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6381
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6382
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6383
0
                return -1;
6384
0
            }
6385
0
            return 0;
6386
0
        }
6387
        // TODO(plat1ko): check rowset not referenced
6388
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6389
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6390
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6391
0
                LOG_INFO("recycle rowset that has empty resource id");
6392
0
            } else {
6393
                // other situations, keep this key-value pair and it needs to be checked manually
6394
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6395
0
                return -1;
6396
0
            }
6397
0
        }
6398
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6399
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6400
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6401
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6402
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6403
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6404
2.01k
                  << " rowset_meta_size=" << v.size()
6405
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6406
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6407
            // unable to calculate file path, can only be deleted by rowset id prefix
6408
400
            num_prepare += 1;
6409
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6410
400
                                             rowset_meta->tablet_id(),
6411
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6412
0
                return -1;
6413
0
            }
6414
1.61k
        } else {
6415
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6416
1.61k
            worker_pool->submit(
6417
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6418
                        // The load & compact rowset keys are recycled during recycling operation logs.
6419
1.61k
                        RowsetDeleteTask task;
6420
1.61k
                        task.rowset_meta = rowset_meta;
6421
1.61k
                        task.recycle_rowset_key = k;
6422
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6423
1.59k
                            return;
6424
1.59k
                        }
6425
14
                        num_compacted += is_compacted;
6426
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6427
14
                        if (rowset_meta.num_segments() == 0) {
6428
0
                            ++num_empty_rowset;
6429
0
                        }
6430
14
                    });
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
6417
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6418
                        // The load & compact rowset keys are recycled during recycling operation logs.
6419
1.61k
                        RowsetDeleteTask task;
6420
1.61k
                        task.rowset_meta = rowset_meta;
6421
1.61k
                        task.recycle_rowset_key = k;
6422
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6423
1.59k
                            return;
6424
1.59k
                        }
6425
14
                        num_compacted += is_compacted;
6426
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6427
14
                        if (rowset_meta.num_segments() == 0) {
6428
0
                            ++num_empty_rowset;
6429
0
                        }
6430
14
                    });
6431
1.61k
        }
6432
2.01k
        return 0;
6433
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
6338
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6339
2.01k
        ++num_scanned;
6340
2.01k
        total_rowset_key_size += k.size();
6341
2.01k
        total_rowset_value_size += v.size();
6342
2.01k
        RecycleRowsetPB rowset;
6343
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6344
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6345
0
            return -1;
6346
0
        }
6347
6348
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6349
6350
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6351
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6352
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6353
2.01k
        int64_t current_time = ::time(nullptr);
6354
2.01k
        if (current_time < final_expiration) { // not expired
6355
0
            return 0;
6356
0
        }
6357
2.01k
        ++num_expired;
6358
2.01k
        expired_rowset_size += v.size();
6359
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6360
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6361
                // in old version, keep this key-value pair and it needs to be checked manually
6362
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6363
0
                return -1;
6364
0
            }
6365
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6366
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6367
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6368
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6369
0
                orphan_rowset_keys.emplace_back(k);
6370
0
                return -1;
6371
0
            }
6372
            // decode rowset_id
6373
0
            auto k1 = k;
6374
0
            k1.remove_prefix(1);
6375
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6376
0
            decode_key(&k1, &out);
6377
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6378
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6379
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6380
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6381
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6382
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6383
0
                return -1;
6384
0
            }
6385
0
            return 0;
6386
0
        }
6387
        // TODO(plat1ko): check rowset not referenced
6388
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6389
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6390
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6391
0
                LOG_INFO("recycle rowset that has empty resource id");
6392
0
            } else {
6393
                // other situations, keep this key-value pair and it needs to be checked manually
6394
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6395
0
                return -1;
6396
0
            }
6397
0
        }
6398
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6399
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6400
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6401
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6402
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6403
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6404
2.01k
                  << " rowset_meta_size=" << v.size()
6405
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6406
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6407
            // unable to calculate file path, can only be deleted by rowset id prefix
6408
400
            num_prepare += 1;
6409
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6410
400
                                             rowset_meta->tablet_id(),
6411
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6412
0
                return -1;
6413
0
            }
6414
1.61k
        } else {
6415
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6416
1.61k
            worker_pool->submit(
6417
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6418
                        // The load & compact rowset keys are recycled during recycling operation logs.
6419
1.61k
                        RowsetDeleteTask task;
6420
1.61k
                        task.rowset_meta = rowset_meta;
6421
1.61k
                        task.recycle_rowset_key = k;
6422
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6423
1.61k
                            return;
6424
1.61k
                        }
6425
1.61k
                        num_compacted += is_compacted;
6426
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6427
1.61k
                        if (rowset_meta.num_segments() == 0) {
6428
1.61k
                            ++num_empty_rowset;
6429
1.61k
                        }
6430
1.61k
                    });
6431
1.61k
        }
6432
2.01k
        return 0;
6433
2.01k
    };
6434
6435
11
    if (config::enable_recycler_stats_metrics) {
6436
0
        scan_and_statistics_rowsets();
6437
0
    }
6438
6439
11
    auto loop_done = [&]() -> int {
6440
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6441
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6442
0
        }
6443
6
        orphan_rowset_keys.clear();
6444
6
        return 0;
6445
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6439
6
    auto loop_done = [&]() -> int {
6440
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6441
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6442
0
        }
6443
6
        orphan_rowset_keys.clear();
6444
6
        return 0;
6445
6
    };
6446
6447
    // recycle_func and loop_done for scan and recycle
6448
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6449
11
                               std::move(loop_done));
6450
6451
11
    worker_pool->stop();
6452
6453
11
    if (!async_recycled_rowset_keys.empty()) {
6454
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6455
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6456
0
            return -1;
6457
0
        } else {
6458
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6459
0
        }
6460
0
    }
6461
6462
    // Report final metrics after all concurrent tasks completed
6463
11
    segment_metrics_context_.report();
6464
11
    metrics_context.report();
6465
6466
11
    return ret;
6467
11
}
6468
6469
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6470
1.61k
    constexpr int MAX_RETRY = 10;
6471
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6472
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6473
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6474
1.61k
    std::string_view reference_instance_id = instance_id_;
6475
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6476
8
        reference_instance_id = rowset_meta.reference_instance_id();
6477
8
    }
6478
6479
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6480
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6481
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6482
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6483
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6484
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6485
1.61k
        std::unique_ptr<Transaction> txn;
6486
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6487
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6488
0
            LOG_WARNING("failed to create txn").tag("err", err);
6489
0
            return -1;
6490
0
        }
6491
6492
1.61k
        std::string rowset_ref_count_key =
6493
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6494
1.61k
        int64_t ref_count = 0;
6495
1.61k
        {
6496
1.61k
            std::string value;
6497
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6498
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6499
                // This is the old version rowset, we could recycle it directly.
6500
1.60k
                ref_count = 1;
6501
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6502
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6503
0
                return -1;
6504
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6505
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6506
0
                return -1;
6507
0
            }
6508
1.61k
        }
6509
6510
1.61k
        if (ref_count == 1) {
6511
            // It would not be added since it is recycling.
6512
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6513
1.60k
                LOG_WARNING("failed to delete rowset data");
6514
1.60k
                return -1;
6515
1.60k
            }
6516
6517
            // Reset the transaction to avoid timeout.
6518
10
            err = txn_kv_->create_txn(&txn);
6519
10
            if (err != TxnErrorCode::TXN_OK) {
6520
0
                LOG_WARNING("failed to create txn").tag("err", err);
6521
0
                return -1;
6522
0
            }
6523
10
            txn->remove(rowset_ref_count_key);
6524
10
            LOG_INFO("delete rowset data ref count key")
6525
10
                    .tag("txn_id", rowset_meta.txn_id())
6526
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6527
6528
10
            std::string dbm_start_key =
6529
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6530
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6531
10
                    {reference_instance_id, tablet_id, rowset_id,
6532
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6533
10
            txn->remove(dbm_start_key, dbm_end_key);
6534
10
            LOG_INFO("remove delete bitmap kv")
6535
10
                    .tag("begin", hex(dbm_start_key))
6536
10
                    .tag("end", hex(dbm_end_key));
6537
6538
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6539
10
                    {reference_instance_id, tablet_id, rowset_id});
6540
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6541
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6542
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6543
10
            LOG_INFO("remove versioned delete bitmap kv")
6544
10
                    .tag("begin", hex(versioned_dbm_start_key))
6545
10
                    .tag("end", hex(versioned_dbm_end_key));
6546
10
        } else {
6547
            // Decrease the rowset ref count.
6548
            //
6549
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6550
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6551
3
            txn->atomic_add(rowset_ref_count_key, -1);
6552
3
            LOG_INFO("decrease rowset data ref count")
6553
3
                    .tag("txn_id", rowset_meta.txn_id())
6554
3
                    .tag("ref_count", ref_count - 1)
6555
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6556
3
        }
6557
6558
13
        if (!task.versioned_rowset_key.empty()) {
6559
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6560
0
                                                          task.versionstamp);
6561
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6562
0
        }
6563
6564
13
        if (!task.non_versioned_rowset_key.empty()) {
6565
0
            txn->remove(task.non_versioned_rowset_key);
6566
0
            LOG_INFO("remove non versioned rowset key")
6567
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6568
0
        }
6569
6570
        // empty when recycle ref rowsets for deleted instance
6571
13
        if (!task.recycle_rowset_key.empty()) {
6572
13
            txn->remove(task.recycle_rowset_key);
6573
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6574
13
        }
6575
6576
13
        err = txn->commit();
6577
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6578
            // The rowset ref count key has been changed, we need to retry.
6579
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6580
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6581
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6582
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6583
0
            continue;
6584
13
        } else if (err != TxnErrorCode::TXN_OK) {
6585
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6586
0
            return -1;
6587
0
        }
6588
13
        LOG_INFO("recycle rowset meta and data success");
6589
13
        return 0;
6590
13
    }
6591
18.4E
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6592
18.4E
            .tag("tablet_id", tablet_id)
6593
18.4E
            .tag("rowset_id", rowset_id)
6594
18.4E
            .tag("retry", MAX_RETRY);
6595
18.4E
    return -1;
6596
1.61k
}
6597
6598
37
int InstanceRecycler::recycle_tmp_rowsets() {
6599
37
    const std::string task_name = "recycle_tmp_rowsets";
6600
37
    int64_t num_scanned = 0;
6601
37
    int64_t num_expired = 0;
6602
37
    std::atomic_long num_recycled = 0;
6603
37
    size_t expired_rowset_size = 0;
6604
37
    size_t total_rowset_key_size = 0;
6605
37
    size_t total_rowset_value_size = 0;
6606
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6607
6608
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6609
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6610
37
    std::string tmp_rs_key0;
6611
37
    std::string tmp_rs_key1;
6612
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6613
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6614
6615
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6616
6617
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6618
37
    register_recycle_task(task_name, start_time);
6619
6620
37
    DORIS_CLOUD_DEFER {
6621
37
        unregister_recycle_task(task_name);
6622
37
        int64_t cost =
6623
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
37
        metrics_context.finish_report();
6625
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6626
37
                .tag("instance_id", instance_id_)
6627
37
                .tag("num_scanned", num_scanned)
6628
37
                .tag("num_expired", num_expired)
6629
37
                .tag("num_recycled", num_recycled)
6630
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6631
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6632
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6633
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6620
12
    DORIS_CLOUD_DEFER {
6621
12
        unregister_recycle_task(task_name);
6622
12
        int64_t cost =
6623
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
12
        metrics_context.finish_report();
6625
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6626
12
                .tag("instance_id", instance_id_)
6627
12
                .tag("num_scanned", num_scanned)
6628
12
                .tag("num_expired", num_expired)
6629
12
                .tag("num_recycled", num_recycled)
6630
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6631
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6632
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6633
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6620
25
    DORIS_CLOUD_DEFER {
6621
25
        unregister_recycle_task(task_name);
6622
25
        int64_t cost =
6623
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6624
25
        metrics_context.finish_report();
6625
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6626
25
                .tag("instance_id", instance_id_)
6627
25
                .tag("num_scanned", num_scanned)
6628
25
                .tag("num_expired", num_expired)
6629
25
                .tag("num_recycled", num_recycled)
6630
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6631
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6632
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6633
25
    };
6634
6635
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6636
37
    std::vector<std::string> tmp_rowset_keys;
6637
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6638
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6639
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6640
6641
    // rowset_id -> rowset_meta
6642
    // store tmp_rowset id and meta for statistics rs size when delete
6643
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6644
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6645
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6646
37
    worker_pool->start();
6647
6648
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6649
6650
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6651
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6652
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6653
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6654
53.2k
                                    std::string_view k, std::string_view v) -> int {
6655
53.2k
        ++num_scanned;
6656
53.2k
        total_rowset_key_size += k.size();
6657
53.2k
        total_rowset_value_size += v.size();
6658
53.2k
        doris::RowsetMetaCloudPB rowset;
6659
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6660
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6661
0
            return -1;
6662
0
        }
6663
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6664
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6665
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6666
0
                   << " txn_expiration=" << rowset.txn_expiration()
6667
0
                   << " rowset_creation_time=" << rowset.creation_time();
6668
53.2k
        int64_t current_time = ::time(nullptr);
6669
53.2k
        if (current_time < expiration) { // not expired
6670
0
            return 0;
6671
0
        }
6672
53.2k
        ++num_expired;
6673
53.2k
        expired_rowset_size += v.size();
6674
53.2k
        if (!rowset.has_resource_id()) {
6675
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6676
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6677
0
                return -1;
6678
0
            }
6679
            // might be a delete pred rowset
6680
0
            tmp_rowset_keys.emplace_back(k);
6681
0
            return 0;
6682
0
        }
6683
6684
        // TODO(plat1ko): check rowset not referenced
6685
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6686
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6687
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6688
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6689
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6690
53.2k
                  << " num_expired=" << num_expired
6691
53.2k
                  << " task_type=" << metrics_context.operation_type;
6692
6693
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6694
16
            if (need_mark_rowset_as_recycled(rowset)) {
6695
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6696
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6697
9
                             "at next turn, instance_id="
6698
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6699
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6700
9
                return 0;
6701
9
            }
6702
16
        }
6703
6704
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6705
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6706
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6707
261
                             "instance_id="
6708
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6709
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6710
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6711
261
                return 0;
6712
261
            }
6713
265
        }
6714
6715
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6716
        // Remove the rowset ref count key directly since it has not been used.
6717
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6718
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6719
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6720
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6721
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6722
6723
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6724
53.0k
        return 0;
6725
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6654
16
                                    std::string_view k, std::string_view v) -> int {
6655
16
        ++num_scanned;
6656
16
        total_rowset_key_size += k.size();
6657
16
        total_rowset_value_size += v.size();
6658
16
        doris::RowsetMetaCloudPB rowset;
6659
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6660
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6661
0
            return -1;
6662
0
        }
6663
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6664
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6665
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6666
0
                   << " txn_expiration=" << rowset.txn_expiration()
6667
0
                   << " rowset_creation_time=" << rowset.creation_time();
6668
16
        int64_t current_time = ::time(nullptr);
6669
16
        if (current_time < expiration) { // not expired
6670
0
            return 0;
6671
0
        }
6672
16
        ++num_expired;
6673
16
        expired_rowset_size += v.size();
6674
16
        if (!rowset.has_resource_id()) {
6675
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6676
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6677
0
                return -1;
6678
0
            }
6679
            // might be a delete pred rowset
6680
0
            tmp_rowset_keys.emplace_back(k);
6681
0
            return 0;
6682
0
        }
6683
6684
        // TODO(plat1ko): check rowset not referenced
6685
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6686
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6687
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6688
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6689
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6690
16
                  << " num_expired=" << num_expired
6691
16
                  << " task_type=" << metrics_context.operation_type;
6692
6693
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6694
16
            if (need_mark_rowset_as_recycled(rowset)) {
6695
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6696
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6697
9
                             "at next turn, instance_id="
6698
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6699
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6700
9
                return 0;
6701
9
            }
6702
16
        }
6703
6704
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6705
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6706
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6707
3
                             "instance_id="
6708
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6709
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6710
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6711
3
                return 0;
6712
3
            }
6713
7
        }
6714
6715
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6716
        // Remove the rowset ref count key directly since it has not been used.
6717
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6718
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6719
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6720
4
                  << "key=" << hex(rowset_ref_count_key);
6721
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6722
6723
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6724
4
        return 0;
6725
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6654
53.2k
                                    std::string_view k, std::string_view v) -> int {
6655
53.2k
        ++num_scanned;
6656
53.2k
        total_rowset_key_size += k.size();
6657
53.2k
        total_rowset_value_size += v.size();
6658
53.2k
        doris::RowsetMetaCloudPB rowset;
6659
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6660
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6661
0
            return -1;
6662
0
        }
6663
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6664
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6665
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6666
0
                   << " txn_expiration=" << rowset.txn_expiration()
6667
0
                   << " rowset_creation_time=" << rowset.creation_time();
6668
53.2k
        int64_t current_time = ::time(nullptr);
6669
53.2k
        if (current_time < expiration) { // not expired
6670
0
            return 0;
6671
0
        }
6672
53.2k
        ++num_expired;
6673
53.2k
        expired_rowset_size += v.size();
6674
53.2k
        if (!rowset.has_resource_id()) {
6675
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6676
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6677
0
                return -1;
6678
0
            }
6679
            // might be a delete pred rowset
6680
0
            tmp_rowset_keys.emplace_back(k);
6681
0
            return 0;
6682
0
        }
6683
6684
        // TODO(plat1ko): check rowset not referenced
6685
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6686
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6687
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6688
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6689
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6690
53.2k
                  << " num_expired=" << num_expired
6691
53.2k
                  << " task_type=" << metrics_context.operation_type;
6692
6693
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6694
0
            if (need_mark_rowset_as_recycled(rowset)) {
6695
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6696
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6697
0
                             "at next turn, instance_id="
6698
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6699
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6700
0
                return 0;
6701
0
            }
6702
0
        }
6703
6704
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6705
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6706
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6707
258
                             "instance_id="
6708
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6709
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6710
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6711
258
                return 0;
6712
258
            }
6713
258
        }
6714
6715
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6716
        // Remove the rowset ref count key directly since it has not been used.
6717
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6718
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6719
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6720
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6721
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6722
6723
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6724
53.0k
        return 0;
6725
53.2k
    };
6726
6727
37
    auto loop_done = [&]() -> int {
6728
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6729
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6730
24
        std::vector<std::string> mark_keys_to_process;
6731
24
        std::vector<std::string> abort_keys_to_process;
6732
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6733
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6734
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6735
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6736
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6737
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6738
24
        if (!mark_keys_to_process.empty()) {
6739
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6740
7
                    *worker_pool, std::move(mark_keys_to_process));
6741
7
        }
6742
24
        if (!abort_keys_to_process.empty()) {
6743
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6744
5
                                           &num_recycled, &metrics_context);
6745
5
        }
6746
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6747
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6748
24
                             tmp_rowset_ref_count_keys_to_delete =
6749
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6750
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6751
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6752
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6753
24
                                   metrics_context) != 0) {
6754
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6755
2
                return;
6756
2
            }
6757
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6758
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6759
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6760
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6761
0
                                 << rs.ShortDebugString();
6762
0
                    return;
6763
0
                }
6764
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6765
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6766
0
                                 << rs.ShortDebugString();
6767
0
                    return;
6768
0
                }
6769
51.0k
            }
6770
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6771
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6772
0
                return;
6773
0
            }
6774
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6775
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6776
0
                return;
6777
0
            }
6778
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6779
22
            return;
6780
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6751
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6752
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6753
12
                                   metrics_context) != 0) {
6754
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6755
0
                return;
6756
0
            }
6757
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6758
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6759
4
                                                       rs.rowset_id_v2()) != 0) {
6760
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6761
0
                                 << rs.ShortDebugString();
6762
0
                    return;
6763
0
                }
6764
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6765
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6766
0
                                 << rs.ShortDebugString();
6767
0
                    return;
6768
0
                }
6769
4
            }
6770
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6771
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6772
0
                return;
6773
0
            }
6774
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6775
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6776
0
                return;
6777
0
            }
6778
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6779
12
            return;
6780
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6751
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6752
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6753
12
                                   metrics_context) != 0) {
6754
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6755
2
                return;
6756
2
            }
6757
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6758
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6759
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6760
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6761
0
                                 << rs.ShortDebugString();
6762
0
                    return;
6763
0
                }
6764
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6765
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6766
0
                                 << rs.ShortDebugString();
6767
0
                    return;
6768
0
                }
6769
51.0k
            }
6770
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6771
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6772
0
                return;
6773
0
            }
6774
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6775
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6776
0
                return;
6777
0
            }
6778
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6779
10
            return;
6780
10
        });
6781
24
        return 0;
6782
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6727
12
    auto loop_done = [&]() -> int {
6728
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6729
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6730
12
        std::vector<std::string> mark_keys_to_process;
6731
12
        std::vector<std::string> abort_keys_to_process;
6732
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6733
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6734
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6735
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6736
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6737
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6738
12
        if (!mark_keys_to_process.empty()) {
6739
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6740
7
                    *worker_pool, std::move(mark_keys_to_process));
6741
7
        }
6742
12
        if (!abort_keys_to_process.empty()) {
6743
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6744
3
                                           &num_recycled, &metrics_context);
6745
3
        }
6746
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6747
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6748
12
                             tmp_rowset_ref_count_keys_to_delete =
6749
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6750
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6751
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6752
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6753
12
                                   metrics_context) != 0) {
6754
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6755
12
                return;
6756
12
            }
6757
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6758
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6759
12
                                                       rs.rowset_id_v2()) != 0) {
6760
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6761
12
                                 << rs.ShortDebugString();
6762
12
                    return;
6763
12
                }
6764
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6765
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6766
12
                                 << rs.ShortDebugString();
6767
12
                    return;
6768
12
                }
6769
12
            }
6770
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6771
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6772
12
                return;
6773
12
            }
6774
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6775
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6776
12
                return;
6777
12
            }
6778
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6779
12
            return;
6780
12
        });
6781
12
        return 0;
6782
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6727
12
    auto loop_done = [&]() -> int {
6728
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6729
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6730
12
        std::vector<std::string> mark_keys_to_process;
6731
12
        std::vector<std::string> abort_keys_to_process;
6732
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6733
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6734
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6735
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6736
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6737
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6738
12
        if (!mark_keys_to_process.empty()) {
6739
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6740
0
                    *worker_pool, std::move(mark_keys_to_process));
6741
0
        }
6742
12
        if (!abort_keys_to_process.empty()) {
6743
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6744
2
                                           &num_recycled, &metrics_context);
6745
2
        }
6746
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6747
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6748
12
                             tmp_rowset_ref_count_keys_to_delete =
6749
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6750
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6751
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6752
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6753
12
                                   metrics_context) != 0) {
6754
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6755
12
                return;
6756
12
            }
6757
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6758
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6759
12
                                                       rs.rowset_id_v2()) != 0) {
6760
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6761
12
                                 << rs.ShortDebugString();
6762
12
                    return;
6763
12
                }
6764
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6765
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6766
12
                                 << rs.ShortDebugString();
6767
12
                    return;
6768
12
                }
6769
12
            }
6770
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6771
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6772
12
                return;
6773
12
            }
6774
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6775
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6776
12
                return;
6777
12
            }
6778
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6779
12
            return;
6780
12
        });
6781
12
        return 0;
6782
12
    };
6783
6784
37
    if (config::enable_recycler_stats_metrics) {
6785
0
        scan_and_statistics_tmp_rowsets();
6786
0
    }
6787
    // recycle_func and loop_done for scan and recycle
6788
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6789
37
                               std::move(loop_done));
6790
6791
37
    worker_pool->stop();
6792
6793
    // Report final metrics after all concurrent tasks completed
6794
37
    segment_metrics_context_.report();
6795
37
    metrics_context.report();
6796
6797
37
    return ret;
6798
37
}
6799
6800
int InstanceRecycler::scan_and_recycle(
6801
        std::string begin, std::string_view end,
6802
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6803
352
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6804
352
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6805
352
    int ret = 0;
6806
352
    int64_t cnt = 0;
6807
352
    int get_range_retried = 0;
6808
352
    std::string err;
6809
352
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6810
352
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6811
352
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6812
352
                  << " ret=" << ret << " err=" << err;
6813
352
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6809
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6810
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6811
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6812
39
                  << " ret=" << ret << " err=" << err;
6813
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6809
313
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6810
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6811
313
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6812
313
                  << " ret=" << ret << " err=" << err;
6813
313
    };
6814
6815
352
    std::unique_ptr<RangeGetIterator> it;
6816
906
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6817
707
        if (get_range_retried > 1000) {
6818
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6819
0
            ret = -3;
6820
0
            return ret;
6821
0
        }
6822
707
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6823
707
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6824
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6825
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6826
0
                         << " get_range_retried=" << get_range_retried;
6827
0
            ++get_range_retried;
6828
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6829
0
            continue; // try again
6830
0
        }
6831
707
        if (!it->has_next()) {
6832
153
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6833
153
            break; // scan finished
6834
153
        }
6835
554
        bool begin_updated = false;
6836
554
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6837
554
                  << ") iterator->size()=" << it->size();
6838
258k
        while (it->has_next()) {
6839
258k
            ++cnt;
6840
            // recycle corresponding resources
6841
258k
            auto [k, v] = it->next();
6842
258k
            if (!it->has_next()) {
6843
554
                begin = k;
6844
554
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6845
554
            }
6846
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6847
258k
            if (recycle_func(k, v) != 0) {
6848
4.00k
                err = "recycle_func error";
6849
4.00k
                ret = -1;
6850
4.00k
            }
6851
258k
            if (next_begin_getter) {
6852
0
                std::string next_begin;
6853
0
                if (next_begin_getter(&next_begin)) {
6854
0
                    if (next_begin > k) {
6855
0
                        begin = std::move(next_begin);
6856
0
                        begin_updated = true;
6857
0
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6858
0
                                   << " after key=" << hex(k);
6859
0
                        break;
6860
0
                    }
6861
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6862
0
                            .tag("next_begin", hex(next_begin))
6863
0
                            .tag("current_key", hex(k));
6864
0
                }
6865
0
            }
6866
258k
        }
6867
554
        if (!begin_updated) {
6868
554
            begin.push_back('\x00'); // Update to next smallest key for iteration
6869
554
        } else {
6870
0
            it.reset();
6871
0
        }
6872
6873
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6874
        // if we want to continue scanning, the recycle_func should not return non-zero
6875
554
        if (loop_done && loop_done() != 0) {
6876
9
            err = "loop_done error";
6877
9
            ret = -1;
6878
9
        }
6879
554
    }
6880
352
    return ret;
6881
352
}
6882
6883
19
int InstanceRecycler::abort_timeout_txn() {
6884
19
    const std::string task_name = "abort_timeout_txn";
6885
19
    int64_t num_scanned = 0;
6886
19
    int64_t num_timeout = 0;
6887
19
    int64_t num_abort = 0;
6888
19
    int64_t num_advance = 0;
6889
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6890
6891
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6892
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6893
19
    std::string begin_txn_running_key;
6894
19
    std::string end_txn_running_key;
6895
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6896
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6897
6898
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6899
6900
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6901
19
    register_recycle_task(task_name, start_time);
6902
6903
19
    DORIS_CLOUD_DEFER {
6904
19
        unregister_recycle_task(task_name);
6905
19
        int64_t cost =
6906
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6907
19
        metrics_context.finish_report();
6908
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6909
19
                .tag("instance_id", instance_id_)
6910
19
                .tag("num_scanned", num_scanned)
6911
19
                .tag("num_timeout", num_timeout)
6912
19
                .tag("num_abort", num_abort)
6913
19
                .tag("num_advance", num_advance);
6914
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6903
3
    DORIS_CLOUD_DEFER {
6904
3
        unregister_recycle_task(task_name);
6905
3
        int64_t cost =
6906
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6907
3
        metrics_context.finish_report();
6908
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6909
3
                .tag("instance_id", instance_id_)
6910
3
                .tag("num_scanned", num_scanned)
6911
3
                .tag("num_timeout", num_timeout)
6912
3
                .tag("num_abort", num_abort)
6913
3
                .tag("num_advance", num_advance);
6914
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6903
16
    DORIS_CLOUD_DEFER {
6904
16
        unregister_recycle_task(task_name);
6905
16
        int64_t cost =
6906
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6907
16
        metrics_context.finish_report();
6908
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6909
16
                .tag("instance_id", instance_id_)
6910
16
                .tag("num_scanned", num_scanned)
6911
16
                .tag("num_timeout", num_timeout)
6912
16
                .tag("num_abort", num_abort)
6913
16
                .tag("num_advance", num_advance);
6914
16
    };
6915
6916
19
    int64_t current_time =
6917
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6918
6919
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6920
19
                                  &current_time, &metrics_context,
6921
19
                                  this](std::string_view k, std::string_view v) -> int {
6922
9
        ++num_scanned;
6923
6924
9
        std::unique_ptr<Transaction> txn;
6925
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6926
9
        if (err != TxnErrorCode::TXN_OK) {
6927
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
9
        std::string_view k1 = k;
6931
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6932
9
        k1.remove_prefix(1); // Remove key space
6933
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6934
9
        if (decode_key(&k1, &out) != 0) {
6935
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6936
0
            return -1;
6937
0
        }
6938
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6939
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6940
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6941
        // Update txn_info
6942
9
        std::string txn_inf_key, txn_inf_val;
6943
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6944
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6945
9
        if (err != TxnErrorCode::TXN_OK) {
6946
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6947
0
            return -1;
6948
0
        }
6949
9
        TxnInfoPB txn_info;
6950
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6951
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6952
0
            return -1;
6953
0
        }
6954
6955
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6956
3
            txn.reset();
6957
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6958
3
            std::shared_ptr<TxnLazyCommitTask> task =
6959
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6960
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6961
3
            if (ret.first != MetaServiceCode::OK) {
6962
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6963
0
                             << "msg=" << ret.second;
6964
0
                return -1;
6965
0
            }
6966
3
            ++num_advance;
6967
3
            return 0;
6968
6
        } else {
6969
6
            TxnRunningPB txn_running_pb;
6970
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6971
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6972
0
                return -1;
6973
0
            }
6974
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6975
4
                return 0;
6976
4
            }
6977
2
            ++num_timeout;
6978
6979
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6980
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6981
2
            txn_info.set_finish_time(current_time);
6982
2
            txn_info.set_reason("timeout");
6983
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6984
2
            txn_inf_val.clear();
6985
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6986
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6987
0
                return -1;
6988
0
            }
6989
2
            txn->put(txn_inf_key, txn_inf_val);
6990
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6991
            // Put recycle txn key
6992
2
            std::string recyc_txn_key, recyc_txn_val;
6993
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6994
2
            RecycleTxnPB recycle_txn_pb;
6995
2
            recycle_txn_pb.set_creation_time(current_time);
6996
2
            recycle_txn_pb.set_label(txn_info.label());
6997
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6998
0
                LOG_WARNING("failed to serialize txn recycle info")
6999
0
                        .tag("key", hex(k))
7000
0
                        .tag("db_id", db_id)
7001
0
                        .tag("txn_id", txn_id);
7002
0
                return -1;
7003
0
            }
7004
2
            txn->put(recyc_txn_key, recyc_txn_val);
7005
            // Remove txn running key
7006
2
            txn->remove(k);
7007
2
            err = txn->commit();
7008
2
            if (err != TxnErrorCode::TXN_OK) {
7009
0
                LOG_WARNING("failed to commit txn err={}", err)
7010
0
                        .tag("key", hex(k))
7011
0
                        .tag("db_id", db_id)
7012
0
                        .tag("txn_id", txn_id);
7013
0
                return -1;
7014
0
            }
7015
2
            metrics_context.total_recycled_num = ++num_abort;
7016
2
            metrics_context.report();
7017
2
        }
7018
7019
2
        return 0;
7020
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6921
3
                                  this](std::string_view k, std::string_view v) -> int {
6922
3
        ++num_scanned;
6923
6924
3
        std::unique_ptr<Transaction> txn;
6925
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6926
3
        if (err != TxnErrorCode::TXN_OK) {
6927
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
3
        std::string_view k1 = k;
6931
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6932
3
        k1.remove_prefix(1); // Remove key space
6933
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6934
3
        if (decode_key(&k1, &out) != 0) {
6935
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6936
0
            return -1;
6937
0
        }
6938
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6939
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6940
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6941
        // Update txn_info
6942
3
        std::string txn_inf_key, txn_inf_val;
6943
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6944
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6945
3
        if (err != TxnErrorCode::TXN_OK) {
6946
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6947
0
            return -1;
6948
0
        }
6949
3
        TxnInfoPB txn_info;
6950
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6951
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6952
0
            return -1;
6953
0
        }
6954
6955
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6956
3
            txn.reset();
6957
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6958
3
            std::shared_ptr<TxnLazyCommitTask> task =
6959
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6960
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6961
3
            if (ret.first != MetaServiceCode::OK) {
6962
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6963
0
                             << "msg=" << ret.second;
6964
0
                return -1;
6965
0
            }
6966
3
            ++num_advance;
6967
3
            return 0;
6968
3
        } else {
6969
0
            TxnRunningPB txn_running_pb;
6970
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6971
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6972
0
                return -1;
6973
0
            }
6974
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6975
0
                return 0;
6976
0
            }
6977
0
            ++num_timeout;
6978
6979
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6980
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6981
0
            txn_info.set_finish_time(current_time);
6982
0
            txn_info.set_reason("timeout");
6983
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6984
0
            txn_inf_val.clear();
6985
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6986
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6987
0
                return -1;
6988
0
            }
6989
0
            txn->put(txn_inf_key, txn_inf_val);
6990
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6991
            // Put recycle txn key
6992
0
            std::string recyc_txn_key, recyc_txn_val;
6993
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6994
0
            RecycleTxnPB recycle_txn_pb;
6995
0
            recycle_txn_pb.set_creation_time(current_time);
6996
0
            recycle_txn_pb.set_label(txn_info.label());
6997
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6998
0
                LOG_WARNING("failed to serialize txn recycle info")
6999
0
                        .tag("key", hex(k))
7000
0
                        .tag("db_id", db_id)
7001
0
                        .tag("txn_id", txn_id);
7002
0
                return -1;
7003
0
            }
7004
0
            txn->put(recyc_txn_key, recyc_txn_val);
7005
            // Remove txn running key
7006
0
            txn->remove(k);
7007
0
            err = txn->commit();
7008
0
            if (err != TxnErrorCode::TXN_OK) {
7009
0
                LOG_WARNING("failed to commit txn err={}", err)
7010
0
                        .tag("key", hex(k))
7011
0
                        .tag("db_id", db_id)
7012
0
                        .tag("txn_id", txn_id);
7013
0
                return -1;
7014
0
            }
7015
0
            metrics_context.total_recycled_num = ++num_abort;
7016
0
            metrics_context.report();
7017
0
        }
7018
7019
0
        return 0;
7020
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6921
6
                                  this](std::string_view k, std::string_view v) -> int {
6922
6
        ++num_scanned;
6923
6924
6
        std::unique_ptr<Transaction> txn;
6925
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6926
6
        if (err != TxnErrorCode::TXN_OK) {
6927
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
6
        std::string_view k1 = k;
6931
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6932
6
        k1.remove_prefix(1); // Remove key space
6933
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6934
6
        if (decode_key(&k1, &out) != 0) {
6935
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6936
0
            return -1;
6937
0
        }
6938
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6939
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6940
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6941
        // Update txn_info
6942
6
        std::string txn_inf_key, txn_inf_val;
6943
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6944
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6945
6
        if (err != TxnErrorCode::TXN_OK) {
6946
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6947
0
            return -1;
6948
0
        }
6949
6
        TxnInfoPB txn_info;
6950
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6951
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6952
0
            return -1;
6953
0
        }
6954
6955
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6956
0
            txn.reset();
6957
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6958
0
            std::shared_ptr<TxnLazyCommitTask> task =
6959
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6960
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6961
0
            if (ret.first != MetaServiceCode::OK) {
6962
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6963
0
                             << "msg=" << ret.second;
6964
0
                return -1;
6965
0
            }
6966
0
            ++num_advance;
6967
0
            return 0;
6968
6
        } else {
6969
6
            TxnRunningPB txn_running_pb;
6970
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6971
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6972
0
                return -1;
6973
0
            }
6974
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6975
4
                return 0;
6976
4
            }
6977
2
            ++num_timeout;
6978
6979
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6980
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6981
2
            txn_info.set_finish_time(current_time);
6982
2
            txn_info.set_reason("timeout");
6983
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6984
2
            txn_inf_val.clear();
6985
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6986
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6987
0
                return -1;
6988
0
            }
6989
2
            txn->put(txn_inf_key, txn_inf_val);
6990
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6991
            // Put recycle txn key
6992
2
            std::string recyc_txn_key, recyc_txn_val;
6993
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6994
2
            RecycleTxnPB recycle_txn_pb;
6995
2
            recycle_txn_pb.set_creation_time(current_time);
6996
2
            recycle_txn_pb.set_label(txn_info.label());
6997
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6998
0
                LOG_WARNING("failed to serialize txn recycle info")
6999
0
                        .tag("key", hex(k))
7000
0
                        .tag("db_id", db_id)
7001
0
                        .tag("txn_id", txn_id);
7002
0
                return -1;
7003
0
            }
7004
2
            txn->put(recyc_txn_key, recyc_txn_val);
7005
            // Remove txn running key
7006
2
            txn->remove(k);
7007
2
            err = txn->commit();
7008
2
            if (err != TxnErrorCode::TXN_OK) {
7009
0
                LOG_WARNING("failed to commit txn err={}", err)
7010
0
                        .tag("key", hex(k))
7011
0
                        .tag("db_id", db_id)
7012
0
                        .tag("txn_id", txn_id);
7013
0
                return -1;
7014
0
            }
7015
2
            metrics_context.total_recycled_num = ++num_abort;
7016
2
            metrics_context.report();
7017
2
        }
7018
7019
2
        return 0;
7020
6
    };
7021
7022
19
    if (config::enable_recycler_stats_metrics) {
7023
0
        scan_and_statistics_abort_timeout_txn();
7024
0
    }
7025
    // recycle_func and loop_done for scan and recycle
7026
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7027
19
                            std::move(handle_txn_running_kv));
7028
19
}
7029
7030
22
int InstanceRecycler::recycle_expired_txn_label() {
7031
22
    const std::string task_name = "recycle_expired_txn_label";
7032
22
    int64_t num_scanned = 0;
7033
22
    int64_t num_expired = 0;
7034
22
    std::atomic_long num_recycled = 0;
7035
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7036
22
    int ret = 0;
7037
7038
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7039
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7040
22
    std::string begin_recycle_txn_key;
7041
22
    std::string end_recycle_txn_key;
7042
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7043
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7044
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
7045
7046
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
7047
7048
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7049
22
    register_recycle_task(task_name, start_time);
7050
22
    DORIS_CLOUD_DEFER {
7051
22
        unregister_recycle_task(task_name);
7052
22
        int64_t cost =
7053
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7054
22
        metrics_context.finish_report();
7055
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7056
22
                .tag("instance_id", instance_id_)
7057
22
                .tag("num_scanned", num_scanned)
7058
22
                .tag("num_expired", num_expired)
7059
22
                .tag("num_recycled", num_recycled);
7060
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7050
1
    DORIS_CLOUD_DEFER {
7051
1
        unregister_recycle_task(task_name);
7052
1
        int64_t cost =
7053
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7054
1
        metrics_context.finish_report();
7055
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7056
1
                .tag("instance_id", instance_id_)
7057
1
                .tag("num_scanned", num_scanned)
7058
1
                .tag("num_expired", num_expired)
7059
1
                .tag("num_recycled", num_recycled);
7060
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7050
21
    DORIS_CLOUD_DEFER {
7051
21
        unregister_recycle_task(task_name);
7052
21
        int64_t cost =
7053
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7054
21
        metrics_context.finish_report();
7055
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7056
21
                .tag("instance_id", instance_id_)
7057
21
                .tag("num_scanned", num_scanned)
7058
21
                .tag("num_expired", num_expired)
7059
21
                .tag("num_recycled", num_recycled);
7060
21
    };
7061
7062
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7063
7064
22
    SyncExecutor<int> concurrent_delete_executor(
7065
22
            _thread_pool_group.s3_producer_pool,
7066
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7067
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7067
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7067
38.0k
            [](const int& ret) { return ret != 0; });
7068
7069
22
    int64_t current_time_ms =
7070
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7071
7072
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7073
50.0k
        ++num_scanned;
7074
50.0k
        RecycleTxnPB recycle_txn_pb;
7075
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7076
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7077
0
            return -1;
7078
0
        }
7079
50.0k
        if ((config::force_immediate_recycle) ||
7080
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7081
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7082
50.0k
             current_time_ms)) {
7083
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7084
38.0k
            num_expired++;
7085
7086
38.0k
            std::string_view k1 = k;
7087
38.0k
            k1.remove_prefix(1); // Remove key space
7088
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7089
38.0k
            if (decode_key(&k1, &out) != 0) {
7090
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7091
0
                return -1;
7092
0
            }
7093
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7094
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7095
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7096
38.0k
        }
7097
50.0k
        return 0;
7098
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7072
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7073
1
        ++num_scanned;
7074
1
        RecycleTxnPB recycle_txn_pb;
7075
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7076
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7077
0
            return -1;
7078
0
        }
7079
1
        if ((config::force_immediate_recycle) ||
7080
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7081
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7082
1
             current_time_ms)) {
7083
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7084
1
            num_expired++;
7085
7086
1
            std::string_view k1 = k;
7087
1
            k1.remove_prefix(1); // Remove key space
7088
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7089
1
            if (decode_key(&k1, &out) != 0) {
7090
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7091
0
                return -1;
7092
0
            }
7093
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7094
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7095
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7096
1
        }
7097
1
        return 0;
7098
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7072
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7073
50.0k
        ++num_scanned;
7074
50.0k
        RecycleTxnPB recycle_txn_pb;
7075
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7076
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7077
0
            return -1;
7078
0
        }
7079
50.0k
        if ((config::force_immediate_recycle) ||
7080
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7081
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7082
50.0k
             current_time_ms)) {
7083
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7084
38.0k
            num_expired++;
7085
7086
38.0k
            std::string_view k1 = k;
7087
38.0k
            k1.remove_prefix(1); // Remove key space
7088
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7089
38.0k
            if (decode_key(&k1, &out) != 0) {
7090
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7091
0
                return -1;
7092
0
            }
7093
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7094
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7095
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7096
38.0k
        }
7097
50.0k
        return 0;
7098
50.0k
    };
7099
7100
    // int 0 for success, 1 for conflict, -1 for error
7101
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7102
38.0k
        std::string_view k1 = k;
7103
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7104
38.0k
        k1.remove_prefix(1); // Remove key space
7105
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7106
38.0k
        int ret = decode_key(&k1, &out);
7107
38.0k
        if (ret != 0) {
7108
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7109
0
            return -1;
7110
0
        }
7111
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7112
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7113
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7114
38.0k
        std::unique_ptr<Transaction> txn;
7115
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7116
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7117
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7118
0
            return -1;
7119
0
        }
7120
        // Remove txn index kv
7121
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7122
38.0k
        txn->remove(index_key);
7123
        // Remove txn info kv
7124
38.0k
        std::string info_key, info_val;
7125
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7126
38.0k
        err = txn->get(info_key, &info_val);
7127
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7128
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7129
0
            return -1;
7130
0
        }
7131
38.0k
        TxnInfoPB txn_info;
7132
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7133
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7134
0
            return -1;
7135
0
        }
7136
38.0k
        txn->remove(info_key);
7137
        // Remove sub txn index kvs
7138
38.0k
        std::vector<std::string> sub_txn_index_keys;
7139
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7140
37.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7141
37.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7142
37.9k
        }
7143
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7144
37.9k
            txn->remove(sub_txn_index_key);
7145
37.9k
        }
7146
        // Update txn label
7147
38.0k
        std::string label_key, label_val;
7148
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7149
38.0k
        err = txn->get(label_key, &label_val);
7150
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7151
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7152
0
                         << " err=" << err;
7153
0
            return -1;
7154
0
        }
7155
38.0k
        TxnLabelPB txn_label;
7156
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7157
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7158
0
            return -1;
7159
0
        }
7160
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7161
38.0k
        if (it != txn_label.txn_ids().end()) {
7162
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7163
38.0k
        }
7164
38.0k
        if (txn_label.txn_ids().empty()) {
7165
38.0k
            txn->remove(label_key);
7166
38.0k
            TEST_SYNC_POINT_CALLBACK(
7167
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7168
38.0k
        } else {
7169
11
            if (!txn_label.SerializeToString(&label_val)) {
7170
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7171
0
                return -1;
7172
0
            }
7173
11
            TEST_SYNC_POINT_CALLBACK(
7174
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7175
11
            txn->atomic_set_ver_value(label_key, label_val);
7176
11
            TEST_SYNC_POINT_CALLBACK(
7177
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7178
11
        }
7179
        // Remove recycle txn kv
7180
38.0k
        txn->remove(k);
7181
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7182
38.0k
        err = txn->commit();
7183
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7184
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7185
4
                TEST_SYNC_POINT_CALLBACK(
7186
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7187
                // log the txn_id and label
7188
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7189
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7190
4
                             << " txn_label=" << txn_info.label();
7191
4
                return 1;
7192
4
            }
7193
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7194
0
            return -1;
7195
4
        }
7196
38.0k
        ++num_recycled;
7197
7198
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7199
38.0k
        return 0;
7200
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7101
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7102
1
        std::string_view k1 = k;
7103
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7104
1
        k1.remove_prefix(1); // Remove key space
7105
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7106
1
        int ret = decode_key(&k1, &out);
7107
1
        if (ret != 0) {
7108
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7109
0
            return -1;
7110
0
        }
7111
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7112
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7113
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7114
1
        std::unique_ptr<Transaction> txn;
7115
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7116
1
        if (err != TxnErrorCode::TXN_OK) {
7117
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7118
0
            return -1;
7119
0
        }
7120
        // Remove txn index kv
7121
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7122
1
        txn->remove(index_key);
7123
        // Remove txn info kv
7124
1
        std::string info_key, info_val;
7125
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7126
1
        err = txn->get(info_key, &info_val);
7127
1
        if (err != TxnErrorCode::TXN_OK) {
7128
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7129
0
            return -1;
7130
0
        }
7131
1
        TxnInfoPB txn_info;
7132
1
        if (!txn_info.ParseFromString(info_val)) {
7133
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7134
0
            return -1;
7135
0
        }
7136
1
        txn->remove(info_key);
7137
        // Remove sub txn index kvs
7138
1
        std::vector<std::string> sub_txn_index_keys;
7139
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7140
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7141
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7142
0
        }
7143
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7144
0
            txn->remove(sub_txn_index_key);
7145
0
        }
7146
        // Update txn label
7147
1
        std::string label_key, label_val;
7148
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7149
1
        err = txn->get(label_key, &label_val);
7150
1
        if (err != TxnErrorCode::TXN_OK) {
7151
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7152
0
                         << " err=" << err;
7153
0
            return -1;
7154
0
        }
7155
1
        TxnLabelPB txn_label;
7156
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7157
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7158
0
            return -1;
7159
0
        }
7160
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7161
1
        if (it != txn_label.txn_ids().end()) {
7162
1
            txn_label.mutable_txn_ids()->erase(it);
7163
1
        }
7164
1
        if (txn_label.txn_ids().empty()) {
7165
1
            txn->remove(label_key);
7166
1
            TEST_SYNC_POINT_CALLBACK(
7167
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7168
1
        } else {
7169
0
            if (!txn_label.SerializeToString(&label_val)) {
7170
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7171
0
                return -1;
7172
0
            }
7173
0
            TEST_SYNC_POINT_CALLBACK(
7174
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7175
0
            txn->atomic_set_ver_value(label_key, label_val);
7176
0
            TEST_SYNC_POINT_CALLBACK(
7177
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7178
0
        }
7179
        // Remove recycle txn kv
7180
1
        txn->remove(k);
7181
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7182
1
        err = txn->commit();
7183
1
        if (err != TxnErrorCode::TXN_OK) {
7184
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7185
0
                TEST_SYNC_POINT_CALLBACK(
7186
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7187
                // log the txn_id and label
7188
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7189
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7190
0
                             << " txn_label=" << txn_info.label();
7191
0
                return 1;
7192
0
            }
7193
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7194
0
            return -1;
7195
0
        }
7196
1
        ++num_recycled;
7197
7198
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7199
1
        return 0;
7200
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7101
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7102
38.0k
        std::string_view k1 = k;
7103
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7104
38.0k
        k1.remove_prefix(1); // Remove key space
7105
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7106
38.0k
        int ret = decode_key(&k1, &out);
7107
38.0k
        if (ret != 0) {
7108
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7109
0
            return -1;
7110
0
        }
7111
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7112
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7113
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7114
38.0k
        std::unique_ptr<Transaction> txn;
7115
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7116
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7117
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7118
0
            return -1;
7119
0
        }
7120
        // Remove txn index kv
7121
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7122
38.0k
        txn->remove(index_key);
7123
        // Remove txn info kv
7124
38.0k
        std::string info_key, info_val;
7125
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7126
38.0k
        err = txn->get(info_key, &info_val);
7127
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7128
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7129
0
            return -1;
7130
0
        }
7131
38.0k
        TxnInfoPB txn_info;
7132
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7133
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7134
0
            return -1;
7135
0
        }
7136
38.0k
        txn->remove(info_key);
7137
        // Remove sub txn index kvs
7138
38.0k
        std::vector<std::string> sub_txn_index_keys;
7139
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7140
37.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7141
37.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7142
37.9k
        }
7143
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7144
37.9k
            txn->remove(sub_txn_index_key);
7145
37.9k
        }
7146
        // Update txn label
7147
38.0k
        std::string label_key, label_val;
7148
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7149
38.0k
        err = txn->get(label_key, &label_val);
7150
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7151
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7152
0
                         << " err=" << err;
7153
0
            return -1;
7154
0
        }
7155
38.0k
        TxnLabelPB txn_label;
7156
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7157
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7158
0
            return -1;
7159
0
        }
7160
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7161
38.0k
        if (it != txn_label.txn_ids().end()) {
7162
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7163
38.0k
        }
7164
38.0k
        if (txn_label.txn_ids().empty()) {
7165
38.0k
            txn->remove(label_key);
7166
38.0k
            TEST_SYNC_POINT_CALLBACK(
7167
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7168
38.0k
        } else {
7169
11
            if (!txn_label.SerializeToString(&label_val)) {
7170
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7171
0
                return -1;
7172
0
            }
7173
11
            TEST_SYNC_POINT_CALLBACK(
7174
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7175
11
            txn->atomic_set_ver_value(label_key, label_val);
7176
11
            TEST_SYNC_POINT_CALLBACK(
7177
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7178
11
        }
7179
        // Remove recycle txn kv
7180
38.0k
        txn->remove(k);
7181
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7182
38.0k
        err = txn->commit();
7183
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7184
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7185
4
                TEST_SYNC_POINT_CALLBACK(
7186
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7187
                // log the txn_id and label
7188
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7189
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7190
4
                             << " txn_label=" << txn_info.label();
7191
4
                return 1;
7192
4
            }
7193
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7194
0
            return -1;
7195
4
        }
7196
38.0k
        ++num_recycled;
7197
7198
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7199
38.0k
        return 0;
7200
38.0k
    };
7201
7202
22
    auto loop_done = [&]() -> int {
7203
15
        DORIS_CLOUD_DEFER {
7204
15
            recycle_txn_keys_by_label.clear();
7205
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7203
1
        DORIS_CLOUD_DEFER {
7204
1
            recycle_txn_keys_by_label.clear();
7205
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7203
14
        DORIS_CLOUD_DEFER {
7204
14
            recycle_txn_keys_by_label.clear();
7205
14
        };
7206
15
        TEST_SYNC_POINT_CALLBACK(
7207
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7208
15
                &recycle_txn_keys_by_label);
7209
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7210
38.0k
            int ret = delete_recycle_txn_kv(k);
7211
38.0k
            TEST_SYNC_POINT_CALLBACK(
7212
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7213
38.0k
                    &ret);
7214
38.0k
            if (ret == 1) {
7215
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7216
4
                for (int i = 1; i <= max_retry; ++i) {
7217
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7218
3
                    ret = delete_recycle_txn_kv(k);
7219
3
                    TEST_SYNC_POINT_CALLBACK(
7220
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7221
3
                            "error",
7222
3
                            &ret);
7223
3
                    if (ret != 1) {
7224
1
                        break;
7225
1
                    }
7226
                    // random sleep 0-100 ms to retry
7227
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7228
2
                }
7229
2
            }
7230
38.0k
            return ret;
7231
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7209
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7210
1
            int ret = delete_recycle_txn_kv(k);
7211
1
            TEST_SYNC_POINT_CALLBACK(
7212
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7213
1
                    &ret);
7214
1
            if (ret == 1) {
7215
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7216
0
                for (int i = 1; i <= max_retry; ++i) {
7217
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7218
0
                    ret = delete_recycle_txn_kv(k);
7219
0
                    TEST_SYNC_POINT_CALLBACK(
7220
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7221
0
                            "error",
7222
0
                            &ret);
7223
0
                    if (ret != 1) {
7224
0
                        break;
7225
0
                    }
7226
                    // random sleep 0-100 ms to retry
7227
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7228
0
                }
7229
0
            }
7230
1
            return ret;
7231
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7209
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7210
38.0k
            int ret = delete_recycle_txn_kv(k);
7211
38.0k
            TEST_SYNC_POINT_CALLBACK(
7212
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7213
38.0k
                    &ret);
7214
38.0k
            if (ret == 1) {
7215
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7216
4
                for (int i = 1; i <= max_retry; ++i) {
7217
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7218
3
                    ret = delete_recycle_txn_kv(k);
7219
3
                    TEST_SYNC_POINT_CALLBACK(
7220
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7221
3
                            "error",
7222
3
                            &ret);
7223
3
                    if (ret != 1) {
7224
1
                        break;
7225
1
                    }
7226
                    // random sleep 0-100 ms to retry
7227
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7228
2
                }
7229
2
            }
7230
38.0k
            return ret;
7231
38.0k
        };
7232
7233
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7234
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7235
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7236
1
                           << " txn_count=" << txn_keys.size();
7237
38.0k
                for (const auto& k : txn_keys) {
7238
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7239
38.0k
                    if (ret != 0) {
7240
2
                        LOG_WARNING("failed to delete recycle txn kv")
7241
2
                                .tag("instance id", instance_id_)
7242
2
                                .tag("key", hex(k))
7243
2
                                .tag("label_key", hex(label_key));
7244
2
                        return -1;
7245
2
                    }
7246
38.0k
                }
7247
38.0k
                return 0;
7248
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7234
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7235
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7236
0
                           << " txn_count=" << txn_keys.size();
7237
1
                for (const auto& k : txn_keys) {
7238
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7239
1
                    if (ret != 0) {
7240
0
                        LOG_WARNING("failed to delete recycle txn kv")
7241
0
                                .tag("instance id", instance_id_)
7242
0
                                .tag("key", hex(k))
7243
0
                                .tag("label_key", hex(label_key));
7244
0
                        return -1;
7245
0
                    }
7246
1
                }
7247
1
                return 0;
7248
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7234
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7235
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7236
1
                           << " txn_count=" << txn_keys.size();
7237
38.0k
                for (const auto& k : txn_keys) {
7238
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7239
38.0k
                    if (ret != 0) {
7240
2
                        LOG_WARNING("failed to delete recycle txn kv")
7241
2
                                .tag("instance id", instance_id_)
7242
2
                                .tag("key", hex(k))
7243
2
                                .tag("label_key", hex(label_key));
7244
2
                        return -1;
7245
2
                    }
7246
38.0k
                }
7247
38.0k
                return 0;
7248
38.0k
            });
7249
38.0k
        }
7250
15
        bool finished = true;
7251
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7252
38.0k
        for (int r : rets) {
7253
38.0k
            if (r != 0) {
7254
2
                ret = -1;
7255
2
            }
7256
38.0k
        }
7257
7258
15
        ret = finished ? ret : -1;
7259
7260
        // Update metrics after all concurrent tasks completed
7261
15
        metrics_context.total_recycled_num = num_recycled.load();
7262
15
        metrics_context.report();
7263
7264
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7265
7266
15
        if (ret != 0) {
7267
6
            LOG_WARNING("recycle txn kv ret!=0")
7268
6
                    .tag("finished", finished)
7269
6
                    .tag("ret", ret)
7270
6
                    .tag("instance_id", instance_id_);
7271
6
            return ret;
7272
6
        }
7273
9
        return ret;
7274
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7202
1
    auto loop_done = [&]() -> int {
7203
1
        DORIS_CLOUD_DEFER {
7204
1
            recycle_txn_keys_by_label.clear();
7205
1
        };
7206
1
        TEST_SYNC_POINT_CALLBACK(
7207
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7208
1
                &recycle_txn_keys_by_label);
7209
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7210
1
            int ret = delete_recycle_txn_kv(k);
7211
1
            TEST_SYNC_POINT_CALLBACK(
7212
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7213
1
                    &ret);
7214
1
            if (ret == 1) {
7215
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7216
1
                for (int i = 1; i <= max_retry; ++i) {
7217
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7218
1
                    ret = delete_recycle_txn_kv(k);
7219
1
                    TEST_SYNC_POINT_CALLBACK(
7220
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7221
1
                            "error",
7222
1
                            &ret);
7223
1
                    if (ret != 1) {
7224
1
                        break;
7225
1
                    }
7226
                    // random sleep 0-100 ms to retry
7227
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7228
1
                }
7229
1
            }
7230
1
            return ret;
7231
1
        };
7232
7233
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7234
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7235
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7236
1
                           << " txn_count=" << txn_keys.size();
7237
1
                for (const auto& k : txn_keys) {
7238
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7239
1
                    if (ret != 0) {
7240
1
                        LOG_WARNING("failed to delete recycle txn kv")
7241
1
                                .tag("instance id", instance_id_)
7242
1
                                .tag("key", hex(k))
7243
1
                                .tag("label_key", hex(label_key));
7244
1
                        return -1;
7245
1
                    }
7246
1
                }
7247
1
                return 0;
7248
1
            });
7249
1
        }
7250
1
        bool finished = true;
7251
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7252
1
        for (int r : rets) {
7253
1
            if (r != 0) {
7254
0
                ret = -1;
7255
0
            }
7256
1
        }
7257
7258
1
        ret = finished ? ret : -1;
7259
7260
        // Update metrics after all concurrent tasks completed
7261
1
        metrics_context.total_recycled_num = num_recycled.load();
7262
1
        metrics_context.report();
7263
7264
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7265
7266
1
        if (ret != 0) {
7267
0
            LOG_WARNING("recycle txn kv ret!=0")
7268
0
                    .tag("finished", finished)
7269
0
                    .tag("ret", ret)
7270
0
                    .tag("instance_id", instance_id_);
7271
0
            return ret;
7272
0
        }
7273
1
        return ret;
7274
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7202
14
    auto loop_done = [&]() -> int {
7203
14
        DORIS_CLOUD_DEFER {
7204
14
            recycle_txn_keys_by_label.clear();
7205
14
        };
7206
14
        TEST_SYNC_POINT_CALLBACK(
7207
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7208
14
                &recycle_txn_keys_by_label);
7209
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7210
14
            int ret = delete_recycle_txn_kv(k);
7211
14
            TEST_SYNC_POINT_CALLBACK(
7212
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7213
14
                    &ret);
7214
14
            if (ret == 1) {
7215
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7216
14
                for (int i = 1; i <= max_retry; ++i) {
7217
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7218
14
                    ret = delete_recycle_txn_kv(k);
7219
14
                    TEST_SYNC_POINT_CALLBACK(
7220
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7221
14
                            "error",
7222
14
                            &ret);
7223
14
                    if (ret != 1) {
7224
14
                        break;
7225
14
                    }
7226
                    // random sleep 0-100 ms to retry
7227
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7228
14
                }
7229
14
            }
7230
14
            return ret;
7231
14
        };
7232
7233
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7234
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7235
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7236
38.0k
                           << " txn_count=" << txn_keys.size();
7237
38.0k
                for (const auto& k : txn_keys) {
7238
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7239
38.0k
                    if (ret != 0) {
7240
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7241
38.0k
                                .tag("instance id", instance_id_)
7242
38.0k
                                .tag("key", hex(k))
7243
38.0k
                                .tag("label_key", hex(label_key));
7244
38.0k
                        return -1;
7245
38.0k
                    }
7246
38.0k
                }
7247
38.0k
                return 0;
7248
38.0k
            });
7249
38.0k
        }
7250
14
        bool finished = true;
7251
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7252
38.0k
        for (int r : rets) {
7253
38.0k
            if (r != 0) {
7254
2
                ret = -1;
7255
2
            }
7256
38.0k
        }
7257
7258
14
        ret = finished ? ret : -1;
7259
7260
        // Update metrics after all concurrent tasks completed
7261
14
        metrics_context.total_recycled_num = num_recycled.load();
7262
14
        metrics_context.report();
7263
7264
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7265
7266
14
        if (ret != 0) {
7267
6
            LOG_WARNING("recycle txn kv ret!=0")
7268
6
                    .tag("finished", finished)
7269
6
                    .tag("ret", ret)
7270
6
                    .tag("instance_id", instance_id_);
7271
6
            return ret;
7272
6
        }
7273
8
        return ret;
7274
14
    };
7275
7276
22
    if (config::enable_recycler_stats_metrics) {
7277
0
        scan_and_statistics_expired_txn_label();
7278
0
    }
7279
    // recycle_func and loop_done for scan and recycle
7280
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7281
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7282
22
}
7283
7284
struct CopyJobIdTuple {
7285
    std::string instance_id;
7286
    std::string stage_id;
7287
    long table_id;
7288
    std::string copy_id;
7289
    std::string stage_path;
7290
};
7291
struct BatchObjStoreAccessor {
7292
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7293
                          TxnKv* txn_kv)
7294
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7295
3
    ~BatchObjStoreAccessor() {
7296
3
        if (!paths_.empty()) {
7297
3
            consume();
7298
3
        }
7299
3
    }
7300
7301
    /**
7302
    * To implicitely do batch work and submit the batch delete task to s3
7303
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7304
    *
7305
    * @param copy_job The protubuf struct consists of the copy job files.
7306
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7307
    *            it would last until we finish the delete task, here we need pass one string value
7308
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7309
    */
7310
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7311
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7312
5
        auto& file_keys = copy_file_keys_[key];
7313
5
        file_keys.log_trace =
7314
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7315
5
                            instance_id, stage_id, table_id, copy_id, path);
7316
5
        std::string_view log_trace = file_keys.log_trace;
7317
2.03k
        for (const auto& file : copy_job.object_files()) {
7318
2.03k
            auto relative_path = file.relative_path();
7319
2.03k
            paths_.push_back(relative_path);
7320
2.03k
            file_keys.keys.push_back(copy_file_key(
7321
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7322
2.03k
            LOG_INFO(log_trace)
7323
2.03k
                    .tag("relative_path", relative_path)
7324
2.03k
                    .tag("batch_count", batch_count_);
7325
2.03k
        }
7326
5
        LOG_INFO(log_trace)
7327
5
                .tag("objects_num", copy_job.object_files().size())
7328
5
                .tag("batch_count", batch_count_);
7329
        // 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
7330
        // recommend using delete objects when objects num is less than 10)
7331
5
        if (paths_.size() < 1000) {
7332
3
            return;
7333
3
        }
7334
2
        consume();
7335
2
    }
7336
7337
private:
7338
5
    void consume() {
7339
5
        DORIS_CLOUD_DEFER {
7340
5
            paths_.clear();
7341
5
            copy_file_keys_.clear();
7342
5
            batch_count_++;
7343
7344
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7345
5
                        batch_count_);
7346
5
        };
7347
7348
5
        StopWatch sw;
7349
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7350
5
        if (0 != accessor_->delete_files(paths_)) {
7351
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7352
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7353
2
            return;
7354
2
        }
7355
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7356
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7357
        // delete fdb's keys
7358
3
        for (auto& file_keys : copy_file_keys_) {
7359
3
            auto& [log_trace, keys] = file_keys.second;
7360
3
            std::unique_ptr<Transaction> txn;
7361
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7362
0
                LOG(WARNING) << "failed to create txn";
7363
0
                continue;
7364
0
            }
7365
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7366
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7367
            // limited, should not cause the txn commit failed.
7368
1.02k
            for (const auto& key : keys) {
7369
1.02k
                txn->remove(key);
7370
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7371
1.02k
            }
7372
3
            txn->remove(file_keys.first);
7373
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7374
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7375
0
                continue;
7376
0
            }
7377
3
        }
7378
3
    }
7379
    std::shared_ptr<StorageVaultAccessor> accessor_;
7380
    // the path of the s3 files to be deleted
7381
    std::vector<std::string> paths_;
7382
    struct CopyFiles {
7383
        std::string log_trace;
7384
        std::vector<std::string> keys;
7385
    };
7386
    // pair<std::string, std::vector<std::string>>
7387
    // first: instance_id_ stage_id table_id query_id
7388
    // second: keys to be deleted
7389
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7390
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7391
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7392
    // which can together uniquely identifies different tasks for tracing log
7393
    uint64_t& batch_count_;
7394
    TxnKv* txn_kv_;
7395
};
7396
7397
13
int InstanceRecycler::recycle_copy_jobs() {
7398
13
    int64_t num_scanned = 0;
7399
13
    int64_t num_finished = 0;
7400
13
    int64_t num_expired = 0;
7401
13
    int64_t num_recycled = 0;
7402
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7403
13
    uint64_t batch_count = 0;
7404
13
    const std::string task_name = "recycle_copy_jobs";
7405
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7406
7407
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7408
7409
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7410
13
    register_recycle_task(task_name, start_time);
7411
7412
13
    DORIS_CLOUD_DEFER {
7413
13
        unregister_recycle_task(task_name);
7414
13
        int64_t cost =
7415
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7416
13
        metrics_context.finish_report();
7417
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7418
13
                .tag("instance_id", instance_id_)
7419
13
                .tag("num_scanned", num_scanned)
7420
13
                .tag("num_finished", num_finished)
7421
13
                .tag("num_expired", num_expired)
7422
13
                .tag("num_recycled", num_recycled);
7423
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7412
13
    DORIS_CLOUD_DEFER {
7413
13
        unregister_recycle_task(task_name);
7414
13
        int64_t cost =
7415
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7416
13
        metrics_context.finish_report();
7417
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7418
13
                .tag("instance_id", instance_id_)
7419
13
                .tag("num_scanned", num_scanned)
7420
13
                .tag("num_finished", num_finished)
7421
13
                .tag("num_expired", num_expired)
7422
13
                .tag("num_recycled", num_recycled);
7423
13
    };
7424
7425
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7426
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7427
13
    std::string key0;
7428
13
    std::string key1;
7429
13
    copy_job_key(key_info0, &key0);
7430
13
    copy_job_key(key_info1, &key1);
7431
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7432
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7433
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7434
16
                         this](std::string_view k, std::string_view v) -> int {
7435
16
        ++num_scanned;
7436
16
        CopyJobPB copy_job;
7437
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7438
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7439
0
            return -1;
7440
0
        }
7441
7442
        // decode copy job key
7443
16
        auto k1 = k;
7444
16
        k1.remove_prefix(1);
7445
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7446
16
        decode_key(&k1, &out);
7447
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7448
        // -> CopyJobPB
7449
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7450
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7451
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7452
7453
16
        bool check_storage = true;
7454
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7455
12
            ++num_finished;
7456
7457
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7458
7
                auto it = stage_accessor_map.find(stage_id);
7459
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7460
7
                std::string_view path;
7461
7
                if (it != stage_accessor_map.end()) {
7462
2
                    accessor = it->second;
7463
5
                } else {
7464
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7465
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7466
5
                                                      &inner_accessor);
7467
5
                    if (ret < 0) { // error
7468
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7469
0
                        return -1;
7470
5
                    } else if (ret == 0) {
7471
3
                        path = inner_accessor->uri();
7472
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7473
3
                                inner_accessor, batch_count, txn_kv_.get());
7474
3
                        stage_accessor_map.emplace(stage_id, accessor);
7475
3
                    } else { // stage not found, skip check storage
7476
2
                        check_storage = false;
7477
2
                    }
7478
5
                }
7479
7
                if (check_storage) {
7480
                    // TODO delete objects with key and etag is not supported
7481
5
                    accessor->add(std::move(copy_job), std::string(k),
7482
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7483
5
                    return 0;
7484
5
                }
7485
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7486
5
                int64_t current_time =
7487
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7488
5
                if (copy_job.finish_time_ms() > 0) {
7489
2
                    if (!config::force_immediate_recycle &&
7490
2
                        current_time < copy_job.finish_time_ms() +
7491
2
                                               config::copy_job_max_retention_second * 1000) {
7492
1
                        return 0;
7493
1
                    }
7494
3
                } else {
7495
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7496
3
                    if (!config::force_immediate_recycle &&
7497
3
                        current_time < copy_job.start_time_ms() +
7498
3
                                               config::copy_job_max_retention_second * 1000) {
7499
1
                        return 0;
7500
1
                    }
7501
3
                }
7502
5
            }
7503
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7504
4
            int64_t current_time =
7505
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7506
            // if copy job is timeout: delete all copy file kvs and copy job kv
7507
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7508
2
                return 0;
7509
2
            }
7510
2
            ++num_expired;
7511
2
        }
7512
7513
        // delete all copy files
7514
7
        std::vector<std::string> copy_file_keys;
7515
70
        for (auto& file : copy_job.object_files()) {
7516
70
            copy_file_keys.push_back(copy_file_key(
7517
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7518
70
        }
7519
7
        std::unique_ptr<Transaction> txn;
7520
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7521
0
            LOG(WARNING) << "failed to create txn";
7522
0
            return -1;
7523
0
        }
7524
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7525
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7526
        // limited, should not cause the txn commit failed.
7527
70
        for (const auto& key : copy_file_keys) {
7528
70
            txn->remove(key);
7529
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7530
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7531
70
                      << ", query_id=" << copy_id;
7532
70
        }
7533
7
        txn->remove(k);
7534
7
        TxnErrorCode err = txn->commit();
7535
7
        if (err != TxnErrorCode::TXN_OK) {
7536
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7537
0
            return -1;
7538
0
        }
7539
7540
7
        metrics_context.total_recycled_num = ++num_recycled;
7541
7
        metrics_context.report();
7542
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7543
7
        return 0;
7544
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
7434
16
                         this](std::string_view k, std::string_view v) -> int {
7435
16
        ++num_scanned;
7436
16
        CopyJobPB copy_job;
7437
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7438
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7439
0
            return -1;
7440
0
        }
7441
7442
        // decode copy job key
7443
16
        auto k1 = k;
7444
16
        k1.remove_prefix(1);
7445
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7446
16
        decode_key(&k1, &out);
7447
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7448
        // -> CopyJobPB
7449
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7450
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7451
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7452
7453
16
        bool check_storage = true;
7454
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7455
12
            ++num_finished;
7456
7457
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7458
7
                auto it = stage_accessor_map.find(stage_id);
7459
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7460
7
                std::string_view path;
7461
7
                if (it != stage_accessor_map.end()) {
7462
2
                    accessor = it->second;
7463
5
                } else {
7464
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7465
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7466
5
                                                      &inner_accessor);
7467
5
                    if (ret < 0) { // error
7468
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7469
0
                        return -1;
7470
5
                    } else if (ret == 0) {
7471
3
                        path = inner_accessor->uri();
7472
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7473
3
                                inner_accessor, batch_count, txn_kv_.get());
7474
3
                        stage_accessor_map.emplace(stage_id, accessor);
7475
3
                    } else { // stage not found, skip check storage
7476
2
                        check_storage = false;
7477
2
                    }
7478
5
                }
7479
7
                if (check_storage) {
7480
                    // TODO delete objects with key and etag is not supported
7481
5
                    accessor->add(std::move(copy_job), std::string(k),
7482
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7483
5
                    return 0;
7484
5
                }
7485
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7486
5
                int64_t current_time =
7487
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7488
5
                if (copy_job.finish_time_ms() > 0) {
7489
2
                    if (!config::force_immediate_recycle &&
7490
2
                        current_time < copy_job.finish_time_ms() +
7491
2
                                               config::copy_job_max_retention_second * 1000) {
7492
1
                        return 0;
7493
1
                    }
7494
3
                } else {
7495
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7496
3
                    if (!config::force_immediate_recycle &&
7497
3
                        current_time < copy_job.start_time_ms() +
7498
3
                                               config::copy_job_max_retention_second * 1000) {
7499
1
                        return 0;
7500
1
                    }
7501
3
                }
7502
5
            }
7503
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7504
4
            int64_t current_time =
7505
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7506
            // if copy job is timeout: delete all copy file kvs and copy job kv
7507
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7508
2
                return 0;
7509
2
            }
7510
2
            ++num_expired;
7511
2
        }
7512
7513
        // delete all copy files
7514
7
        std::vector<std::string> copy_file_keys;
7515
70
        for (auto& file : copy_job.object_files()) {
7516
70
            copy_file_keys.push_back(copy_file_key(
7517
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7518
70
        }
7519
7
        std::unique_ptr<Transaction> txn;
7520
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7521
0
            LOG(WARNING) << "failed to create txn";
7522
0
            return -1;
7523
0
        }
7524
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7525
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7526
        // limited, should not cause the txn commit failed.
7527
70
        for (const auto& key : copy_file_keys) {
7528
70
            txn->remove(key);
7529
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7530
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7531
70
                      << ", query_id=" << copy_id;
7532
70
        }
7533
7
        txn->remove(k);
7534
7
        TxnErrorCode err = txn->commit();
7535
7
        if (err != TxnErrorCode::TXN_OK) {
7536
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7537
0
            return -1;
7538
0
        }
7539
7540
7
        metrics_context.total_recycled_num = ++num_recycled;
7541
7
        metrics_context.report();
7542
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7543
7
        return 0;
7544
7
    };
7545
7546
13
    if (config::enable_recycler_stats_metrics) {
7547
0
        scan_and_statistics_copy_jobs();
7548
0
    }
7549
    // recycle_func and loop_done for scan and recycle
7550
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7551
13
}
7552
7553
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7554
                                             const StagePB::StageType& stage_type,
7555
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7556
5
#ifdef UNIT_TEST
7557
    // In unit test, external use the same accessor as the internal stage
7558
5
    auto it = accessor_map_.find(stage_id);
7559
5
    if (it != accessor_map_.end()) {
7560
3
        *accessor = it->second;
7561
3
    } else {
7562
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7563
2
        return 1;
7564
2
    }
7565
#else
7566
    // init s3 accessor and add to accessor map
7567
    auto stage_it =
7568
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7569
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7570
7571
    if (stage_it == instance_info_.stages().end()) {
7572
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7573
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7574
        return 1;
7575
    }
7576
7577
    const auto& object_store_info = stage_it->obj_info();
7578
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7579
7580
    S3Conf s3_conf;
7581
    if (stage_type == StagePB::EXTERNAL) {
7582
        if (stage_access_type == StagePB::AKSK) {
7583
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7584
            if (!conf) {
7585
                return -1;
7586
            }
7587
7588
            s3_conf = std::move(*conf);
7589
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7590
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7591
            if (!conf) {
7592
                return -1;
7593
            }
7594
7595
            s3_conf = std::move(*conf);
7596
            if (instance_info_.ram_user().has_encryption_info()) {
7597
                AkSkPair plain_ak_sk_pair;
7598
                int ret = decrypt_ak_sk_helper(
7599
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7600
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7601
                if (ret != 0) {
7602
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7603
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7604
                    return -1;
7605
                }
7606
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7607
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7608
            } else {
7609
                s3_conf.ak = instance_info_.ram_user().ak();
7610
                s3_conf.sk = instance_info_.ram_user().sk();
7611
            }
7612
        } else {
7613
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7614
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7615
            return -1;
7616
        }
7617
    } else if (stage_type == StagePB::INTERNAL) {
7618
        int idx = stoi(object_store_info.id());
7619
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7620
            LOG(WARNING) << "invalid idx: " << idx;
7621
            return -1;
7622
        }
7623
7624
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7625
        auto conf = S3Conf::from_obj_store_info(old_obj);
7626
        if (!conf) {
7627
            return -1;
7628
        }
7629
7630
        s3_conf = std::move(*conf);
7631
        s3_conf.prefix = object_store_info.prefix();
7632
    } else {
7633
        LOG(WARNING) << "unknown stage type " << stage_type;
7634
        return -1;
7635
    }
7636
7637
    std::shared_ptr<S3Accessor> s3_accessor;
7638
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7639
    if (ret != 0) {
7640
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7641
        return -1;
7642
    }
7643
7644
    *accessor = std::move(s3_accessor);
7645
#endif
7646
3
    return 0;
7647
5
}
7648
7649
11
int InstanceRecycler::recycle_stage() {
7650
11
    int64_t num_scanned = 0;
7651
11
    int64_t num_recycled = 0;
7652
11
    const std::string task_name = "recycle_stage";
7653
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7654
7655
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7656
7657
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7658
11
    register_recycle_task(task_name, start_time);
7659
7660
11
    DORIS_CLOUD_DEFER {
7661
11
        unregister_recycle_task(task_name);
7662
11
        int64_t cost =
7663
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7664
11
        metrics_context.finish_report();
7665
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7666
11
                .tag("instance_id", instance_id_)
7667
11
                .tag("num_scanned", num_scanned)
7668
11
                .tag("num_recycled", num_recycled);
7669
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7660
11
    DORIS_CLOUD_DEFER {
7661
11
        unregister_recycle_task(task_name);
7662
11
        int64_t cost =
7663
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7664
11
        metrics_context.finish_report();
7665
        LOG_WARNING("recycle stage, cost={}s", cost)
7666
11
                .tag("instance_id", instance_id_)
7667
11
                .tag("num_scanned", num_scanned)
7668
11
                .tag("num_recycled", num_recycled);
7669
11
    };
7670
7671
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7672
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7673
11
    std::string key0 = recycle_stage_key(key_info0);
7674
11
    std::string key1 = recycle_stage_key(key_info1);
7675
7676
11
    std::vector<std::string_view> stage_keys;
7677
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7678
11
                         this](std::string_view k, std::string_view v) -> int {
7679
1
        ++num_scanned;
7680
1
        RecycleStagePB recycle_stage;
7681
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7682
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7683
0
            return -1;
7684
0
        }
7685
7686
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7687
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7688
0
            LOG(WARNING) << "invalid idx: " << idx;
7689
0
            return -1;
7690
0
        }
7691
7692
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7693
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7694
1
                [&] {
7695
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7696
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7697
1
                    if (!s3_conf) {
7698
1
                        return -1;
7699
1
                    }
7700
7701
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7702
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7703
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7704
1
                    if (ret != 0) {
7705
1
                        return -1;
7706
1
                    }
7707
7708
1
                    accessor = std::move(s3_accessor);
7709
1
                    return 0;
7710
1
                }(),
7711
1
                "recycle_stage:get_accessor", &accessor);
7712
7713
1
        if (ret != 0) {
7714
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7715
0
            return ret;
7716
0
        }
7717
7718
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7719
1
                .tag("instance_id", instance_id_)
7720
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7721
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7722
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7723
1
                .tag("obj_info_id", idx)
7724
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7725
1
        ret = accessor->delete_all();
7726
1
        if (ret != 0) {
7727
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7728
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7729
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7730
0
                         << ", ret=" << ret;
7731
0
            return -1;
7732
0
        }
7733
1
        metrics_context.total_recycled_num = ++num_recycled;
7734
1
        metrics_context.report();
7735
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7736
1
        stage_keys.push_back(k);
7737
1
        return 0;
7738
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7678
1
                         this](std::string_view k, std::string_view v) -> int {
7679
1
        ++num_scanned;
7680
1
        RecycleStagePB recycle_stage;
7681
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7682
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7683
0
            return -1;
7684
0
        }
7685
7686
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7687
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7688
0
            LOG(WARNING) << "invalid idx: " << idx;
7689
0
            return -1;
7690
0
        }
7691
7692
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7693
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7694
1
                [&] {
7695
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7696
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7697
1
                    if (!s3_conf) {
7698
1
                        return -1;
7699
1
                    }
7700
7701
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7702
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7703
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7704
1
                    if (ret != 0) {
7705
1
                        return -1;
7706
1
                    }
7707
7708
1
                    accessor = std::move(s3_accessor);
7709
1
                    return 0;
7710
1
                }(),
7711
1
                "recycle_stage:get_accessor", &accessor);
7712
7713
1
        if (ret != 0) {
7714
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7715
0
            return ret;
7716
0
        }
7717
7718
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7719
1
                .tag("instance_id", instance_id_)
7720
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7721
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7722
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7723
1
                .tag("obj_info_id", idx)
7724
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7725
1
        ret = accessor->delete_all();
7726
1
        if (ret != 0) {
7727
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7728
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7729
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7730
0
                         << ", ret=" << ret;
7731
0
            return -1;
7732
0
        }
7733
1
        metrics_context.total_recycled_num = ++num_recycled;
7734
1
        metrics_context.report();
7735
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7736
1
        stage_keys.push_back(k);
7737
1
        return 0;
7738
1
    };
7739
7740
11
    auto loop_done = [&stage_keys, this]() -> int {
7741
1
        if (stage_keys.empty()) return 0;
7742
1
        DORIS_CLOUD_DEFER {
7743
1
            stage_keys.clear();
7744
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7742
1
        DORIS_CLOUD_DEFER {
7743
1
            stage_keys.clear();
7744
1
        };
7745
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7746
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7747
0
            return -1;
7748
0
        }
7749
1
        return 0;
7750
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7740
1
    auto loop_done = [&stage_keys, this]() -> int {
7741
1
        if (stage_keys.empty()) return 0;
7742
1
        DORIS_CLOUD_DEFER {
7743
1
            stage_keys.clear();
7744
1
        };
7745
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7746
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7747
0
            return -1;
7748
0
        }
7749
1
        return 0;
7750
1
    };
7751
11
    if (config::enable_recycler_stats_metrics) {
7752
0
        scan_and_statistics_stage();
7753
0
    }
7754
    // recycle_func and loop_done for scan and recycle
7755
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7756
11
}
7757
7758
10
int InstanceRecycler::recycle_expired_stage_objects() {
7759
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7760
7761
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7762
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7763
7764
10
    DORIS_CLOUD_DEFER {
7765
10
        int64_t cost =
7766
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7767
10
        metrics_context.finish_report();
7768
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7769
10
                .tag("instance_id", instance_id_);
7770
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7764
10
    DORIS_CLOUD_DEFER {
7765
10
        int64_t cost =
7766
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7767
10
        metrics_context.finish_report();
7768
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7769
10
                .tag("instance_id", instance_id_);
7770
10
    };
7771
7772
10
    int ret = 0;
7773
7774
10
    if (config::enable_recycler_stats_metrics) {
7775
0
        scan_and_statistics_expired_stage_objects();
7776
0
    }
7777
7778
10
    for (const auto& stage : instance_info_.stages()) {
7779
0
        std::stringstream ss;
7780
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7781
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7782
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7783
0
           << ", prefix=" << stage.obj_info().prefix();
7784
7785
0
        if (stopped()) {
7786
0
            break;
7787
0
        }
7788
0
        if (stage.type() == StagePB::EXTERNAL) {
7789
0
            continue;
7790
0
        }
7791
0
        int idx = stoi(stage.obj_info().id());
7792
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7793
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7794
0
            continue;
7795
0
        }
7796
7797
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7798
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7799
0
        if (!s3_conf) {
7800
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7801
0
            continue;
7802
0
        }
7803
7804
0
        s3_conf->prefix = stage.obj_info().prefix();
7805
0
        std::shared_ptr<S3Accessor> accessor;
7806
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7807
0
        if (ret1 != 0) {
7808
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7809
0
            ret = -1;
7810
0
            continue;
7811
0
        }
7812
7813
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7814
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7815
0
            ret = -1;
7816
0
            continue;
7817
0
        }
7818
7819
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7820
0
        int64_t expiration_time =
7821
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7822
0
                config::internal_stage_objects_expire_time_second;
7823
0
        if (config::force_immediate_recycle) {
7824
0
            expiration_time = INT64_MAX;
7825
0
        }
7826
0
        ret1 = accessor->delete_all(expiration_time);
7827
0
        if (ret1 != 0) {
7828
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7829
0
                         << ss.str();
7830
0
            ret = -1;
7831
0
            continue;
7832
0
        }
7833
0
        metrics_context.total_recycled_num++;
7834
0
        metrics_context.report();
7835
0
    }
7836
10
    return ret;
7837
10
}
7838
7839
247
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7840
247
    std::lock_guard lock(recycle_tasks_mutex);
7841
247
    running_recycle_tasks[task_name] = start_time;
7842
247
}
7843
7844
247
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7845
247
    std::lock_guard lock(recycle_tasks_mutex);
7846
247
    DCHECK(running_recycle_tasks[task_name] > 0);
7847
247
    running_recycle_tasks.erase(task_name);
7848
247
}
7849
7850
21
bool InstanceRecycler::check_recycle_tasks() {
7851
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7852
21
    {
7853
21
        std::lock_guard lock(recycle_tasks_mutex);
7854
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7855
21
    }
7856
7857
21
    bool found = false;
7858
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7859
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7860
20
        int64_t cost = now - start_time;
7861
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7862
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7863
20
                    .tag("instance_id", instance_id_)
7864
20
                    .tag("task", task_name);
7865
20
            found = true;
7866
20
        }
7867
20
    }
7868
7869
21
    return found;
7870
21
}
7871
7872
// Scan and statistics indexes that need to be recycled
7873
1
int InstanceRecycler::scan_and_statistics_indexes() {
7874
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7875
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7876
7877
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7878
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7879
1
    std::string index_key0;
7880
1
    std::string index_key1;
7881
1
    recycle_index_key(index_key_info0, &index_key0);
7882
1
    recycle_index_key(index_key_info1, &index_key1);
7883
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7884
7885
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7886
1
        RecycleIndexPB index_pb;
7887
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7888
0
            return 0;
7889
0
        }
7890
1
        int64_t current_time = ::time(nullptr);
7891
1
        if (current_time <
7892
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7893
0
            return 0;
7894
0
        }
7895
        // decode index_id
7896
1
        auto k1 = k;
7897
1
        k1.remove_prefix(1);
7898
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7899
1
        decode_key(&k1, &out);
7900
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7901
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7902
1
        std::unique_ptr<Transaction> txn;
7903
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7904
1
        if (err != TxnErrorCode::TXN_OK) {
7905
0
            return 0;
7906
0
        }
7907
1
        std::string val;
7908
1
        err = txn->get(k, &val);
7909
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7910
0
            return 0;
7911
0
        }
7912
1
        if (err != TxnErrorCode::TXN_OK) {
7913
0
            return 0;
7914
0
        }
7915
1
        index_pb.Clear();
7916
1
        if (!index_pb.ParseFromString(val)) {
7917
0
            return 0;
7918
0
        }
7919
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7920
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7921
0
                LOG_WARNING("table stream recycle index is missing binding")
7922
0
                        .tag("instance_id", instance_id_)
7923
0
                        .tag("stream_id", index_id);
7924
0
                return 0;
7925
0
            }
7926
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7927
2
                std::string end = prefix;
7928
2
                end.push_back('\xff');
7929
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7930
6
                                                              std::string_view value) {
7931
6
                    stream_metrics_context.total_need_recycle_num++;
7932
6
                    stream_metrics_context.total_need_recycle_data_size +=
7933
6
                            key.size() + value.size();
7934
6
                    return 0;
7935
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
7930
6
                                                              std::string_view value) {
7931
6
                    stream_metrics_context.total_need_recycle_num++;
7932
6
                    stream_metrics_context.total_need_recycle_data_size +=
7933
6
                            key.size() + value.size();
7934
6
                    return 0;
7935
6
                };
7936
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7937
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
7926
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7927
2
                std::string end = prefix;
7928
2
                end.push_back('\xff');
7929
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7930
2
                                                              std::string_view value) {
7931
2
                    stream_metrics_context.total_need_recycle_num++;
7932
2
                    stream_metrics_context.total_need_recycle_data_size +=
7933
2
                            key.size() + value.size();
7934
2
                    return 0;
7935
2
                };
7936
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7937
2
            };
7938
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7939
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7940
1
                    index_id);
7941
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7942
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7943
1
                    index_id);
7944
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7945
1
                scan_offset_prefix(versioned_prefix) != 0) {
7946
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7947
0
                        .tag("instance_id", instance_id_)
7948
0
                        .tag("stream_id", index_id);
7949
0
            }
7950
1
            return 0;
7951
1
        }
7952
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7953
0
            return 0;
7954
0
        }
7955
0
        metrics_context.total_need_recycle_num++;
7956
0
        return 0;
7957
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
7885
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7886
1
        RecycleIndexPB index_pb;
7887
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7888
0
            return 0;
7889
0
        }
7890
1
        int64_t current_time = ::time(nullptr);
7891
1
        if (current_time <
7892
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7893
0
            return 0;
7894
0
        }
7895
        // decode index_id
7896
1
        auto k1 = k;
7897
1
        k1.remove_prefix(1);
7898
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7899
1
        decode_key(&k1, &out);
7900
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7901
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7902
1
        std::unique_ptr<Transaction> txn;
7903
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7904
1
        if (err != TxnErrorCode::TXN_OK) {
7905
0
            return 0;
7906
0
        }
7907
1
        std::string val;
7908
1
        err = txn->get(k, &val);
7909
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7910
0
            return 0;
7911
0
        }
7912
1
        if (err != TxnErrorCode::TXN_OK) {
7913
0
            return 0;
7914
0
        }
7915
1
        index_pb.Clear();
7916
1
        if (!index_pb.ParseFromString(val)) {
7917
0
            return 0;
7918
0
        }
7919
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7920
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7921
0
                LOG_WARNING("table stream recycle index is missing binding")
7922
0
                        .tag("instance_id", instance_id_)
7923
0
                        .tag("stream_id", index_id);
7924
0
                return 0;
7925
0
            }
7926
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7927
1
                std::string end = prefix;
7928
1
                end.push_back('\xff');
7929
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7930
1
                                                              std::string_view value) {
7931
1
                    stream_metrics_context.total_need_recycle_num++;
7932
1
                    stream_metrics_context.total_need_recycle_data_size +=
7933
1
                            key.size() + value.size();
7934
1
                    return 0;
7935
1
                };
7936
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7937
1
            };
7938
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7939
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7940
1
                    index_id);
7941
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7942
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7943
1
                    index_id);
7944
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7945
1
                scan_offset_prefix(versioned_prefix) != 0) {
7946
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7947
0
                        .tag("instance_id", instance_id_)
7948
0
                        .tag("stream_id", index_id);
7949
0
            }
7950
1
            return 0;
7951
1
        }
7952
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7953
0
            return 0;
7954
0
        }
7955
0
        metrics_context.total_need_recycle_num++;
7956
0
        return 0;
7957
0
    };
7958
7959
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7960
1
    metrics_context.report(true);
7961
1
    stream_metrics_context.report(true);
7962
1
    segment_metrics_context_.report(true);
7963
1
    tablet_metrics_context_.report(true);
7964
1
    return ret;
7965
1
}
7966
7967
// Scan and statistics partitions that need to be recycled
7968
0
int InstanceRecycler::scan_and_statistics_partitions() {
7969
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7970
7971
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7972
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7973
0
    std::string part_key0;
7974
0
    std::string part_key1;
7975
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7976
7977
0
    recycle_partition_key(part_key_info0, &part_key0);
7978
0
    recycle_partition_key(part_key_info1, &part_key1);
7979
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7980
0
        RecyclePartitionPB part_pb;
7981
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7982
0
            return 0;
7983
0
        }
7984
0
        int64_t current_time = ::time(nullptr);
7985
0
        if (current_time <
7986
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7987
0
            return 0;
7988
0
        }
7989
        // decode partition_id
7990
0
        auto k1 = k;
7991
0
        k1.remove_prefix(1);
7992
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7993
0
        decode_key(&k1, &out);
7994
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7995
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7996
        // Change state to RECYCLING
7997
0
        std::unique_ptr<Transaction> txn;
7998
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7999
0
        if (err != TxnErrorCode::TXN_OK) {
8000
0
            return 0;
8001
0
        }
8002
0
        std::string val;
8003
0
        err = txn->get(k, &val);
8004
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8005
0
            return 0;
8006
0
        }
8007
0
        if (err != TxnErrorCode::TXN_OK) {
8008
0
            return 0;
8009
0
        }
8010
0
        part_pb.Clear();
8011
0
        if (!part_pb.ParseFromString(val)) {
8012
0
            return 0;
8013
0
        }
8014
        // Partitions with PREPARED state MUST have no data
8015
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
8016
0
        int ret = 0;
8017
0
        for (int64_t index_id : part_pb.index_id()) {
8018
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
8019
0
                                            partition_id, is_empty_tablet) != 0) {
8020
0
                ret = 0;
8021
0
            }
8022
0
        }
8023
0
        metrics_context.total_need_recycle_num++;
8024
0
        return ret;
8025
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_
8026
8027
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
8028
0
    metrics_context.report(true);
8029
0
    segment_metrics_context_.report(true);
8030
0
    tablet_metrics_context_.report(true);
8031
0
    return ret;
8032
0
}
8033
8034
// Scan and statistics rowsets that need to be recycled
8035
0
int InstanceRecycler::scan_and_statistics_rowsets() {
8036
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
8037
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
8038
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
8039
0
    std::string recyc_rs_key0;
8040
0
    std::string recyc_rs_key1;
8041
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
8042
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
8043
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8044
8045
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
8046
0
        RecycleRowsetPB rowset;
8047
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8048
0
            return 0;
8049
0
        }
8050
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
8051
0
        int64_t current_time = ::time(nullptr);
8052
0
        if (current_time <
8053
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
8054
0
            return 0;
8055
0
        }
8056
8057
0
        if (!rowset.has_type()) {
8058
0
            if (!rowset.has_resource_id()) [[unlikely]] {
8059
0
                return 0;
8060
0
            }
8061
0
            if (rowset.resource_id().empty()) [[unlikely]] {
8062
0
                return 0;
8063
0
            }
8064
0
            metrics_context.total_need_recycle_num++;
8065
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8066
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
8067
0
            segment_metrics_context_.total_need_recycle_data_size +=
8068
0
                    rowset.rowset_meta().total_disk_size();
8069
0
            return 0;
8070
0
        }
8071
8072
0
        if (config::enable_mark_delete_rowset_before_recycle &&
8073
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
8074
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
8075
0
            return 0;
8076
0
        }
8077
8078
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
8079
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
8080
0
                return 0;
8081
0
            }
8082
0
        }
8083
0
        metrics_context.total_need_recycle_num++;
8084
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
8085
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
8086
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8087
0
        return 0;
8088
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_
8089
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8090
0
    metrics_context.report(true);
8091
0
    segment_metrics_context_.report(true);
8092
0
    return ret;
8093
0
}
8094
8095
// Scan and statistics tmp_rowsets that need to be recycled
8096
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8097
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8098
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8099
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8100
0
    std::string tmp_rs_key0;
8101
0
    std::string tmp_rs_key1;
8102
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8103
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8104
8105
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8106
8107
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8108
0
        doris::RowsetMetaCloudPB rowset;
8109
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8110
0
            return 0;
8111
0
        }
8112
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8113
0
        int64_t current_time = ::time(nullptr);
8114
0
        if (current_time < expiration) {
8115
0
            return 0;
8116
0
        }
8117
8118
0
        DCHECK_GT(rowset.txn_id(), 0)
8119
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8120
8121
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
8122
0
            return 0;
8123
0
        }
8124
8125
0
        if (!rowset.has_resource_id()) {
8126
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8127
0
                return 0;
8128
0
            }
8129
0
            return 0;
8130
0
        }
8131
8132
0
        metrics_context.total_need_recycle_num++;
8133
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8134
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8135
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8136
0
        return 0;
8137
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_
8138
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8139
0
    metrics_context.report(true);
8140
0
    segment_metrics_context_.report(true);
8141
0
    return ret;
8142
0
}
8143
8144
// Scan and statistics abort_timeout_txn that need to be recycled
8145
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8146
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8147
8148
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8149
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8150
0
    std::string begin_txn_running_key;
8151
0
    std::string end_txn_running_key;
8152
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8153
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8154
8155
0
    int64_t current_time =
8156
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8157
8158
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8159
0
                                               std::string_view k, std::string_view v) -> int {
8160
0
        std::unique_ptr<Transaction> txn;
8161
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8162
0
        if (err != TxnErrorCode::TXN_OK) {
8163
0
            return 0;
8164
0
        }
8165
0
        std::string_view k1 = k;
8166
0
        k1.remove_prefix(1);
8167
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8168
0
        if (decode_key(&k1, &out) != 0) {
8169
0
            return 0;
8170
0
        }
8171
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8172
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8173
        // Update txn_info
8174
0
        std::string txn_inf_key, txn_inf_val;
8175
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8176
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8177
0
        if (err != TxnErrorCode::TXN_OK) {
8178
0
            return 0;
8179
0
        }
8180
0
        TxnInfoPB txn_info;
8181
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8182
0
            return 0;
8183
0
        }
8184
8185
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8186
0
            TxnRunningPB txn_running_pb;
8187
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8188
0
                return 0;
8189
0
            }
8190
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8191
0
                return 0;
8192
0
            }
8193
0
            metrics_context.total_need_recycle_num++;
8194
0
        }
8195
0
        return 0;
8196
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_
8197
8198
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
8199
0
                               std::move(handle_abort_timeout_txn_kv));
8200
0
    metrics_context.report(true);
8201
0
    return ret;
8202
0
}
8203
8204
// Scan and statistics expired_txn_label that need to be recycled
8205
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8206
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8207
8208
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8209
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8210
0
    std::string begin_recycle_txn_key;
8211
0
    std::string end_recycle_txn_key;
8212
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8213
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8214
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8215
0
    int64_t current_time_ms =
8216
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8217
8218
    // for calculate the total num or bytes of recyled objects
8219
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8220
0
        RecycleTxnPB recycle_txn_pb;
8221
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8222
0
            return 0;
8223
0
        }
8224
0
        if ((config::force_immediate_recycle) ||
8225
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8226
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8227
0
             current_time_ms)) {
8228
0
            metrics_context.total_need_recycle_num++;
8229
0
        }
8230
0
        return 0;
8231
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_
8232
8233
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
8234
0
                               std::move(handle_expired_txn_label_kv));
8235
0
    metrics_context.report(true);
8236
0
    return ret;
8237
0
}
8238
8239
// Scan and statistics copy_jobs that need to be recycled
8240
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8241
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8242
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8243
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8244
0
    std::string key0;
8245
0
    std::string key1;
8246
0
    copy_job_key(key_info0, &key0);
8247
0
    copy_job_key(key_info1, &key1);
8248
8249
    // for calculate the total num or bytes of recyled objects
8250
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8251
0
        CopyJobPB copy_job;
8252
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8253
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8254
0
            return 0;
8255
0
        }
8256
8257
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8258
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8259
0
                int64_t current_time =
8260
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8261
0
                if (copy_job.finish_time_ms() > 0) {
8262
0
                    if (!config::force_immediate_recycle &&
8263
0
                        current_time < copy_job.finish_time_ms() +
8264
0
                                               config::copy_job_max_retention_second * 1000) {
8265
0
                        return 0;
8266
0
                    }
8267
0
                } else {
8268
0
                    if (!config::force_immediate_recycle &&
8269
0
                        current_time < copy_job.start_time_ms() +
8270
0
                                               config::copy_job_max_retention_second * 1000) {
8271
0
                        return 0;
8272
0
                    }
8273
0
                }
8274
0
            }
8275
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8276
0
            int64_t current_time =
8277
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8278
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8279
0
                return 0;
8280
0
            }
8281
0
        }
8282
0
        metrics_context.total_need_recycle_num++;
8283
0
        return 0;
8284
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_
8285
8286
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8287
0
    metrics_context.report(true);
8288
0
    return ret;
8289
0
}
8290
8291
// Scan and statistics stage that need to be recycled
8292
0
int InstanceRecycler::scan_and_statistics_stage() {
8293
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8294
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8295
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8296
0
    std::string key0 = recycle_stage_key(key_info0);
8297
0
    std::string key1 = recycle_stage_key(key_info1);
8298
8299
    // for calculate the total num or bytes of recyled objects
8300
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8301
0
                                                        std::string_view v) -> int {
8302
0
        RecycleStagePB recycle_stage;
8303
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8304
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8305
0
            return 0;
8306
0
        }
8307
8308
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8309
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8310
0
            LOG(WARNING) << "invalid idx: " << idx;
8311
0
            return 0;
8312
0
        }
8313
8314
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8315
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8316
0
                [&] {
8317
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8318
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8319
0
                    if (!s3_conf) {
8320
0
                        return 0;
8321
0
                    }
8322
8323
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8324
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8325
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8326
0
                    if (ret != 0) {
8327
0
                        return 0;
8328
0
                    }
8329
8330
0
                    accessor = std::move(s3_accessor);
8331
0
                    return 0;
8332
0
                }(),
8333
0
                "recycle_stage:get_accessor", &accessor);
8334
8335
0
        if (ret != 0) {
8336
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8337
0
            return 0;
8338
0
        }
8339
8340
0
        metrics_context.total_need_recycle_num++;
8341
0
        return 0;
8342
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_
8343
8344
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8345
0
    metrics_context.report(true);
8346
0
    return ret;
8347
0
}
8348
8349
// Scan and statistics expired_stage_objects that need to be recycled
8350
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8351
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8352
8353
    // for calculate the total num or bytes of recyled objects
8354
0
    auto scan_and_statistics = [&metrics_context, this]() {
8355
0
        for (const auto& stage : instance_info_.stages()) {
8356
0
            if (stopped()) {
8357
0
                break;
8358
0
            }
8359
0
            if (stage.type() == StagePB::EXTERNAL) {
8360
0
                continue;
8361
0
            }
8362
0
            int idx = stoi(stage.obj_info().id());
8363
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8364
0
                continue;
8365
0
            }
8366
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8367
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8368
0
            if (!s3_conf) {
8369
0
                continue;
8370
0
            }
8371
0
            s3_conf->prefix = stage.obj_info().prefix();
8372
0
            std::shared_ptr<S3Accessor> accessor;
8373
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8374
0
            if (ret1 != 0) {
8375
0
                continue;
8376
0
            }
8377
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8378
0
                continue;
8379
0
            }
8380
0
            metrics_context.total_need_recycle_num++;
8381
0
        }
8382
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8383
8384
0
    scan_and_statistics();
8385
0
    metrics_context.report(true);
8386
0
    return 0;
8387
0
}
8388
8389
// Scan and statistics versions that need to be recycled
8390
0
int InstanceRecycler::scan_and_statistics_versions() {
8391
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8392
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8393
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8394
8395
0
    int64_t last_scanned_table_id = 0;
8396
0
    bool is_recycled = false; // Is last scanned kv recycled
8397
    // for calculate the total num or bytes of recyled objects
8398
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8399
0
                                       std::string_view k, std::string_view) {
8400
0
        auto k1 = k;
8401
0
        k1.remove_prefix(1);
8402
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8403
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8404
0
        decode_key(&k1, &out);
8405
0
        DCHECK_EQ(out.size(), 6) << k;
8406
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8407
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8408
0
            metrics_context.total_need_recycle_num +=
8409
0
                    is_recycled; // Version kv of this table has been recycled
8410
0
            return 0;
8411
0
        }
8412
0
        last_scanned_table_id = table_id;
8413
0
        is_recycled = false;
8414
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8415
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8416
0
        std::unique_ptr<Transaction> txn;
8417
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8418
0
        if (err != TxnErrorCode::TXN_OK) {
8419
0
            return 0;
8420
0
        }
8421
0
        std::unique_ptr<RangeGetIterator> iter;
8422
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8423
0
        if (err != TxnErrorCode::TXN_OK) {
8424
0
            return 0;
8425
0
        }
8426
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8427
0
            return 0;
8428
0
        }
8429
0
        metrics_context.total_need_recycle_num++;
8430
0
        is_recycled = true;
8431
0
        return 0;
8432
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_
8433
8434
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8435
0
    metrics_context.report(true);
8436
0
    return ret;
8437
0
}
8438
8439
// Scan and statistics restore jobs that need to be recycled
8440
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8441
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8442
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8443
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8444
0
    std::string restore_job_key0;
8445
0
    std::string restore_job_key1;
8446
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8447
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8448
8449
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8450
8451
    // for calculate the total num or bytes of recyled objects
8452
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8453
0
        RestoreJobCloudPB restore_job_pb;
8454
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8455
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8456
0
            return 0;
8457
0
        }
8458
0
        int64_t expiration =
8459
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8460
0
        int64_t current_time = ::time(nullptr);
8461
0
        if (current_time < expiration) { // not expired
8462
0
            return 0;
8463
0
        }
8464
0
        metrics_context.total_need_recycle_num++;
8465
0
        if (restore_job_pb.need_recycle_data()) {
8466
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8467
0
        }
8468
0
        return 0;
8469
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_
8470
8471
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8472
0
    metrics_context.report(true);
8473
0
    return ret;
8474
0
}
8475
8476
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8477
3
    if (!should_recycle_versioned_keys()) {
8478
0
        return;
8479
0
    }
8480
8481
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8482
8483
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8484
3
    if (recycle_checker.init() != 0) {
8485
0
        return;
8486
0
    }
8487
8488
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8489
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8490
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8491
8492
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8493
8
    for (; iter->valid(); iter->next()) {
8494
5
        OperationLogPB operation_log;
8495
5
        if (!iter->parse_value(&operation_log)) {
8496
0
            continue;
8497
0
        }
8498
8499
5
        std::string_view key = iter->key();
8500
5
        Versionstamp log_versionstamp;
8501
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8502
0
            continue;
8503
0
        }
8504
8505
5
        OperationLogReferenceInfo ref_info;
8506
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8507
5
                                        &ref_info)) {
8508
4
            metrics_context.total_need_recycle_num++;
8509
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8510
4
        }
8511
5
    }
8512
8513
3
    metrics_context.report(true);
8514
3
}
8515
8516
int InstanceRecycler::classify_rowset_task_by_ref_count(
8517
61
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8518
61
    constexpr int MAX_RETRY = 10;
8519
61
    const auto& rowset_meta = task.rowset_meta;
8520
61
    int64_t tablet_id = rowset_meta.tablet_id();
8521
61
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8522
61
    std::string_view reference_instance_id = instance_id_;
8523
61
    if (rowset_meta.has_reference_instance_id()) {
8524
5
        reference_instance_id = rowset_meta.reference_instance_id();
8525
5
    }
8526
8527
62
    for (int i = 0; i < MAX_RETRY; ++i) {
8528
62
        std::unique_ptr<Transaction> txn;
8529
62
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8530
62
        if (err != TxnErrorCode::TXN_OK) {
8531
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8532
0
                    .tag("instance_id", instance_id_)
8533
0
                    .tag("tablet_id", tablet_id)
8534
0
                    .tag("rowset_id", rowset_id)
8535
0
                    .tag("err", err);
8536
0
            return -1;
8537
0
        }
8538
8539
62
        std::string rowset_ref_count_key =
8540
62
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8541
62
        task.rowset_ref_count_key = rowset_ref_count_key;
8542
8543
62
        int64_t ref_count = 0;
8544
62
        {
8545
62
            std::string value;
8546
62
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8547
62
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8548
0
                ref_count = 1;
8549
62
            } else if (err != TxnErrorCode::TXN_OK) {
8550
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8551
0
                        .tag("instance_id", instance_id_)
8552
0
                        .tag("tablet_id", tablet_id)
8553
0
                        .tag("rowset_id", rowset_id)
8554
0
                        .tag("err", err);
8555
0
                return -1;
8556
62
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8557
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8558
0
                        .tag("instance_id", instance_id_)
8559
0
                        .tag("tablet_id", tablet_id)
8560
0
                        .tag("rowset_id", rowset_id)
8561
0
                        .tag("value", hex(value));
8562
0
                return -1;
8563
0
            }
8564
62
        }
8565
8566
62
        if (ref_count > 1) {
8567
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8568
12
            txn->atomic_add(rowset_ref_count_key, -1);
8569
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8570
12
                    .tag("instance_id", instance_id_)
8571
12
                    .tag("tablet_id", tablet_id)
8572
12
                    .tag("rowset_id", rowset_id)
8573
12
                    .tag("ref_count", ref_count - 1)
8574
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8575
8576
12
            if (!task.recycle_rowset_key.empty()) {
8577
0
                txn->remove(task.recycle_rowset_key);
8578
0
                LOG_INFO("remove recycle rowset key in classification phase")
8579
0
                        .tag("key", hex(task.recycle_rowset_key));
8580
0
            }
8581
12
            if (!task.non_versioned_rowset_key.empty()) {
8582
12
                txn->remove(task.non_versioned_rowset_key);
8583
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8584
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8585
12
            }
8586
8587
12
            err = txn->commit();
8588
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8589
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8590
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8591
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8592
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8593
1
                continue;
8594
11
            } else if (err != TxnErrorCode::TXN_OK) {
8595
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8596
0
                        .tag("instance_id", instance_id_)
8597
0
                        .tag("tablet_id", tablet_id)
8598
0
                        .tag("rowset_id", rowset_id)
8599
0
                        .tag("err", err);
8600
0
                return -1;
8601
0
            }
8602
11
            return 1; // handled, not added to batch delete
8603
50
        } else {
8604
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8605
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8606
50
            LOG_INFO("add rowset to batch delete plan")
8607
50
                    .tag("instance_id", instance_id_)
8608
50
                    .tag("tablet_id", tablet_id)
8609
50
                    .tag("rowset_id", rowset_id)
8610
50
                    .tag("resource_id", rowset_meta.resource_id())
8611
50
                    .tag("ref_count", ref_count);
8612
8613
50
            batch_delete_tasks.push_back(std::move(task));
8614
50
            return 0; // added to batch delete
8615
50
        }
8616
62
    }
8617
8618
0
    LOG_WARNING("failed to classify rowset task after retry")
8619
0
            .tag("instance_id", instance_id_)
8620
0
            .tag("tablet_id", tablet_id)
8621
0
            .tag("rowset_id", rowset_id)
8622
0
            .tag("retry", MAX_RETRY);
8623
0
    return -1;
8624
61
}
8625
8626
11
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8627
11
    int ret = 0;
8628
50
    for (const auto& task : tasks) {
8629
50
        int64_t tablet_id = task.rowset_meta.tablet_id();
8630
50
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8631
8632
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8633
        // so we don't need to call it again here.
8634
8635
        // Remove all metadata keys in one transaction
8636
50
        std::unique_ptr<Transaction> txn;
8637
50
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8638
50
        if (err != TxnErrorCode::TXN_OK) {
8639
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8640
0
                    .tag("instance_id", instance_id_)
8641
0
                    .tag("tablet_id", tablet_id)
8642
0
                    .tag("rowset_id", rowset_id)
8643
0
                    .tag("err", err);
8644
0
            ret = -1;
8645
0
            continue;
8646
0
        }
8647
8648
50
        std::string_view reference_instance_id = instance_id_;
8649
50
        if (task.rowset_meta.has_reference_instance_id()) {
8650
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8651
0
        }
8652
8653
50
        txn->remove(task.rowset_ref_count_key);
8654
50
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8655
50
                .tag("instance_id", instance_id_)
8656
50
                .tag("tablet_id", tablet_id)
8657
50
                .tag("rowset_id", rowset_id)
8658
50
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8659
8660
50
        std::string dbm_start_key =
8661
50
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8662
50
        std::string dbm_end_key = meta_delete_bitmap_key(
8663
50
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8664
50
                 std::numeric_limits<int64_t>::max()});
8665
50
        txn->remove(dbm_start_key, dbm_end_key);
8666
50
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8667
50
                .tag("instance_id", instance_id_)
8668
50
                .tag("tablet_id", tablet_id)
8669
50
                .tag("rowset_id", rowset_id)
8670
50
                .tag("begin", hex(dbm_start_key))
8671
50
                .tag("end", hex(dbm_end_key));
8672
8673
50
        std::string versioned_dbm_start_key =
8674
50
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8675
50
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8676
50
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8677
50
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8678
50
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8679
50
                .tag("instance_id", instance_id_)
8680
50
                .tag("tablet_id", tablet_id)
8681
50
                .tag("rowset_id", rowset_id)
8682
50
                .tag("begin", hex(versioned_dbm_start_key))
8683
50
                .tag("end", hex(versioned_dbm_end_key));
8684
8685
        // Remove versioned meta rowset key
8686
50
        if (!task.versioned_rowset_key.empty()) {
8687
50
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8688
50
                                                          task.versionstamp);
8689
50
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8690
50
                    .tag("instance_id", instance_id_)
8691
50
                    .tag("tablet_id", tablet_id)
8692
50
                    .tag("rowset_id", rowset_id)
8693
50
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8694
50
        }
8695
8696
50
        if (!task.non_versioned_rowset_key.empty()) {
8697
50
            txn->remove(task.non_versioned_rowset_key);
8698
50
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8699
50
                    .tag("instance_id", instance_id_)
8700
50
                    .tag("tablet_id", tablet_id)
8701
50
                    .tag("rowset_id", rowset_id)
8702
50
                    .tag("key", hex(task.non_versioned_rowset_key));
8703
50
        }
8704
8705
        // Remove recycle_rowset_key last to ensure retry safety:
8706
        // if cleanup fails, this key remains and triggers next round retry.
8707
50
        if (!task.recycle_rowset_key.empty()) {
8708
0
            txn->remove(task.recycle_rowset_key);
8709
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8710
0
                    .tag("instance_id", instance_id_)
8711
0
                    .tag("tablet_id", tablet_id)
8712
0
                    .tag("rowset_id", rowset_id)
8713
0
                    .tag("key", hex(task.recycle_rowset_key));
8714
0
        }
8715
8716
50
        err = txn->commit();
8717
50
        if (err != TxnErrorCode::TXN_OK) {
8718
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8719
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8720
0
                    .tag("instance_id", instance_id_)
8721
0
                    .tag("tablet_id", tablet_id)
8722
0
                    .tag("rowset_id", rowset_id)
8723
0
                    .tag("err", err);
8724
0
            ret = -1;
8725
0
            continue;
8726
0
        }
8727
8728
50
        LOG_INFO("cleanup rowset metadata success")
8729
50
                .tag("instance_id", instance_id_)
8730
50
                .tag("tablet_id", tablet_id)
8731
50
                .tag("rowset_id", rowset_id);
8732
50
    }
8733
11
    return ret;
8734
11
}
8735
8736
} // namespace doris::cloud