Coverage Report

Created: 2026-11-03 19:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
constexpr size_t kRowsetBatchGetSize = 256;
89
90
0
int64_t packed_file_retry_sleep_ms() {
91
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
92
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
93
0
    thread_local std::mt19937_64 gen(std::random_device {}());
94
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
95
0
    return dist(gen);
96
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
97
98
0
void sleep_for_packed_file_retry() {
99
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
100
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
101
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
110
111
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
948k
    const auto& locations = rowset.packed_slice_locations();
113
948k
    auto it = locations.find(path);
114
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
948k
           !it->second.packed_file_path().empty();
116
948k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
7
    const auto& locations = rowset.packed_slice_locations();
113
7
    auto it = locations.find(path);
114
7
    return it != locations.end() && it->second.has_packed_file_path() &&
115
7
           !it->second.packed_file_path().empty();
116
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
948k
    const auto& locations = rowset.packed_slice_locations();
113
948k
    auto it = locations.find(path);
114
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
948k
           !it->second.packed_file_path().empty();
116
948k
}
117
118
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
119
                                      const std::string& path,
120
949k
                                      std::vector<std::string>* file_paths) {
121
949k
    if (!is_packed_slice_path(rowset, path)) {
122
920k
        file_paths->push_back(path);
123
920k
    }
124
949k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
7
                                      std::vector<std::string>* file_paths) {
121
7
    if (!is_packed_slice_path(rowset, path)) {
122
7
        file_paths->push_back(path);
123
7
    }
124
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
949k
                                      std::vector<std::string>* file_paths) {
121
949k
    if (!is_packed_slice_path(rowset, path)) {
122
920k
        file_paths->push_back(path);
123
920k
    }
124
949k
}
125
126
} // namespace
127
128
// return 0 for success get a key, 1 for key not found, negative for error
129
2.59k
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
2.59k
    std::unique_ptr<Transaction> txn;
131
2.59k
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
2.59k
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
2.59k
    switch (txn->get(key, &val, true)) {
136
32
    case TxnErrorCode::TXN_OK:
137
32
        return 0;
138
2.56k
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
2.56k
        return 1;
140
0
    default:
141
0
        return -1;
142
2.59k
    };
143
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
16
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
16
    std::unique_ptr<Transaction> txn;
131
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
16
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
16
    switch (txn->get(key, &val, true)) {
136
3
    case TxnErrorCode::TXN_OK:
137
3
        return 0;
138
13
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
13
        return 1;
140
0
    default:
141
0
        return -1;
142
16
    };
143
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
2.57k
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
2.57k
    std::unique_ptr<Transaction> txn;
131
2.57k
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
2.57k
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
2.57k
    switch (txn->get(key, &val, true)) {
136
29
    case TxnErrorCode::TXN_OK:
137
29
        return 0;
138
2.54k
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
2.54k
        return 1;
140
0
    default:
141
0
        return -1;
142
2.57k
    };
143
0
}
144
145
// 0 for success, negative for error
146
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
147
692
                   std::unique_ptr<RangeGetIterator>& it) {
148
692
    std::unique_ptr<Transaction> txn;
149
692
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
692
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
692
    switch (txn->get(begin, end, &it, true)) {
154
692
    case TxnErrorCode::TXN_OK:
155
692
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
692
    };
161
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
31
                   std::unique_ptr<RangeGetIterator>& it) {
148
31
    std::unique_ptr<Transaction> txn;
149
31
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
31
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
31
    switch (txn->get(begin, end, &it, true)) {
154
31
    case TxnErrorCode::TXN_OK:
155
31
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
31
    };
161
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
147
661
                   std::unique_ptr<RangeGetIterator>& it) {
148
661
    std::unique_ptr<Transaction> txn;
149
661
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
661
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
661
    switch (txn->get(begin, end, &it, true)) {
154
661
    case TxnErrorCode::TXN_OK:
155
661
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
661
    };
161
0
}
162
163
// return 0 for success otherwise error
164
6
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
6
    std::unique_ptr<Transaction> txn;
166
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
6
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
10
    for (auto k : keys) {
171
10
        txn->remove(k);
172
10
    }
173
6
    switch (txn->commit()) {
174
6
    case TxnErrorCode::TXN_OK:
175
6
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
6
    }
181
6
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
164
1
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
1
    std::unique_ptr<Transaction> txn;
166
1
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
1
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
1
    for (auto k : keys) {
171
1
        txn->remove(k);
172
1
    }
173
1
    switch (txn->commit()) {
174
1
    case TxnErrorCode::TXN_OK:
175
1
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
1
    }
181
1
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
164
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
165
5
    std::unique_ptr<Transaction> txn;
166
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
167
5
    if (err != TxnErrorCode::TXN_OK) {
168
0
        return -1;
169
0
    }
170
9
    for (auto k : keys) {
171
9
        txn->remove(k);
172
9
    }
173
5
    switch (txn->commit()) {
174
5
    case TxnErrorCode::TXN_OK:
175
5
        return 0;
176
0
    case TxnErrorCode::TXN_CONFLICT:
177
0
        return -1;
178
0
    default:
179
0
        return -1;
180
5
    }
181
5
}
182
183
// return 0 for success otherwise error
184
10.9k
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
10.9k
    std::unique_ptr<Transaction> txn;
186
10.9k
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
10.9k
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
206k
    for (auto& k : keys) {
191
206k
        txn->remove(k);
192
206k
    }
193
10.9k
    switch (txn->commit()) {
194
10.9k
    case TxnErrorCode::TXN_OK:
195
10.9k
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
10.9k
    }
201
10.9k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
40
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
40
    std::unique_ptr<Transaction> txn;
186
40
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
40
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
40
    for (auto& k : keys) {
191
17
        txn->remove(k);
192
17
    }
193
40
    switch (txn->commit()) {
194
40
    case TxnErrorCode::TXN_OK:
195
40
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
40
    }
201
40
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
184
10.9k
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
185
10.9k
    std::unique_ptr<Transaction> txn;
186
10.9k
    TxnErrorCode err = txn_kv->create_txn(&txn);
187
10.9k
    if (err != TxnErrorCode::TXN_OK) {
188
0
        return -1;
189
0
    }
190
206k
    for (auto& k : keys) {
191
206k
        txn->remove(k);
192
206k
    }
193
10.9k
    switch (txn->commit()) {
194
10.9k
    case TxnErrorCode::TXN_OK:
195
10.9k
        return 0;
196
0
    case TxnErrorCode::TXN_CONFLICT:
197
0
        return -1;
198
0
    default:
199
0
        return -1;
200
10.9k
    }
201
10.9k
}
202
203
// return 0 for success otherwise error
204
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
205
142k
                                       std::string_view end) {
206
142k
    std::unique_ptr<Transaction> txn;
207
142k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
142k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
142k
    txn->remove(begin, end);
212
142k
    switch (txn->commit()) {
213
142k
    case TxnErrorCode::TXN_OK:
214
142k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
142k
    }
220
142k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
14
                                       std::string_view end) {
206
14
    std::unique_ptr<Transaction> txn;
207
14
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
14
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
14
    txn->remove(begin, end);
212
14
    switch (txn->commit()) {
213
14
    case TxnErrorCode::TXN_OK:
214
14
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
14
    }
220
14
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
205
142k
                                       std::string_view end) {
206
142k
    std::unique_ptr<Transaction> txn;
207
142k
    TxnErrorCode err = txn_kv->create_txn(&txn);
208
142k
    if (err != TxnErrorCode::TXN_OK) {
209
0
        return -1;
210
0
    }
211
142k
    txn->remove(begin, end);
212
142k
    switch (txn->commit()) {
213
142k
    case TxnErrorCode::TXN_OK:
214
142k
        return 0;
215
0
    case TxnErrorCode::TXN_CONFLICT:
216
0
        return -1;
217
0
    default:
218
0
        return -1;
219
142k
    }
220
142k
}
221
222
// Remove versioned delete bitmap keys grouped by rowset.
223
// Each inner vector represents all DBM shard keys for one rowset that MUST be deleted
224
// atomically in the same txn. Transaction splitting only occurs between rowsets, never
225
// within a rowset's shard keys.
226
//
227
// This ensures that a DBM blob with multiple shards is either fully deleted or not
228
// deleted at all, preventing partial deletion that would leave the blob unrecoverable.
229
//
230
// return 0 for success otherwise error
231
static int delete_versioned_delete_bitmap_by_rowset(
232
54
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
54
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
53
    size_t idx = 0;
237
107
    while (idx < rowset_dbm_key_groups.size()) {
238
54
        std::unique_ptr<Transaction> txn;
239
54
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
54
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
54
        bool has_keys = false;
245
11.6k
        while (idx < rowset_dbm_key_groups.size()) {
246
11.5k
            const auto& keys = rowset_dbm_key_groups[idx];
247
11.5k
            const auto keys_bytes =
248
11.5k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
249
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
249
11.6k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
250
251
11.5k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
252
1
                break;
253
1
            }
254
255
11.6k
            for (const auto& key : keys) {
256
11.6k
                txn->remove(key);
257
11.6k
            }
258
259
11.5k
            has_keys = true;
260
11.5k
            ++idx;
261
11.5k
        }
262
263
54
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
54
        err = txn->commit();
265
54
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
54
    }
270
53
    return 0;
271
53
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
recycler_test.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
Line
Count
Source
232
54
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
54
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
53
    size_t idx = 0;
237
107
    while (idx < rowset_dbm_key_groups.size()) {
238
54
        std::unique_ptr<Transaction> txn;
239
54
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
54
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
54
        bool has_keys = false;
245
11.6k
        while (idx < rowset_dbm_key_groups.size()) {
246
11.5k
            const auto& keys = rowset_dbm_key_groups[idx];
247
11.5k
            const auto keys_bytes =
248
11.5k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
249
11.5k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
250
251
11.5k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
252
1
                break;
253
1
            }
254
255
11.6k
            for (const auto& key : keys) {
256
11.6k
                txn->remove(key);
257
11.6k
            }
258
259
11.5k
            has_keys = true;
260
11.5k
            ++idx;
261
11.5k
        }
262
263
54
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
54
        err = txn->commit();
265
54
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
54
    }
270
53
    return 0;
271
53
}
272
273
void scan_restore_job_rowset(
274
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
275
        std::string& msg,
276
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
277
278
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
279
                                      int64_t num_scanned, int64_t num_recycled,
280
323
                                      int64_t start_time) {
281
323
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
282
0
        int64_t cost =
283
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
284
0
        if (cost > config::recycle_task_threshold_seconds) {
285
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
286
0
                    .tag("instance_id", instance_id)
287
0
                    .tag("task", task_name)
288
0
                    .tag("num_scanned", num_scanned)
289
0
                    .tag("num_recycled", num_recycled);
290
0
        }
291
0
    }
292
323
    return;
293
323
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
280
2
                                      int64_t start_time) {
281
2
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
282
0
        int64_t cost =
283
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
284
0
        if (cost > config::recycle_task_threshold_seconds) {
285
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
286
0
                    .tag("instance_id", instance_id)
287
0
                    .tag("task", task_name)
288
0
                    .tag("num_scanned", num_scanned)
289
0
                    .tag("num_recycled", num_recycled);
290
0
        }
291
0
    }
292
2
    return;
293
2
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
280
321
                                      int64_t start_time) {
281
321
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
282
0
        int64_t cost =
283
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
284
0
        if (cost > config::recycle_task_threshold_seconds) {
285
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
286
0
                    .tag("instance_id", instance_id)
287
0
                    .tag("task", task_name)
288
0
                    .tag("num_scanned", num_scanned)
289
0
                    .tag("num_recycled", num_recycled);
290
0
        }
291
0
    }
292
321
    return;
293
321
}
294
295
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
296
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
297
298
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
299
6
                                                               "s3_producer_pool");
300
6
    s3_producer_pool->start();
301
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
302
6
                                                                  "recycle_tablet_pool");
303
6
    recycle_tablet_pool->start();
304
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
305
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
306
6
    group_recycle_function_pool->start();
307
6
    _thread_pool_group =
308
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
309
6
                                    std::move(group_recycle_function_pool));
310
311
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
312
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
313
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
314
6
}
315
316
6
Recycler::~Recycler() {
317
6
    if (!stopped()) {
318
0
        stop();
319
0
    }
320
6
}
321
322
5
void Recycler::instance_scanner_callback() {
323
    // sleep 60 seconds before scheduling for the launch procedure to complete:
324
    // some bad hdfs connection may cause some log to stdout stderr
325
    // which may pollute .out file and affect the script to check success
326
5
    std::this_thread::sleep_for(
327
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
328
673
    while (!stopped()) {
329
668
        if (config::enable_recycler) {
330
4
            std::vector<InstanceInfoPB> instances;
331
4
            get_all_instances(txn_kv_.get(), instances);
332
            // TODO(plat1ko): delete job recycle kv of non-existent instances
333
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
334
4
                std::stringstream ss;
335
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
336
4
                return ss.str();
337
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
333
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
334
4
                std::stringstream ss;
335
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
336
4
                return ss.str();
337
4
            }();
338
4
            if (!instances.empty()) {
339
                // enqueue instances
340
3
                std::lock_guard lock(mtx_);
341
30
                for (auto& instance : instances) {
342
30
                    if (filter_out_instance(instance.instance_id())) continue;
343
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
344
                    // skip instance already in pending queue
345
30
                    if (success) {
346
30
                        pending_instance_queue_.push_back(std::move(instance));
347
30
                    }
348
30
                }
349
3
                pending_instance_cond_.notify_all();
350
3
            }
351
664
        } else {
352
664
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
353
664
        }
354
668
        {
355
668
            std::unique_lock lock(mtx_);
356
668
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
357
1.33k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
357
1.33k
                               [&]() { return stopped(); });
358
668
        }
359
668
    }
360
5
}
361
362
9
void Recycler::recycle_callback() {
363
40
    while (!stopped()) {
364
38
        InstanceInfoPB instance;
365
38
        {
366
38
            std::unique_lock lock(mtx_);
367
38
            pending_instance_cond_.wait(
368
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
368
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
369
38
            if (stopped()) {
370
7
                return;
371
7
            }
372
31
            instance = std::move(pending_instance_queue_.front());
373
31
            pending_instance_queue_.pop_front();
374
31
            pending_instance_set_.erase(instance.instance_id());
375
31
        }
376
0
        auto& instance_id = instance.instance_id();
377
31
        {
378
31
            std::lock_guard lock(mtx_);
379
            // skip instance in recycling
380
31
            if (recycling_instance_map_.count(instance_id)) continue;
381
31
        }
382
31
        if (!config::enable_recycler) {
383
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
384
1
                         << " since enable_recycler is false";
385
1
            continue;
386
1
        }
387
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
388
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
389
390
30
        if (int r = instance_recycler->init(); r != 0) {
391
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
392
0
                         << " ret=" << r;
393
0
            continue;
394
0
        }
395
30
        std::string recycle_job_key;
396
30
        job_recycle_key({instance_id}, &recycle_job_key);
397
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
398
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
399
30
        if (ret != 0) { // Prepare failed
400
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
401
20
                         << " ret=" << ret;
402
20
            continue;
403
20
        } else {
404
10
            std::lock_guard lock(mtx_);
405
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
406
10
        }
407
10
        if (stopped()) return;
408
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
409
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
410
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
411
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
412
10
        ret = instance_recycler->do_recycle();
413
        // If instance recycler has been aborted, don't finish this job
414
415
10
        if (!instance_recycler->stopped()) {
416
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
417
10
                                        ret == 0, ctime_ms);
418
10
        }
419
10
        if (instance_recycler->stopped() || ret != 0) {
420
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
421
0
        }
422
10
        {
423
10
            std::lock_guard lock(mtx_);
424
10
            recycling_instance_map_.erase(instance_id);
425
10
        }
426
427
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
428
10
        auto elpased_ms = now - ctime_ms;
429
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
430
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
431
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
432
10
                                             now + config::recycle_interval_seconds * 1000);
433
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
434
10
        LOG(INFO) << "recycle instance done, "
435
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
436
10
                  << " now: " << now;
437
438
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
439
440
10
        LOG_WARNING("finish recycle instance")
441
10
                .tag("instance_id", instance_id)
442
10
                .tag("cost_ms", elpased_ms);
443
10
    }
444
9
}
445
446
4
void Recycler::lease_recycle_jobs() {
447
55
    while (!stopped()) {
448
51
        std::vector<std::string> instances;
449
51
        instances.reserve(recycling_instance_map_.size());
450
51
        {
451
51
            std::lock_guard lock(mtx_);
452
51
            for (auto& [id, _] : recycling_instance_map_) {
453
30
                instances.push_back(id);
454
30
            }
455
51
        }
456
51
        for (auto& i : instances) {
457
30
            std::string recycle_job_key;
458
30
            job_recycle_key({i}, &recycle_job_key);
459
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
460
30
            if (ret == 1) {
461
0
                std::lock_guard lock(mtx_);
462
0
                if (auto it = recycling_instance_map_.find(i);
463
0
                    it != recycling_instance_map_.end()) {
464
0
                    it->second->stop();
465
0
                }
466
0
            }
467
30
        }
468
51
        {
469
51
            std::unique_lock lock(mtx_);
470
51
            notifier_.wait_for(lock,
471
51
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
472
101
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
472
101
                               [&]() { return stopped(); });
473
51
        }
474
51
    }
475
4
}
476
477
4
void Recycler::check_recycle_tasks() {
478
7
    while (!stopped()) {
479
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
480
3
        {
481
3
            std::lock_guard lock(mtx_);
482
3
            recycling_instance_map = recycling_instance_map_;
483
3
        }
484
3
        for (auto& entry : recycling_instance_map) {
485
0
            entry.second->check_recycle_tasks();
486
0
        }
487
488
3
        std::unique_lock lock(mtx_);
489
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
490
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
490
6
                           [&]() { return stopped(); });
491
3
    }
492
4
}
493
494
4
int Recycler::start(brpc::Server* server) {
495
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
496
4
    S3Environment::getInstance();
497
498
4
    if (config::enable_checker) {
499
0
        checker_ = std::make_unique<Checker>(txn_kv_);
500
0
        int ret = checker_->start();
501
0
        std::string msg;
502
0
        if (ret != 0) {
503
0
            msg = "failed to start checker";
504
0
            LOG(ERROR) << msg;
505
0
            std::cerr << msg << std::endl;
506
0
            return ret;
507
0
        }
508
0
        msg = "checker started";
509
0
        LOG(INFO) << msg;
510
0
        std::cout << msg << std::endl;
511
0
    }
512
513
4
    if (server) {
514
        // Add service
515
1
        auto recycler_service =
516
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
517
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
518
1
    }
519
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
521
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
522
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
522
8
        workers_.emplace_back([this] { recycle_callback(); });
523
8
    }
524
525
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
526
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
527
528
4
    if (config::enable_snapshot_data_migrator) {
529
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
530
0
        int ret = snapshot_data_migrator_->start();
531
0
        if (ret != 0) {
532
0
            LOG(ERROR) << "failed to start snapshot data migrator";
533
0
            return ret;
534
0
        }
535
0
        LOG(INFO) << "snapshot data migrator started";
536
0
    }
537
538
4
    if (config::enable_snapshot_chain_compactor) {
539
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
540
0
        int ret = snapshot_chain_compactor_->start();
541
0
        if (ret != 0) {
542
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
543
0
            return ret;
544
0
        }
545
0
        LOG(INFO) << "snapshot chain compactor started";
546
0
    }
547
548
4
    return 0;
549
4
}
550
551
4
void Recycler::stop() {
552
4
    stopped_ = true;
553
4
    notifier_.notify_all();
554
4
    pending_instance_cond_.notify_all();
555
4
    {
556
4
        std::lock_guard lock(mtx_);
557
4
        for (auto& [_, recycler] : recycling_instance_map_) {
558
0
            recycler->stop();
559
0
        }
560
4
    }
561
20
    for (auto& w : workers_) {
562
20
        if (w.joinable()) w.join();
563
20
    }
564
4
    if (checker_) {
565
0
        checker_->stop();
566
0
    }
567
4
    if (snapshot_data_migrator_) {
568
0
        snapshot_data_migrator_->stop();
569
0
    }
570
4
    if (snapshot_chain_compactor_) {
571
0
        snapshot_chain_compactor_->stop();
572
0
    }
573
4
}
574
575
class InstanceRecycler::InvertedIndexIdCache {
576
public:
577
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
578
173
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
579
580
    // Return 0 if success, 1 if schema kv not found, negative for error
581
    // For the same index_id, schema_version, res, since `get` is not completely atomic
582
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
583
    // resulting in repeated addition and inaccuracy.
584
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
585
    // repeated addition does not affect correctness.
586
68.3k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
587
68.3k
        {
588
68.3k
            std::lock_guard lock(mtx_);
589
68.3k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
590
4.67k
                return 0;
591
4.67k
            }
592
63.6k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
593
63.6k
                it != inverted_index_id_map_.end()) {
594
53.1k
                res = it->second;
595
53.1k
                return 0;
596
53.1k
            }
597
63.6k
        }
598
        // Get schema from kv
599
        // TODO(plat1ko): Single flight
600
10.4k
        std::unique_ptr<Transaction> txn;
601
10.4k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
602
10.4k
        if (err != TxnErrorCode::TXN_OK) {
603
0
            LOG(WARNING) << "failed to create txn, err=" << err;
604
0
            return -1;
605
0
        }
606
10.4k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
607
10.4k
        ValueBuf val_buf;
608
10.4k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
609
10.4k
        if (err != TxnErrorCode::TXN_OK) {
610
5.49k
            LOG(WARNING) << "failed to get schema, err=" << err;
611
5.49k
            return static_cast<int>(err);
612
5.49k
        }
613
4.99k
        doris::TabletSchemaCloudPB schema;
614
4.99k
        if (!parse_schema_value(val_buf, &schema)) {
615
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
616
0
            return -1;
617
0
        }
618
4.99k
        if (schema.index_size() > 0) {
619
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
620
4.01k
            if (schema.has_inverted_index_storage_format()) {
621
4.00k
                index_format = schema.inverted_index_storage_format();
622
4.00k
            }
623
4.01k
            res.first = index_format;
624
4.01k
            res.second.reserve(schema.index_size());
625
10.0k
            for (auto& i : schema.index()) {
626
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
627
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
628
10.0k
                }
629
10.0k
            }
630
4.01k
        }
631
4.99k
        insert(index_id, schema_version, res);
632
4.99k
        return 0;
633
4.99k
    }
634
635
    // Empty `ids` means this schema has no inverted index
636
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
637
5.04k
        if (index_info.second.empty()) {
638
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
639
1.02k
            std::lock_guard lock(mtx_);
640
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
641
4.01k
        } else {
642
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
643
4.01k
            std::lock_guard lock(mtx_);
644
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
645
4.01k
        }
646
5.04k
    }
647
648
private:
649
    std::string instance_id_;
650
    std::shared_ptr<TxnKv> txn_kv_;
651
652
    std::mutex mtx_;
653
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
654
    struct HashOfKey {
655
137k
        size_t operator()(const Key& key) const {
656
137k
            size_t seed = 0;
657
137k
            seed = std::hash<int64_t> {}(key.first);
658
137k
            seed = std::hash<int32_t> {}(key.second);
659
137k
            return seed;
660
137k
        }
661
    };
662
    // <index_id, schema_version> -> inverted_index_ids
663
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
664
    // Store <index_id, schema_version> of schema which doesn't have inverted index
665
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
666
};
667
668
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
669
                                   RecyclerThreadPoolGroup thread_pool_group,
670
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
671
173
        : txn_kv_(std::move(txn_kv)),
672
173
          instance_id_(instance.instance_id()),
673
173
          instance_info_(instance),
674
173
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
675
173
          _thread_pool_group(std::move(thread_pool_group)),
676
173
          txn_lazy_committer_(std::move(txn_lazy_committer)),
677
173
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
678
173
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
679
173
    delete_bitmap_lock_white_list_->init();
680
173
    resource_mgr_->init();
681
682
173
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
683
684
    // Since the recycler's resource manager could not be notified when instance info changes,
685
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
686
173
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
687
173
};
688
689
173
InstanceRecycler::~InstanceRecycler() = default;
690
691
149
int InstanceRecycler::init_obj_store_accessors() {
692
149
    for (const auto& obj_info : instance_info_.obj_info()) {
693
105
#ifdef UNIT_TEST
694
105
        auto accessor = std::make_shared<MockAccessor>();
695
#else
696
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
697
        if (!s3_conf) {
698
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
699
            return -1;
700
        }
701
702
        std::shared_ptr<S3Accessor> accessor;
703
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
704
        if (ret != 0) {
705
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
706
                         << " resource_id=" << obj_info.id();
707
            return ret;
708
        }
709
#endif
710
105
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
711
105
    }
712
713
149
    return 0;
714
149
}
715
716
149
int InstanceRecycler::init_storage_vault_accessors() {
717
149
    if (instance_info_.resource_ids().empty()) {
718
142
        return 0;
719
142
    }
720
721
7
    FullRangeGetOptions opts(txn_kv_);
722
7
    opts.prefetch = true;
723
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
724
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
725
726
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
727
18
        auto [k, v] = *kv;
728
18
        StorageVaultPB vault;
729
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
730
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
731
0
            return -1;
732
0
        }
733
18
        std::string recycler_storage_vault_white_list = accumulate(
734
18
                config::recycler_storage_vault_white_list.begin(),
735
18
                config::recycler_storage_vault_white_list.end(), std::string(),
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
737
18
        LOG_INFO("config::recycler_storage_vault_white_list")
738
18
                .tag("", recycler_storage_vault_white_list);
739
18
        if (!config::recycler_storage_vault_white_list.empty()) {
740
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
741
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
742
8
                it == config::recycler_storage_vault_white_list.end()) {
743
2
                LOG_WARNING(
744
2
                        "failed to init accessor for vault because this vault is not in "
745
2
                        "config::recycler_storage_vault_white_list. ")
746
2
                        .tag(" vault name:", vault.name())
747
2
                        .tag(" config::recycler_storage_vault_white_list:",
748
2
                             recycler_storage_vault_white_list);
749
2
                continue;
750
2
            }
751
8
        }
752
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
753
16
                                 &accessor_map_, &vault);
754
16
        if (vault.has_hdfs_info()) {
755
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
756
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
757
9
            int ret = accessor->init();
758
9
            if (ret != 0) {
759
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
760
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
761
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
762
4
                continue;
763
4
            }
764
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
765
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
766
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
767
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
768
#else
769
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
770
                       << "but HDFS storage vaults were detected";
771
#endif
772
7
        } else if (vault.has_obj_info()) {
773
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
774
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
775
7
            if (!s3_conf) {
776
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
777
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
778
1
                continue;
779
1
            }
780
781
6
            std::shared_ptr<S3Accessor> accessor;
782
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
783
6
            if (ret != 0) {
784
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
785
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
786
0
                             << " ret=" << ret
787
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
788
0
                continue;
789
0
            }
790
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
791
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
792
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
793
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
794
6
        }
795
16
    }
796
797
7
    if (!it->is_valid()) {
798
0
        LOG_WARNING("failed to get storage vault kv");
799
0
        return -1;
800
0
    }
801
802
7
    if (accessor_map_.empty()) {
803
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
804
1
        return -2;
805
1
    }
806
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
807
6
             instance_id_);
808
809
6
    return 0;
810
7
}
811
812
150
int InstanceRecycler::init() {
813
150
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
814
150
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
815
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
816
1
        return 0;
817
1
    }
818
819
149
    int ret = init_obj_store_accessors();
820
149
    if (ret != 0) {
821
0
        return ret;
822
0
    }
823
824
149
    return init_storage_vault_accessors();
825
149
}
826
827
template <typename... Func>
828
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
120
    return [funcs...]() {
830
120
        return [](std::initializer_list<int> ret_vals) {
831
120
            int i = 0;
832
140
            for (int ret : ret_vals) {
833
140
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
140
            }
837
120
            return i;
838
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
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
20
            for (int ret : ret_vals) {
833
20
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
20
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
20
            for (int ret : ret_vals) {
833
20
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
20
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
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
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
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
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
841
842
11
int InstanceRecycler::do_recycle() {
843
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
844
11
    tablet_metrics_context_.reset();
845
11
    segment_metrics_context_.reset();
846
11
    DORIS_CLOUD_DEFER {
847
11
        tablet_metrics_context_.finish_report();
848
11
        segment_metrics_context_.finish_report();
849
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
846
11
    DORIS_CLOUD_DEFER {
847
11
        tablet_metrics_context_.finish_report();
848
11
        segment_metrics_context_.finish_report();
849
11
    };
850
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
851
1
        int res = recycle_cluster_snapshots();
852
1
        if (res != 0) {
853
0
            return -1;
854
0
        }
855
1
        return recycle_deleted_instance();
856
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
857
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
858
10
                                        fmt::format("instance id {}", instance_id_),
859
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
859
120
                                        [](int r) { return r != 0; });
860
10
        sync_executor
861
10
                .add(task_wrapper(
862
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
862
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
863
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
863
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
864
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
865
                                   // becase they may both recycle the same set of tablets
866
                        // recycle dropped table or idexes(mv, rollup)
867
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
867
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
868
                        // recycle dropped partitions
869
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
869
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
870
10
                .add(task_wrapper(
871
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
871
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
872
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
872
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
873
10
                .add(task_wrapper(
874
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
874
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
876
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
877
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
877
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
878
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
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
879
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
879
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
880
10
                .add(task_wrapper(
881
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
881
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
882
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
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
883
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
883
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
884
10
        bool finished = true;
885
10
        std::vector<int> rets = sync_executor.when_all(&finished);
886
120
        for (int ret : rets) {
887
120
            if (ret != 0) {
888
0
                return ret;
889
0
            }
890
120
        }
891
10
        return finished ? 0 : -1;
892
10
    } else {
893
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
894
0
                     << " instance_id=" << instance_id_;
895
0
        return -1;
896
0
    }
897
11
}
898
899
/**
900
* 1. delete all remote data
901
* 2. delete all kv
902
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
903
*/
904
13
int InstanceRecycler::recycle_deleted_instance() {
905
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
906
907
13
    int ret = 0;
908
13
    auto start_time = steady_clock::now();
909
13
    const auto recycle_state = instance_info_.recycle_state();
910
911
13
    if (config::retain_deleted_instance_tombstone &&
912
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
913
4
        return 0;
914
4
    }
915
916
9
    DORIS_CLOUD_DEFER {
917
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
918
9
        if (ret != 0) {
919
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
920
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
921
0
                         << "s, instance_id=" << instance_id_;
922
9
        } else if (recycle_state ==
923
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
924
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
925
0
                      << "s, instance_id=" << instance_id_;
926
9
        } else {
927
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
928
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
929
9
                      << "s, instance_id=" << instance_id_;
930
9
        }
931
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
916
9
    DORIS_CLOUD_DEFER {
917
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
918
9
        if (ret != 0) {
919
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
920
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
921
0
                         << "s, instance_id=" << instance_id_;
922
9
        } else if (recycle_state ==
923
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
924
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
925
0
                      << "s, instance_id=" << instance_id_;
926
9
        } else {
927
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
928
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
929
9
                      << "s, instance_id=" << instance_id_;
930
9
        }
931
9
    };
932
933
9
    switch (recycle_state) {
934
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
935
6
        ret = recycle_deleted_instance_data();
936
6
        break;
937
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
938
3
        ret = recycle_deleted_instance_metadata();
939
3
        break;
940
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
941
0
        ret = remove_instance_key();
942
0
        break;
943
0
    default:
944
0
        LOG_WARNING("invalid instance recycle state")
945
0
                .tag("instance_id", instance_id_)
946
0
                .tag("recycle_state", instance_info_.recycle_state());
947
0
        ret = -1;
948
0
        break;
949
9
    }
950
951
9
    return ret;
952
9
}
953
954
6
int InstanceRecycler::recycle_deleted_instance_data() {
955
6
    int ret = 0;
956
957
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
958
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
959
6
        int res = recycle_tmp_rowsets();
960
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
961
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
962
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
963
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
964
            // and cannot be recycled.
965
0
            res = recycle_tmp_rowsets();
966
0
        }
967
6
        return res;
968
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
958
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
959
6
        int res = recycle_tmp_rowsets();
960
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
961
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
962
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
963
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
964
            // and cannot be recycled.
965
0
            res = recycle_tmp_rowsets();
966
0
        }
967
6
        return res;
968
6
    };
969
970
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
971
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
972
0
        return -1;
973
0
    }
974
975
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
976
6
    if (recycle_versioned_rowsets() != 0) {
977
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
978
0
        return -1;
979
0
    }
980
981
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
982
6
    if (recycle_operation_logs() != 0) {
983
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
984
0
        return -1;
985
0
    }
986
987
    // Step 4: Check if there are still cluster snapshots
988
6
    bool has_snapshots = false;
989
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
990
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
991
0
        return -1;
992
6
    } else if (has_snapshots) {
993
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
994
1
        return 0;
995
1
    }
996
997
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
998
5
                            instance_info().snapshot_switch_status() !=
999
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1000
5
    if (snapshot_enabled) {
1001
1
        bool has_unrecycled_rowsets = false;
1002
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1003
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1004
0
            return -1;
1005
1
        } else if (has_unrecycled_rowsets) {
1006
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1007
0
                    .tag("instance_id", instance_id_);
1008
0
            return ret;
1009
0
        }
1010
4
    } else { // delete all remote data if snapshot is disabled
1011
4
        for (auto& [_, accessor] : accessor_map_) {
1012
4
            if (stopped()) {
1013
0
                return ret;
1014
0
            }
1015
1016
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1017
4
            int del_ret = accessor->delete_all();
1018
4
            if (del_ret == 0) {
1019
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1020
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1021
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1022
                // so the recycling has been successful.
1023
0
                ret = -1;
1024
0
            }
1025
4
        }
1026
1027
4
        if (ret != 0) {
1028
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1029
0
            return ret;
1030
0
        }
1031
4
    }
1032
1033
5
    if (update_instance_recycle_state(
1034
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1035
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1036
0
        return -1;
1037
0
    }
1038
1039
5
    return 0;
1040
5
}
1041
1042
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1043
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1044
7
    if (instance_info_.has_successor_instance_id() &&
1045
7
        !instance_info_.successor_instance_id().empty()) {
1046
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1047
4
        std::unique_ptr<Transaction> txn;
1048
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1049
4
        if (err != TxnErrorCode::TXN_OK) {
1050
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1051
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1052
0
                         << " err=" << err;
1053
0
            return -1;
1054
0
        }
1055
1056
4
        InstanceInfoPB successor_instance;
1057
4
        std::string value;
1058
4
        err = txn->get(key, &value);
1059
4
        if (err == TxnErrorCode::TXN_OK) {
1060
3
            InstanceInfoPB successor_instance;
1061
3
            if (!successor_instance.ParseFromString(value)) {
1062
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1063
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1064
0
                return -1;
1065
0
            }
1066
3
            if (!successor_instance.has_recycle_state() ||
1067
3
                successor_instance.recycle_state() !=
1068
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1069
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1070
2
                          << " instance_id=" << instance_id_
1071
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1072
2
                          << " successor_status=" << successor_instance.status()
1073
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1074
2
                return 0;
1075
2
            }
1076
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1077
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1078
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1079
0
                         << " err=" << err;
1080
0
            return -1;
1081
0
        }
1082
4
    }
1083
1084
    // delete all kv
1085
5
    std::unique_ptr<Transaction> txn;
1086
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1087
5
    if (err != TxnErrorCode::TXN_OK) {
1088
0
        LOG(WARNING) << "failed to create txn";
1089
0
        return -1;
1090
0
    }
1091
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1092
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1093
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1094
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1095
5
    txn->remove(start_txn_key, end_txn_key);
1096
5
    std::string start_version_key = version_key_prefix(instance_id_);
1097
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1098
5
    txn->remove(start_version_key, end_version_key);
1099
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1100
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1101
5
    txn->remove(start_meta_key, end_meta_key);
1102
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1103
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1104
5
    txn->remove(start_recycle_key, end_recycle_key);
1105
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1106
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1107
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1108
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1109
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1110
5
    txn->remove(start_copy_key, end_copy_key);
1111
    // should not remove job key range, because we need to reserve job recycle kv
1112
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1113
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1114
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1115
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1116
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1117
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1118
5
    std::string start_vault_key = storage_vault_key(key_info0);
1119
5
    std::string end_vault_key = storage_vault_key(key_info1);
1120
5
    txn->remove(start_vault_key, end_vault_key);
1121
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1122
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1123
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1124
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1125
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1126
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1127
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1128
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1129
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1130
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1131
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1132
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1133
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1134
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1135
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1136
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1137
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1138
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1139
1140
    // Updating the recycle state also commits this transaction, making the metadata deletions
1141
    // and state transition atomic.
1142
5
    if (update_instance_recycle_state(
1143
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1144
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1145
0
        return -1;
1146
0
    }
1147
1148
5
    return 0;
1149
5
}
1150
1151
0
int InstanceRecycler::remove_instance_key() {
1152
0
    std::unique_ptr<Transaction> txn;
1153
0
    std::string key = instance_key(instance_info_.instance_id());
1154
0
    std::string value;
1155
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1156
0
    if (err != TxnErrorCode::TXN_OK) {
1157
0
        LOG(WARNING) << "failed to create txn";
1158
0
        return -1;
1159
0
    }
1160
1161
0
    err = txn->get(key, &value);
1162
0
    if (err != TxnErrorCode::TXN_OK) {
1163
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1164
0
                     << ", err=" << err;
1165
0
        return -1;
1166
0
    }
1167
1168
0
    InstanceInfoPB instance;
1169
0
    if (!instance.ParseFromString(value)) {
1170
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1171
0
        return -1;
1172
0
    }
1173
1174
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1175
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1176
0
                     << instance_id_ << ", status=" << instance.status();
1177
0
        return -1;
1178
0
    }
1179
1180
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1181
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1182
0
                     << instance_id_
1183
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1184
0
                     << ", expected_state="
1185
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1186
0
        return -1;
1187
0
    }
1188
1189
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1190
0
    txn->remove(key);
1191
0
    err = txn->commit();
1192
0
    if (err != TxnErrorCode::TXN_OK) {
1193
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1194
0
                     << " err=" << err;
1195
0
        return -1;
1196
0
    }
1197
0
    return 0;
1198
0
}
1199
1200
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1201
7
                                                    InstanceRecycleState target_state) {
1202
7
    std::unique_ptr<Transaction> txn;
1203
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1204
7
    if (err != TxnErrorCode::TXN_OK) {
1205
0
        LOG(WARNING) << "failed to create txn";
1206
0
        return -1;
1207
0
    }
1208
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1209
7
}
1210
1211
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1212
                                                    InstanceRecycleState target_state,
1213
12
                                                    Transaction* txn) {
1214
12
    const bool valid_transition =
1215
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1216
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1217
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1218
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1219
1220
12
    if (!valid_transition) {
1221
1
        LOG_WARNING("invalid instance recycled state transition")
1222
1
                .tag("instance_id", instance_id_)
1223
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1224
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1225
1
        return -1;
1226
1
    }
1227
1228
11
    std::string key = instance_key({instance_id_});
1229
11
    std::string value;
1230
11
    TxnErrorCode err = txn->get(key, &value);
1231
11
    if (err != TxnErrorCode::TXN_OK) {
1232
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1233
0
                .tag("instance_id", instance_id_)
1234
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1235
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1236
0
                .tag("err", err);
1237
0
        return -1;
1238
0
    }
1239
1240
11
    InstanceInfoPB instance;
1241
11
    if (!instance.ParseFromString(value)) {
1242
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1243
0
                .tag("instance_id", instance_id_)
1244
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1245
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1246
0
        return -1;
1247
0
    }
1248
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1249
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1250
0
                .tag("instance_id", instance_id_)
1251
0
                .tag("status", instance.status())
1252
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1253
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1254
0
        return -1;
1255
0
    }
1256
11
    if (instance.recycle_state() != current_state) {
1257
1
        LOG_WARNING("instance recycled state changed before update")
1258
1
                .tag("instance_id", instance_id_)
1259
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1260
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1261
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1262
1
        return -1;
1263
1
    }
1264
1265
10
    instance.set_recycle_state(target_state);
1266
10
    instance.set_recycle_state_update_time_ms(
1267
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1268
10
    if (!instance.SerializeToString(&value)) {
1269
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1270
0
                .tag("instance_id", instance_id_)
1271
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1272
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1273
0
        return -1;
1274
0
    }
1275
1276
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1277
10
    txn->put(key, value);
1278
10
    err = txn->commit();
1279
10
    if (err != TxnErrorCode::TXN_OK) {
1280
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1281
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1282
0
        return -1;
1283
0
    }
1284
1285
10
    instance_info_.Swap(&instance);
1286
10
    LOG_INFO("updated instance recycled state")
1287
10
            .tag("instance_id", instance_id_)
1288
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1289
10
    return 0;
1290
10
}
1291
1292
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1293
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1294
9
    if (exists == nullptr) {
1295
0
        return -1;
1296
0
    }
1297
9
    *exists = false;
1298
1299
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1300
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1301
9
    std::string scan_begin = begin;
1302
1303
9
    while (true) {
1304
9
        std::unique_ptr<RangeGetIterator> it_range;
1305
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1306
9
        if (get_ret < 0) {
1307
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1308
0
                    .tag("instance_id", instance_id_)
1309
0
                    .tag("tablet_id", tablet_id)
1310
0
                    .tag("ret", get_ret);
1311
0
            return -1;
1312
0
        }
1313
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1314
6
            return 0;
1315
6
        }
1316
1317
3
        std::string last_key;
1318
3
        while (it_range->has_next()) {
1319
3
            auto [k, v] = it_range->next();
1320
3
            last_key.assign(k.data(), k.size());
1321
3
            doris::RowsetMetaCloudPB rowset_meta;
1322
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1323
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1324
0
                        .tag("instance_id", instance_id_)
1325
0
                        .tag("tablet_id", tablet_id)
1326
0
                        .tag("key", hex(k));
1327
0
                continue;
1328
0
            }
1329
3
            if (stats) {
1330
3
                ++stats->rowset_scan_count;
1331
3
            }
1332
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1333
3
                *exists = true;
1334
3
                return 0;
1335
3
            }
1336
3
        }
1337
1338
0
        if (!it_range->more()) {
1339
0
            return 0;
1340
0
        }
1341
1342
        // Continue scanning from the next key to keep each transaction short.
1343
0
        scan_begin = std::move(last_key);
1344
0
        scan_begin.push_back('\x00');
1345
0
    }
1346
9
}
1347
1348
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1349
                                                          const std::string& rowset_id,
1350
                                                          int64_t txn_id, bool* recycle_exists,
1351
11
                                                          bool* tmp_exists) {
1352
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1353
0
        return -1;
1354
0
    }
1355
11
    *recycle_exists = false;
1356
11
    *tmp_exists = false;
1357
1358
11
    if (txn_id <= 0) {
1359
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1360
0
                .tag("instance_id", instance_id_)
1361
0
                .tag("tablet_id", tablet_id)
1362
0
                .tag("rowset_id", rowset_id)
1363
0
                .tag("txn_id", txn_id);
1364
0
        return -1;
1365
0
    }
1366
1367
11
    std::unique_ptr<Transaction> txn;
1368
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1369
11
    if (err != TxnErrorCode::TXN_OK) {
1370
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1371
0
                .tag("instance_id", instance_id_)
1372
0
                .tag("tablet_id", tablet_id)
1373
0
                .tag("rowset_id", rowset_id)
1374
0
                .tag("txn_id", txn_id)
1375
0
                .tag("err", err);
1376
0
        return -1;
1377
0
    }
1378
1379
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1380
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1381
11
    if (ret == TxnErrorCode::TXN_OK) {
1382
1
        *recycle_exists = true;
1383
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1384
0
        LOG_WARNING("failed to check recycle rowset existence")
1385
0
                .tag("instance_id", instance_id_)
1386
0
                .tag("tablet_id", tablet_id)
1387
0
                .tag("rowset_id", rowset_id)
1388
0
                .tag("key", hex(recycle_key))
1389
0
                .tag("err", ret);
1390
0
        return -1;
1391
0
    }
1392
1393
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1394
11
    ret = key_exists(txn.get(), tmp_key, true);
1395
11
    if (ret == TxnErrorCode::TXN_OK) {
1396
1
        *tmp_exists = true;
1397
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1398
0
        LOG_WARNING("failed to check tmp rowset existence")
1399
0
                .tag("instance_id", instance_id_)
1400
0
                .tag("tablet_id", tablet_id)
1401
0
                .tag("txn_id", txn_id)
1402
0
                .tag("key", hex(tmp_key))
1403
0
                .tag("err", ret);
1404
0
        return -1;
1405
0
    }
1406
1407
11
    return 0;
1408
11
}
1409
1410
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1411
7.50k
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1412
7.50k
    if (!hint.empty()) {
1413
7.50k
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1414
7.49k
            return {hint, it->second};
1415
7.49k
        }
1416
7.50k
    }
1417
1418
11
    return {"", nullptr};
1419
7.50k
}
1420
1421
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1422
                                               const std::string& packed_file_path,
1423
3
                                               PackedFileRecycleStats* stats) {
1424
3
    bool local_changed = false;
1425
3
    int64_t left_num = 0;
1426
3
    int64_t left_bytes = 0;
1427
3
    bool all_small_files_confirmed = true;
1428
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1429
1430
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1431
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1432
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1433
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1434
14
        LOG_INFO("packed slice correction status")
1435
14
                .tag("instance_id", instance_id_)
1436
14
                .tag("packed_file_path", packed_file_path)
1437
14
                .tag("small_file_path", file.path())
1438
14
                .tag("tablet_id", tablet_id)
1439
14
                .tag("rowset_id", rowset_id)
1440
14
                .tag("txn_id", txn_id)
1441
14
                .tag("size", file.size())
1442
14
                .tag("deleted", file.deleted())
1443
14
                .tag("corrected", file.corrected())
1444
14
                .tag("confirmed_this_round", confirmed_this_round);
1445
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
1430
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1431
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1432
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1433
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1434
        LOG_INFO("packed slice correction status")
1435
14
                .tag("instance_id", instance_id_)
1436
14
                .tag("packed_file_path", packed_file_path)
1437
14
                .tag("small_file_path", file.path())
1438
14
                .tag("tablet_id", tablet_id)
1439
14
                .tag("rowset_id", rowset_id)
1440
14
                .tag("txn_id", txn_id)
1441
14
                .tag("size", file.size())
1442
14
                .tag("deleted", file.deleted())
1443
14
                .tag("corrected", file.corrected())
1444
14
                .tag("confirmed_this_round", confirmed_this_round);
1445
14
    };
1446
1447
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1448
14
        auto* small_file = packed_info->mutable_slices(i);
1449
14
        if (small_file->deleted()) {
1450
3
            log_small_file_status(*small_file, small_file->corrected());
1451
3
            continue;
1452
3
        }
1453
1454
11
        if (small_file->corrected()) {
1455
0
            left_num++;
1456
0
            left_bytes += small_file->size();
1457
0
            log_small_file_status(*small_file, true);
1458
0
            continue;
1459
0
        }
1460
1461
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1462
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1463
0
                    .tag("instance_id", instance_id_)
1464
0
                    .tag("small_file_path", small_file->path())
1465
0
                    .tag("index", i);
1466
0
            return -1;
1467
0
        }
1468
1469
11
        int64_t tablet_id = small_file->tablet_id();
1470
11
        const std::string& rowset_id = small_file->rowset_id();
1471
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1472
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1473
0
                    .tag("instance_id", instance_id_)
1474
0
                    .tag("small_file_path", small_file->path())
1475
0
                    .tag("index", i)
1476
0
                    .tag("tablet_id", tablet_id)
1477
0
                    .tag("rowset_id", rowset_id)
1478
0
                    .tag("has_txn_id", small_file->has_txn_id())
1479
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1480
0
            return -1;
1481
0
        }
1482
11
        int64_t txn_id = small_file->txn_id();
1483
11
        bool recycle_exists = false;
1484
11
        bool tmp_exists = false;
1485
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1486
11
                                                &tmp_exists) != 0) {
1487
0
            return -1;
1488
0
        }
1489
1490
11
        bool small_file_confirmed = false;
1491
11
        if (tmp_exists) {
1492
1
            left_num++;
1493
1
            left_bytes += small_file->size();
1494
1
            small_file_confirmed = true;
1495
10
        } else if (recycle_exists) {
1496
1
            left_num++;
1497
1
            left_bytes += small_file->size();
1498
            // keep small_file_confirmed=false so the packed file remains uncorrected
1499
9
        } else {
1500
9
            bool rowset_exists = false;
1501
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1502
0
                return -1;
1503
0
            }
1504
1505
9
            if (!rowset_exists) {
1506
6
                if (!small_file->deleted()) {
1507
6
                    small_file->set_deleted(true);
1508
6
                    local_changed = true;
1509
6
                }
1510
6
                if (!small_file->corrected()) {
1511
6
                    small_file->set_corrected(true);
1512
6
                    local_changed = true;
1513
6
                }
1514
6
                small_file_confirmed = true;
1515
6
            } else {
1516
3
                left_num++;
1517
3
                left_bytes += small_file->size();
1518
3
                small_file_confirmed = true;
1519
3
            }
1520
9
        }
1521
1522
11
        if (!small_file_confirmed) {
1523
1
            all_small_files_confirmed = false;
1524
1
        }
1525
1526
11
        if (small_file->corrected() != small_file_confirmed) {
1527
4
            small_file->set_corrected(small_file_confirmed);
1528
4
            local_changed = true;
1529
4
        }
1530
1531
11
        log_small_file_status(*small_file, small_file_confirmed);
1532
11
    }
1533
1534
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1535
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1536
3
        local_changed = true;
1537
3
    }
1538
3
    if (packed_info->ref_cnt() != left_num) {
1539
3
        auto old_ref_cnt = packed_info->ref_cnt();
1540
3
        packed_info->set_ref_cnt(left_num);
1541
3
        LOG_INFO("corrected packed file ref count")
1542
3
                .tag("instance_id", instance_id_)
1543
3
                .tag("resource_id", packed_info->resource_id())
1544
3
                .tag("packed_file_path", packed_file_path)
1545
3
                .tag("old_ref_cnt", old_ref_cnt)
1546
3
                .tag("new_ref_cnt", left_num);
1547
3
        local_changed = true;
1548
3
    }
1549
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1550
2
        packed_info->set_corrected(all_small_files_confirmed);
1551
2
        local_changed = true;
1552
2
    }
1553
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1554
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1555
1
        local_changed = true;
1556
1
    }
1557
1558
3
    if (changed != nullptr) {
1559
3
        *changed = local_changed;
1560
3
    }
1561
3
    return 0;
1562
3
}
1563
1564
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1565
                                                 const std::string& packed_file_path,
1566
4
                                                 PackedFileRecycleStats* stats) {
1567
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1568
4
    bool correction_ok = false;
1569
4
    cloud::PackedFileInfoPB packed_info;
1570
1571
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1572
4
        if (stopped()) {
1573
0
            LOG_WARNING("recycler stopped before processing packed file")
1574
0
                    .tag("instance_id", instance_id_)
1575
0
                    .tag("packed_file_path", packed_file_path)
1576
0
                    .tag("attempt", attempt);
1577
0
            return -1;
1578
0
        }
1579
1580
4
        std::unique_ptr<Transaction> txn;
1581
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1582
4
        if (err != TxnErrorCode::TXN_OK) {
1583
0
            LOG_WARNING("failed to create txn when processing packed file")
1584
0
                    .tag("instance_id", instance_id_)
1585
0
                    .tag("packed_file_path", packed_file_path)
1586
0
                    .tag("attempt", attempt)
1587
0
                    .tag("err", err);
1588
0
            return -1;
1589
0
        }
1590
1591
4
        std::string packed_val;
1592
4
        err = txn->get(packed_key, &packed_val);
1593
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1594
0
            return 0;
1595
0
        }
1596
4
        if (err != TxnErrorCode::TXN_OK) {
1597
0
            LOG_WARNING("failed to get packed file kv")
1598
0
                    .tag("instance_id", instance_id_)
1599
0
                    .tag("packed_file_path", packed_file_path)
1600
0
                    .tag("attempt", attempt)
1601
0
                    .tag("err", err);
1602
0
            return -1;
1603
0
        }
1604
1605
4
        if (!packed_info.ParseFromString(packed_val)) {
1606
0
            LOG_WARNING("failed to parse packed file info")
1607
0
                    .tag("instance_id", instance_id_)
1608
0
                    .tag("packed_file_path", packed_file_path)
1609
0
                    .tag("attempt", attempt);
1610
0
            return -1;
1611
0
        }
1612
1613
4
        int64_t now_sec = ::time(nullptr);
1614
4
        bool corrected = packed_info.corrected();
1615
4
        bool due = config::force_immediate_recycle ||
1616
4
                   now_sec - packed_info.created_at_sec() >=
1617
4
                           config::packed_file_correction_delay_seconds;
1618
1619
4
        if (!corrected && due) {
1620
3
            bool changed = false;
1621
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1622
0
                LOG_WARNING("correct_packed_file_info failed")
1623
0
                        .tag("instance_id", instance_id_)
1624
0
                        .tag("packed_file_path", packed_file_path)
1625
0
                        .tag("attempt", attempt);
1626
0
                return -1;
1627
0
            }
1628
3
            if (changed) {
1629
3
                std::string updated;
1630
3
                if (!packed_info.SerializeToString(&updated)) {
1631
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1632
0
                            .tag("instance_id", instance_id_)
1633
0
                            .tag("packed_file_path", packed_file_path)
1634
0
                            .tag("attempt", attempt);
1635
0
                    return -1;
1636
0
                }
1637
3
                txn->put(packed_key, updated);
1638
3
                err = txn->commit();
1639
3
                if (err == TxnErrorCode::TXN_OK) {
1640
3
                    if (stats) {
1641
3
                        ++stats->num_corrected;
1642
3
                    }
1643
3
                } else {
1644
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1645
0
                        LOG_WARNING(
1646
0
                                "failed to commit correction for packed file due to conflict, "
1647
0
                                "retrying")
1648
0
                                .tag("instance_id", instance_id_)
1649
0
                                .tag("packed_file_path", packed_file_path)
1650
0
                                .tag("attempt", attempt);
1651
0
                        sleep_for_packed_file_retry();
1652
0
                        packed_info.Clear();
1653
0
                        continue;
1654
0
                    }
1655
0
                    LOG_WARNING("failed to commit correction for packed file")
1656
0
                            .tag("instance_id", instance_id_)
1657
0
                            .tag("packed_file_path", packed_file_path)
1658
0
                            .tag("attempt", attempt)
1659
0
                            .tag("err", err);
1660
0
                    return -1;
1661
0
                }
1662
3
            }
1663
3
        }
1664
1665
4
        correction_ok = true;
1666
4
        break;
1667
4
    }
1668
1669
4
    if (!correction_ok) {
1670
0
        return -1;
1671
0
    }
1672
1673
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1674
4
          packed_info.ref_cnt() == 0)) {
1675
3
        return 0;
1676
3
    }
1677
1678
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1679
0
        LOG_WARNING("packed file missing resource id when recycling")
1680
0
                .tag("instance_id", instance_id_)
1681
0
                .tag("packed_file_path", packed_file_path);
1682
0
        return -1;
1683
0
    }
1684
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1685
1
    if (!accessor) {
1686
0
        LOG_WARNING("no accessor available to delete packed file")
1687
0
                .tag("instance_id", instance_id_)
1688
0
                .tag("packed_file_path", packed_file_path)
1689
0
                .tag("resource_id", packed_info.resource_id());
1690
0
        return -1;
1691
0
    }
1692
1
    int del_ret = accessor->delete_file(packed_file_path);
1693
1
    if (del_ret != 0 && del_ret != 1) {
1694
0
        LOG_WARNING("failed to delete packed file")
1695
0
                .tag("instance_id", instance_id_)
1696
0
                .tag("packed_file_path", packed_file_path)
1697
0
                .tag("resource_id", resource_id)
1698
0
                .tag("ret", del_ret);
1699
0
        return -1;
1700
0
    }
1701
1
    if (del_ret == 1) {
1702
0
        LOG_INFO("packed file already removed")
1703
0
                .tag("instance_id", instance_id_)
1704
0
                .tag("packed_file_path", packed_file_path)
1705
0
                .tag("resource_id", resource_id);
1706
1
    } else {
1707
1
        LOG_INFO("deleted packed file")
1708
1
                .tag("instance_id", instance_id_)
1709
1
                .tag("packed_file_path", packed_file_path)
1710
1
                .tag("resource_id", resource_id);
1711
1
    }
1712
1713
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1714
1
        std::unique_ptr<Transaction> del_txn;
1715
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1716
1
        if (err != TxnErrorCode::TXN_OK) {
1717
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1718
0
                    .tag("instance_id", instance_id_)
1719
0
                    .tag("packed_file_path", packed_file_path)
1720
0
                    .tag("del_attempt", del_attempt)
1721
0
                    .tag("err", err);
1722
0
            return -1;
1723
0
        }
1724
1725
1
        std::string latest_val;
1726
1
        err = del_txn->get(packed_key, &latest_val);
1727
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1728
0
            return 0;
1729
0
        }
1730
1
        if (err != TxnErrorCode::TXN_OK) {
1731
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1732
0
                    .tag("instance_id", instance_id_)
1733
0
                    .tag("packed_file_path", packed_file_path)
1734
0
                    .tag("del_attempt", del_attempt)
1735
0
                    .tag("err", err);
1736
0
            return -1;
1737
0
        }
1738
1739
1
        cloud::PackedFileInfoPB latest_info;
1740
1
        if (!latest_info.ParseFromString(latest_val)) {
1741
0
            LOG_WARNING("failed to parse packed file info before removal")
1742
0
                    .tag("instance_id", instance_id_)
1743
0
                    .tag("packed_file_path", packed_file_path)
1744
0
                    .tag("del_attempt", del_attempt);
1745
0
            return -1;
1746
0
        }
1747
1748
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1749
1
              latest_info.ref_cnt() == 0)) {
1750
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1751
0
                    .tag("instance_id", instance_id_)
1752
0
                    .tag("packed_file_path", packed_file_path)
1753
0
                    .tag("del_attempt", del_attempt);
1754
0
            return 0;
1755
0
        }
1756
1757
1
        del_txn->remove(packed_key);
1758
1
        err = del_txn->commit();
1759
1
        if (err == TxnErrorCode::TXN_OK) {
1760
1
            if (stats) {
1761
1
                ++stats->num_deleted;
1762
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1763
1
                                        static_cast<int64_t>(latest_val.size());
1764
1
                if (del_ret == 0 || del_ret == 1) {
1765
1
                    ++stats->num_object_deleted;
1766
1
                    int64_t object_size = latest_info.total_slice_bytes();
1767
1
                    if (object_size <= 0) {
1768
0
                        object_size = packed_info.total_slice_bytes();
1769
0
                    }
1770
1
                    stats->bytes_object_deleted += object_size;
1771
1
                }
1772
1
            }
1773
1
            LOG_INFO("removed packed file metadata")
1774
1
                    .tag("instance_id", instance_id_)
1775
1
                    .tag("packed_file_path", packed_file_path);
1776
1
            return 0;
1777
1
        }
1778
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1779
0
            if (del_attempt >= max_retry_times) {
1780
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1781
0
                        .tag("instance_id", instance_id_)
1782
0
                        .tag("packed_file_path", packed_file_path)
1783
0
                        .tag("del_attempt", del_attempt);
1784
0
                return -1;
1785
0
            }
1786
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1787
0
                    .tag("instance_id", instance_id_)
1788
0
                    .tag("packed_file_path", packed_file_path)
1789
0
                    .tag("del_attempt", del_attempt);
1790
0
            sleep_for_packed_file_retry();
1791
0
            continue;
1792
0
        }
1793
0
        LOG_WARNING("failed to remove packed file kv")
1794
0
                .tag("instance_id", instance_id_)
1795
0
                .tag("packed_file_path", packed_file_path)
1796
0
                .tag("del_attempt", del_attempt)
1797
0
                .tag("err", err);
1798
0
        return -1;
1799
0
    }
1800
1801
0
    return -1;
1802
1
}
1803
1804
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1805
4
                                            PackedFileRecycleStats* stats, int* ret) {
1806
4
    if (stats) {
1807
4
        ++stats->num_scanned;
1808
4
    }
1809
4
    std::string packed_file_path;
1810
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1811
0
        LOG_WARNING("failed to decode packed file key")
1812
0
                .tag("instance_id", instance_id_)
1813
0
                .tag("key", hex(key));
1814
0
        if (stats) {
1815
0
            ++stats->num_failed;
1816
0
        }
1817
0
        if (ret) {
1818
0
            *ret = -1;
1819
0
        }
1820
0
        return 0;
1821
0
    }
1822
1823
4
    std::string packed_key(key);
1824
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1825
4
    if (process_ret != 0) {
1826
0
        if (stats) {
1827
0
            ++stats->num_failed;
1828
0
        }
1829
0
        if (ret) {
1830
0
            *ret = -1;
1831
0
        }
1832
0
    }
1833
4
    return 0;
1834
4
}
1835
1836
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1837
126k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1838
126k
    if (config::force_immediate_recycle) {
1839
120k
        return 0L;
1840
120k
    }
1841
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1842
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1843
6.00k
    int64_t retention_seconds = config::retention_seconds;
1844
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1845
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1846
4.70k
    }
1847
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1848
6.00k
    if (*earlest_ts > final_expiration) {
1849
6
        *earlest_ts = final_expiration;
1850
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1851
6
    }
1852
6.00k
    return final_expiration;
1853
126k
}
1854
1855
int64_t calculate_partition_expired_time(
1856
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1857
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1858
9
    if (config::force_immediate_recycle) {
1859
3
        return 0L;
1860
3
    }
1861
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1862
6
                                                            : partition_meta_pb.creation_time();
1863
6
    int64_t retention_seconds = config::retention_seconds;
1864
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1865
6
        retention_seconds =
1866
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1867
6
    }
1868
6
    int64_t final_expiration = expiration + retention_seconds;
1869
6
    if (*earlest_ts > final_expiration) {
1870
2
        *earlest_ts = final_expiration;
1871
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1872
2
    }
1873
6
    return final_expiration;
1874
9
}
1875
1876
int64_t calculate_index_expired_time(const std::string& instance_id_,
1877
                                     const RecycleIndexPB& index_meta_pb,
1878
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1879
10
    if (config::force_immediate_recycle) {
1880
4
        return 0L;
1881
4
    }
1882
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1883
6
                                                        : index_meta_pb.creation_time();
1884
6
    int64_t retention_seconds = config::retention_seconds;
1885
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1886
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1887
6
    }
1888
6
    int64_t final_expiration = expiration + retention_seconds;
1889
6
    if (*earlest_ts > final_expiration) {
1890
2
        *earlest_ts = final_expiration;
1891
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1892
2
    }
1893
6
    return final_expiration;
1894
10
}
1895
1896
int64_t calculate_tmp_rowset_expired_time(
1897
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1898
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1899
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1900
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1901
    //  duration or timeout always < `retention_time` in practice.
1902
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1903
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1904
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1905
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1906
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1907
53.2k
    if (*earlest_ts > final_expiration) {
1908
20
        *earlest_ts = final_expiration;
1909
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1910
20
    }
1911
53.2k
    return final_expiration;
1912
53.2k
}
1913
1914
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1915
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1916
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1917
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1918
11
        *earlest_ts = final_expiration / 1000;
1919
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1920
11
    }
1921
50.0k
    return final_expiration;
1922
50.0k
}
1923
1924
int64_t calculate_restore_job_expired_time(
1925
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1926
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1927
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1928
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1929
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1930
        // final state, recycle immediately
1931
41
        return 0L;
1932
41
    }
1933
    // not final state, wait much longer than the FE's timeout(1 day)
1934
0
    int64_t last_modified_s =
1935
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1936
0
    int64_t expiration = restore_job.expired_at_s() > 0
1937
0
                                 ? last_modified_s + restore_job.expired_at_s()
1938
0
                                 : last_modified_s;
1939
0
    int64_t final_expiration = expiration + config::retention_seconds;
1940
0
    if (*earlest_ts > final_expiration) {
1941
0
        *earlest_ts = final_expiration;
1942
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1943
0
    }
1944
0
    return final_expiration;
1945
41
}
1946
1947
10.5k
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1948
10.5k
    AbortTxnRequest req;
1949
10.5k
    TxnInfoPB txn_info;
1950
10.5k
    MetaServiceCode code = MetaServiceCode::OK;
1951
10.5k
    std::string msg;
1952
10.5k
    std::stringstream ss;
1953
10.5k
    std::unique_ptr<Transaction> txn;
1954
10.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1955
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1956
0
        LOG_WARNING("failed to create txn").tag("err", err);
1957
0
        return -1;
1958
0
    }
1959
1960
    // get txn index
1961
10.5k
    TxnIndexPB txn_idx_pb;
1962
10.5k
    auto index_key = txn_index_key({instance_id_, txn_id});
1963
10.5k
    std::string index_val;
1964
10.5k
    err = txn->get(index_key, &index_val);
1965
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1966
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1967
            // maybe recycled
1968
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1969
2
                    .tag("key", hex(index_key))
1970
2
                    .tag("txn_id", txn_id);
1971
2
            return 0;
1972
2
        }
1973
0
        LOG_WARNING("failed to get txn index")
1974
0
                .tag("err", err)
1975
0
                .tag("key", hex(index_key))
1976
0
                .tag("txn_id", txn_id);
1977
0
        return -1;
1978
2
    }
1979
10.5k
    if (!txn_idx_pb.ParseFromString(index_val)) {
1980
1
        LOG_WARNING("failed to parse txn index")
1981
1
                .tag("err", err)
1982
1
                .tag("key", hex(index_key))
1983
1
                .tag("txn_id", txn_id);
1984
1
        return -1;
1985
1
    }
1986
10.5k
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1987
10.5k
        txn_idx_pb.tablet_index().db_id() <= 0) {
1988
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1989
3
                .tag("key", hex(index_key))
1990
3
                .tag("txn_id", txn_id)
1991
3
                .tag("db_id",
1992
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1993
3
        return -1;
1994
3
    }
1995
1996
10.4k
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1997
10.4k
    const int64_t owner_txn_id =
1998
10.4k
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1999
10.4k
    if (owner_txn_id <= 0) {
2000
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2001
1
                .tag("key", hex(index_key))
2002
1
                .tag("txn_id", txn_id)
2003
1
                .tag("owner_txn_id", owner_txn_id);
2004
1
        return -1;
2005
1
    }
2006
2007
10.4k
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2008
10.4k
    std::string info_val;
2009
10.4k
    err = txn->get(info_key, &info_val);
2010
10.4k
    if (err != TxnErrorCode::TXN_OK) {
2011
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2012
            // maybe recycled
2013
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2014
1
                        owner_txn_id, instance_id_)
2015
1
                    .tag("key", hex(info_key))
2016
1
                    .tag("txn_id", txn_id)
2017
1
                    .tag("owner_txn_id", owner_txn_id);
2018
1
            return 0;
2019
1
        }
2020
0
        LOG_WARNING("failed to get txn info")
2021
0
                .tag("err", err)
2022
0
                .tag("key", hex(info_key))
2023
0
                .tag("txn_id", txn_id)
2024
0
                .tag("owner_txn_id", owner_txn_id);
2025
0
        return -1;
2026
1
    }
2027
10.4k
    if (!txn_info.ParseFromString(info_val)) {
2028
1
        LOG_WARNING("failed to parse txn info")
2029
1
                .tag("err", err)
2030
1
                .tag("key", hex(info_key))
2031
1
                .tag("txn_id", txn_id)
2032
1
                .tag("owner_txn_id", owner_txn_id);
2033
1
        return -1;
2034
1
    }
2035
10.5k
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2036
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2037
1
                .tag("key", hex(info_key))
2038
1
                .tag("txn_id", txn_id)
2039
1
                .tag("owner_txn_id", owner_txn_id)
2040
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2041
1
        return -1;
2042
1
    }
2043
2044
10.4k
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2045
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2046
514
                .tag("key", hex(info_key))
2047
514
                .tag("txn_id", txn_id)
2048
514
                .tag("owner_txn_id", owner_txn_id);
2049
514
        return 0;
2050
514
    }
2051
9.98k
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2052
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2053
4
                    owner_txn_id, txn_info.status())
2054
4
                .tag("key", hex(info_key))
2055
4
                .tag("txn_id", txn_id)
2056
4
                .tag("owner_txn_id", owner_txn_id);
2057
4
        return -1;
2058
4
    }
2059
2060
9.97k
    req.set_txn_id(owner_txn_id);
2061
9.97k
    req.set_db_id(db_id);
2062
2063
9.97k
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2064
9.97k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2065
9.97k
                 << " txn_info=" << txn_info.ShortDebugString();
2066
2067
9.97k
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2068
9.97k
    if (code != MetaServiceCode::OK) {
2069
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2070
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2071
0
                     << " code=" << code << " msg=" << msg;
2072
0
        return -1;
2073
0
    }
2074
2075
9.97k
    err = txn->commit();
2076
9.97k
    if (err != TxnErrorCode::TXN_OK) {
2077
0
        code = cast_as<ErrCategory::COMMIT>(err);
2078
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2079
0
        msg = ss.str();
2080
0
        return -1;
2081
0
    }
2082
2083
9.97k
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2084
9.97k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2085
9.97k
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2086
9.97k
                 << " msg=" << msg;
2087
2088
9.97k
    return 0;
2089
9.97k
}
2090
2091
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2092
11
                                                   const std::string& job_id) {
2093
11
    FinishTabletJobRequest req;
2094
11
    FinishTabletJobResponse res;
2095
11
    req.set_action(FinishTabletJobRequest::ABORT);
2096
11
    MetaServiceCode code = MetaServiceCode::OK;
2097
11
    std::string msg;
2098
11
    std::stringstream ss;
2099
2100
11
    TabletIndexPB tablet_idx;
2101
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2102
11
    if (ret == 1) {
2103
        // tablet maybe recycled, directly return 0
2104
1
        return 0;
2105
10
    } else if (ret != 0) {
2106
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2107
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2108
0
        return ret;
2109
0
    }
2110
2111
10
    std::unique_ptr<Transaction> txn;
2112
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2113
10
    if (err != TxnErrorCode::TXN_OK) {
2114
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2115
0
        return -1;
2116
0
    }
2117
2118
10
    std::string job_key =
2119
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2120
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2121
10
    std::string job_val;
2122
10
    err = txn->get(job_key, &job_val);
2123
10
    if (err != TxnErrorCode::TXN_OK) {
2124
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2125
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2126
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2127
            // A previous recycler round may have aborted the job. The caller must recheck the
2128
            // recycle key before deleting object data.
2129
1
            return 0;
2130
1
        }
2131
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2132
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2133
0
                     << " key=" << hex(job_key);
2134
0
        return -1;
2135
1
    }
2136
2137
9
    TabletJobInfoPB job_pb;
2138
9
    if (!job_pb.ParseFromString(job_val)) {
2139
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2140
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2141
0
        return -1;
2142
0
    }
2143
2144
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2145
9
    for (const auto& compaction : job_pb.compaction()) {
2146
9
        if (compaction.id() == job_id) {
2147
5
            matched_compaction = &compaction;
2148
5
            break;
2149
5
        }
2150
9
    }
2151
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2152
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2153
9
        job_pb.schema_change().id() == job_id) {
2154
3
        matched_schema_change = &job_pb.schema_change();
2155
3
    }
2156
2157
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2158
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2159
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2160
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2161
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2162
        // both the base and mirrored schema-change records.
2163
8
        if (matched_compaction != nullptr) {
2164
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2165
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2166
5
        } else {
2167
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2168
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2169
3
        }
2170
8
        req.set_action(FinishTabletJobRequest::ABORT);
2171
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2172
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2173
8
                           ss);
2174
8
        if (code != MetaServiceCode::OK) {
2175
            // These two codes mean that the job cannot be aborted anymore.
2176
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2177
            // There is no running job that still owns the PREPARE rowset, so the caller may
2178
            // recheck the recycle key.
2179
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2180
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2181
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2182
            // job again and continue recycling only when the target job id no longer exists.
2183
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2184
0
                std::unique_ptr<Transaction> check_txn;
2185
0
                err = txn_kv_->create_txn(&check_txn);
2186
0
                if (err != TxnErrorCode::TXN_OK) {
2187
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2188
0
                                 << instance_id_ << " err=" << err;
2189
0
                    return -1;
2190
0
                }
2191
2192
0
                const auto& idx = req.job().idx();
2193
0
                std::string current_job_key =
2194
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2195
0
                                        idx.partition_id(), idx.tablet_id()});
2196
0
                std::string current_job_val;
2197
0
                err = check_txn->get(current_job_key, &current_job_val);
2198
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2199
0
                    no_job_to_abort = true;
2200
0
                } else if (err != TxnErrorCode::TXN_OK) {
2201
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2202
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2203
0
                                 << " key=" << hex(current_job_key);
2204
0
                    return -1;
2205
0
                } else {
2206
0
                    TabletJobInfoPB current_job;
2207
0
                    if (!current_job.ParseFromString(current_job_val)) {
2208
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2209
0
                                     << " tablet_id=" << idx.tablet_id()
2210
0
                                     << " key=" << hex(current_job_key);
2211
0
                        return -1;
2212
0
                    }
2213
0
                    if (matched_compaction != nullptr) {
2214
0
                        no_job_to_abort = true;
2215
0
                        for (const auto& compaction : current_job.compaction()) {
2216
0
                            if (compaction.id() == job_id) {
2217
0
                                no_job_to_abort = false;
2218
0
                                break;
2219
0
                            }
2220
0
                        }
2221
0
                    } else {
2222
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2223
0
                                          current_job.schema_change().id() != job_id;
2224
0
                    }
2225
0
                }
2226
0
            }
2227
0
            if (no_job_to_abort) {
2228
0
                return 0;
2229
0
            }
2230
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2231
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2232
0
                         << " msg=" << msg;
2233
0
            return -1;
2234
0
        }
2235
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2236
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2237
8
                     << " code=" << code << " msg=" << msg;
2238
8
    } else {
2239
        // clang-format off
2240
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2241
1
                  << ", instance_id=" << instance_id_ 
2242
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2243
1
                  << ", job_id=" << job_id
2244
1
                  << ", rowset_id=" << rowset_id;
2245
        // clang-format on
2246
1
    }
2247
2248
9
    return 0;
2249
9
}
2250
2251
template <typename T>
2252
19.8k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
19.8k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2255
19.8k
    } else {
2256
9
        return &rowset_meta_pb;
2257
9
    }
2258
19.8k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2252
19.8k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
19.8k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2255
    } else {
2256
        return &rowset_meta_pb;
2257
    }
2258
19.8k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2252
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
        return rowset_meta_pb.mutable_rowset_meta();
2255
9
    } else {
2256
9
        return &rowset_meta_pb;
2257
9
    }
2258
9
}
2259
2260
template <typename T>
2261
81.5k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
81.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
80.7k
        return rowset_meta_pb.rowset_meta();
2264
80.7k
    } else {
2265
799
        return rowset_meta_pb;
2266
799
    }
2267
81.5k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2261
80.7k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
80.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
80.7k
        return rowset_meta_pb.rowset_meta();
2264
    } else {
2265
        return rowset_meta_pb;
2266
    }
2267
80.7k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2261
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
        return rowset_meta_pb.rowset_meta();
2264
799
    } else {
2265
799
        return rowset_meta_pb;
2266
799
    }
2267
799
}
2268
2269
template <typename T>
2270
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2271
41.0k
        const T& rowset_meta_pb) {
2272
41.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
0
            return std::nullopt;
2275
0
        }
2276
40.5k
    }
2277
2278
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
41.0k
    RelatedTxnOrJobAbortTask task;
2280
41.0k
    task.tablet_id = rs_meta.tablet_id();
2281
41.0k
    task.start_version = rs_meta.start_version();
2282
41.0k
    task.end_version = rs_meta.end_version();
2283
41.0k
    task.rowset_id = rs_meta.rowset_id_v2();
2284
41.0k
    if (rs_meta.has_load_id()) {
2285
21.0k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
21.0k
        task.txn_id = rs_meta.txn_id();
2287
21.0k
        return task;
2288
21.0k
    }
2289
20.0k
    if (rs_meta.has_job_id()) {
2290
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
14
        task.job_id = rs_meta.job_id();
2292
14
        return task;
2293
14
    }
2294
20.0k
    return std::nullopt;
2295
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2271
40.5k
        const T& rowset_meta_pb) {
2272
40.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
0
            return std::nullopt;
2275
0
        }
2276
40.5k
    }
2277
2278
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
40.5k
    RelatedTxnOrJobAbortTask task;
2280
40.5k
    task.tablet_id = rs_meta.tablet_id();
2281
40.5k
    task.start_version = rs_meta.start_version();
2282
40.5k
    task.end_version = rs_meta.end_version();
2283
40.5k
    task.rowset_id = rs_meta.rowset_id_v2();
2284
40.5k
    if (rs_meta.has_load_id()) {
2285
20.5k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
20.5k
        task.txn_id = rs_meta.txn_id();
2287
20.5k
        return task;
2288
20.5k
    }
2289
20.0k
    if (rs_meta.has_job_id()) {
2290
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
10
        task.job_id = rs_meta.job_id();
2292
10
        return task;
2293
10
    }
2294
20.0k
    return std::nullopt;
2295
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2271
526
        const T& rowset_meta_pb) {
2272
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
            return std::nullopt;
2275
        }
2276
    }
2277
2278
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
526
    RelatedTxnOrJobAbortTask task;
2280
526
    task.tablet_id = rs_meta.tablet_id();
2281
526
    task.start_version = rs_meta.start_version();
2282
526
    task.end_version = rs_meta.end_version();
2283
526
    task.rowset_id = rs_meta.rowset_id_v2();
2284
526
    if (rs_meta.has_load_id()) {
2285
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
518
        task.txn_id = rs_meta.txn_id();
2287
518
        return task;
2288
518
    }
2289
8
    if (rs_meta.has_job_id()) {
2290
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
4
        task.job_id = rs_meta.job_id();
2292
4
        return task;
2293
4
    }
2294
4
    return std::nullopt;
2295
8
}
2296
2297
template <typename T>
2298
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2299
10.5k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
10.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
0
            return false;
2303
0
        }
2304
10.2k
    }
2305
2306
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
10.5k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
10.5k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
10.5k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
10.5k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
10.5k
    }
2314
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
10.5k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2299
10.2k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
10.2k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
0
            return false;
2303
0
        }
2304
10.2k
    }
2305
2306
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
10.2k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
10.2k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
10.2k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
10.2k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
10.2k
    }
2314
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
10.2k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2299
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
            return false;
2303
        }
2304
    }
2305
2306
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
259
    }
2314
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
261
}
2316
2317
79.8k
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2318
79.8k
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2319
79.8k
}
2320
2321
template <typename T>
2322
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2323
76
                                   const std::vector<std::string>& keys) {
2324
204
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
129
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
129
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
129
        std::unique_ptr<Transaction> txn;
2328
129
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
129
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
129
        std::vector<std::optional<std::string>> values;
2334
129
        err = txn->batch_get(&values, batch_keys);
2335
129
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
129
        DCHECK_EQ(values.size(), batch_keys.size());
2341
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
19.9k
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
19.9k
            const auto& key = batch_keys[i];
2347
19.9k
            auto val = values[i].value();
2348
19.9k
            T rowset_meta_pb;
2349
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
19.9k
            }
2362
19.9k
            val.clear();
2363
19.9k
            rowset_meta_pb.SerializeToString(&val);
2364
19.9k
            txn->put(key, val);
2365
19.9k
        }
2366
129
        err = txn->commit();
2367
129
        if (err != TxnErrorCode::TXN_OK) {
2368
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
1
            return -1;
2370
1
        }
2371
129
    }
2372
2373
75
    return 0;
2374
76
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2323
69
                                   const std::vector<std::string>& keys) {
2324
190
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
122
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
122
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
122
        std::unique_ptr<Transaction> txn;
2328
122
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
122
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
122
        std::vector<std::optional<std::string>> values;
2334
122
        err = txn->batch_get(&values, batch_keys);
2335
122
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
122
        DCHECK_EQ(values.size(), batch_keys.size());
2341
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
19.9k
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
19.9k
            const auto& key = batch_keys[i];
2347
19.9k
            auto val = values[i].value();
2348
19.9k
            T rowset_meta_pb;
2349
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
19.9k
            }
2362
19.9k
            val.clear();
2363
19.9k
            rowset_meta_pb.SerializeToString(&val);
2364
19.9k
            txn->put(key, val);
2365
19.9k
        }
2366
122
        err = txn->commit();
2367
122
        if (err != TxnErrorCode::TXN_OK) {
2368
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
1
            return -1;
2370
1
        }
2371
122
    }
2372
2373
68
    return 0;
2374
69
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2323
7
                                   const std::vector<std::string>& keys) {
2324
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
7
        std::unique_ptr<Transaction> txn;
2328
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
7
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
7
        std::vector<std::optional<std::string>> values;
2334
7
        err = txn->batch_get(&values, batch_keys);
2335
7
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
7
        DCHECK_EQ(values.size(), batch_keys.size());
2341
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
9
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
9
            const auto& key = batch_keys[i];
2347
9
            auto val = values[i].value();
2348
9
            T rowset_meta_pb;
2349
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
            }
2362
9
            val.clear();
2363
9
            rowset_meta_pb.SerializeToString(&val);
2364
9
            txn->put(key, val);
2365
9
        }
2366
7
        err = txn->commit();
2367
7
        if (err != TxnErrorCode::TXN_OK) {
2368
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
0
            return -1;
2370
0
        }
2371
7
    }
2372
2373
7
    return 0;
2374
7
}
2375
2376
template <typename T>
2377
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2378
76
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
76
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
76
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
1
        }
2384
76
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2379
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
1
        }
2384
69
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2379
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
0
        }
2384
7
    });
2385
76
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2378
69
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
69
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
69
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
69
        }
2384
69
    });
2385
69
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2378
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
7
        }
2384
7
    });
2385
7
}
2386
2387
template <typename T>
2388
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2389
                                 const std::vector<std::string>& keys,
2390
51
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
132
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
81
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
81
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
81
        std::unique_ptr<Transaction> txn;
2395
81
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
81
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
81
        std::vector<std::optional<std::string>> values;
2401
81
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
81
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
81
        DCHECK_EQ(values.size(), batch_keys.size());
2408
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
10.5k
            const std::string& key = batch_keys[idx];
2410
10.5k
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
10.5k
            T rowset_meta_pb;
2415
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
10.5k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
10.5k
                abort_task.has_value()) {
2422
10.5k
                abort_task->key = key;
2423
10.5k
                abort_tasks->emplace_back(std::move(*abort_task));
2424
10.5k
            }
2425
10.5k
        }
2426
81
    }
2427
51
    return 0;
2428
51
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2390
46
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
121
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
75
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
75
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
75
        std::unique_ptr<Transaction> txn;
2395
75
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
75
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
75
        std::vector<std::optional<std::string>> values;
2401
75
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
75
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
75
        DCHECK_EQ(values.size(), batch_keys.size());
2408
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
10.2k
            const std::string& key = batch_keys[idx];
2410
10.2k
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
10.2k
            T rowset_meta_pb;
2415
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
10.2k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
10.2k
                abort_task.has_value()) {
2422
10.2k
                abort_task->key = key;
2423
10.2k
                abort_tasks->emplace_back(std::move(*abort_task));
2424
10.2k
            }
2425
10.2k
        }
2426
75
    }
2427
46
    return 0;
2428
46
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2390
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
6
        std::unique_ptr<Transaction> txn;
2395
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
6
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
6
        std::vector<std::optional<std::string>> values;
2401
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
6
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
6
        DCHECK_EQ(values.size(), batch_keys.size());
2408
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
261
            const std::string& key = batch_keys[idx];
2410
261
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
261
            T rowset_meta_pb;
2415
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
261
                abort_task.has_value()) {
2422
261
                abort_task->key = key;
2423
261
                abort_tasks->emplace_back(std::move(*abort_task));
2424
261
            }
2425
261
        }
2426
6
    }
2427
5
    return 0;
2428
5
}
2429
2430
template <typename T>
2431
int batch_recheck_rowsets_after_abort(
2432
        TxnKv* txn_kv, const std::string& instance_id,
2433
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2434
49
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
49
    int ret = 0;
2436
128
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
79
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
79
        std::vector<std::string> batch_keys;
2439
79
        batch_keys.reserve(limit - offset);
2440
10.6k
        for (size_t idx = offset; idx < limit; ++idx) {
2441
10.5k
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
10.5k
        }
2443
2444
79
        std::unique_ptr<Transaction> txn;
2445
79
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
79
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
79
        std::vector<std::optional<std::string>> values;
2454
79
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
79
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
79
        DCHECK_EQ(values.size(), batch_keys.size());
2462
79
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
79
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
79
                                 &batch_size);
2465
2466
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
10.5k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
10.5k
            if (!values[idx].has_value()) {
2469
1
                continue;
2470
1
            }
2471
2472
10.5k
            T rowset_meta_pb;
2473
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
10.5k
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
10.5k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
10.5k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
1
                             << instance_id << " key=" << hex(key);
2488
1
                continue;
2489
1
            }
2490
10.5k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
10.5k
        }
2492
79
    }
2493
49
    return ret;
2494
49
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2434
44
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
44
    int ret = 0;
2436
117
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
73
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
73
        std::vector<std::string> batch_keys;
2439
73
        batch_keys.reserve(limit - offset);
2440
10.3k
        for (size_t idx = offset; idx < limit; ++idx) {
2441
10.2k
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
10.2k
        }
2443
2444
73
        std::unique_ptr<Transaction> txn;
2445
73
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
73
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
73
        std::vector<std::optional<std::string>> values;
2454
73
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
73
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
73
        DCHECK_EQ(values.size(), batch_keys.size());
2462
73
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
73
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
73
                                 &batch_size);
2465
2466
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
10.2k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
10.2k
            if (!values[idx].has_value()) {
2469
1
                continue;
2470
1
            }
2471
2472
10.2k
            T rowset_meta_pb;
2473
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
10.2k
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
10.2k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
10.2k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
1
                             << instance_id << " key=" << hex(key);
2488
1
                continue;
2489
1
            }
2490
10.2k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
10.2k
        }
2492
73
    }
2493
44
    return ret;
2494
44
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2434
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
5
    int ret = 0;
2436
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
6
        std::vector<std::string> batch_keys;
2439
6
        batch_keys.reserve(limit - offset);
2440
267
        for (size_t idx = offset; idx < limit; ++idx) {
2441
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
261
        }
2443
2444
6
        std::unique_ptr<Transaction> txn;
2445
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
6
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
6
        std::vector<std::optional<std::string>> values;
2454
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
6
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
6
        DCHECK_EQ(values.size(), batch_keys.size());
2462
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
6
                                 &batch_size);
2465
2466
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
261
            if (!values[idx].has_value()) {
2469
0
                continue;
2470
0
            }
2471
2472
261
            T rowset_meta_pb;
2473
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
0
                             << instance_id << " key=" << hex(key);
2488
0
                continue;
2489
0
            }
2490
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
261
        }
2492
6
    }
2493
5
    return ret;
2494
5
}
2495
2496
template <typename T>
2497
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2498
        const std::vector<std::string>& keys,
2499
51
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
51
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
51
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
51
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
51
    int ret = 0;
2507
10.5k
    for (const auto& abort_task : abort_tasks) {
2508
10.5k
        int abort_ret = 0;
2509
10.5k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
10.5k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
10.5k
        } else {
2512
6
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
6
                                                     abort_task.job_id);
2514
6
        }
2515
10.5k
        if (abort_ret != 0) {
2516
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
3
            ret = abort_ret;
2520
3
            continue;
2521
3
        }
2522
10.5k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
10.5k
    }
2524
51
    return ret;
2525
51
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2499
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
46
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
46
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
46
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
46
    int ret = 0;
2507
10.2k
    for (const auto& abort_task : abort_tasks) {
2508
10.2k
        int abort_ret = 0;
2509
10.2k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
10.2k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
10.2k
        } else {
2512
4
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
4
                                                     abort_task.job_id);
2514
4
        }
2515
10.2k
        if (abort_ret != 0) {
2516
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
3
            ret = abort_ret;
2520
3
            continue;
2521
3
        }
2522
10.2k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
10.2k
    }
2524
46
    return ret;
2525
46
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2499
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
5
    int ret = 0;
2507
261
    for (const auto& abort_task : abort_tasks) {
2508
261
        int abort_ret = 0;
2509
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
259
        } else {
2512
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
2
                                                     abort_task.job_id);
2514
2
        }
2515
261
        if (abort_ret != 0) {
2516
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
0
            ret = abort_ret;
2520
0
            continue;
2521
0
        }
2522
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
261
    }
2524
5
    return ret;
2525
5
}
2526
2527
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2528
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2529
46
        std::atomic_long* num_recycled) {
2530
46
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2531
46
                                  num_recycled]() mutable {
2532
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
46
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
46
                                                                            keys_to_recheck);
2535
46
        if (abort_ret != 0) {
2536
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
2
                            "instance_id="
2538
2
                         << instance_id_;
2539
2
        }
2540
46
        if (keys_to_recheck.empty()) {
2541
2
            return;
2542
2
        }
2543
2544
44
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
44
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
44
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
44
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2553
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2555
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
1
                continue;
2557
1
            }
2558
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
10.2k
                                                   current_meta.tablet_id(),
2560
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
10.2k
            std::vector<std::string> keys {key};
2564
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
10.2k
        }
2570
44
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2531
2
                                  num_recycled]() mutable {
2532
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
2
                                                                            keys_to_recheck);
2535
2
        if (abort_ret != 0) {
2536
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
0
                            "instance_id="
2538
0
                         << instance_id_;
2539
0
        }
2540
2
        if (keys_to_recheck.empty()) {
2541
0
            return;
2542
0
        }
2543
2544
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
2
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
2
            const auto& current_meta = current_rowset.rowset_meta();
2553
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
2
                                   current_meta.rowset_id_v2()) != 0) {
2555
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
0
                continue;
2557
0
            }
2558
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
2
                                                   current_meta.tablet_id(),
2560
2
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
2
            std::vector<std::string> keys {key};
2564
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
2
        }
2570
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2531
44
                                  num_recycled]() mutable {
2532
44
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
44
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
44
                                                                            keys_to_recheck);
2535
44
        if (abort_ret != 0) {
2536
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
2
                            "instance_id="
2538
2
                         << instance_id_;
2539
2
        }
2540
44
        if (keys_to_recheck.empty()) {
2541
2
            return;
2542
2
        }
2543
2544
42
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
42
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
42
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
42
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2553
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2555
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
1
                continue;
2557
1
            }
2558
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
10.2k
                                                   current_meta.tablet_id(),
2560
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
10.2k
            std::vector<std::string> keys {key};
2564
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
10.2k
        }
2570
42
    });
2571
46
    if (ret != 0) {
2572
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2573
0
    }
2574
46
}
2575
2576
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2577
                                                      std::vector<std::string> rowset_keys_to_abort,
2578
                                                      std::atomic_long* num_recycled,
2579
5
                                                      RecyclerMetricsContext* metrics_context) {
2580
5
    if (rowset_keys_to_abort.empty()) {
2581
0
        return;
2582
0
    }
2583
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2584
5
                        metrics_context]() mutable {
2585
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
5
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
5
        std::vector<std::string> keys_to_delete;
2596
5
        std::vector<std::string> ref_count_keys_to_delete;
2597
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
5
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
261
            keys_to_delete.push_back(key);
2606
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
261
        }
2610
2611
5
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
5
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
261
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
261
        }
2628
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2584
3
                        metrics_context]() mutable {
2585
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
3
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
3
        std::vector<std::string> keys_to_delete;
2596
3
        std::vector<std::string> ref_count_keys_to_delete;
2597
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
3
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
3
            keys_to_delete.push_back(key);
2606
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
3
        }
2610
2611
3
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
3
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
3
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
3
        }
2628
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2584
2
                        metrics_context]() mutable {
2585
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
2
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
2
        std::vector<std::string> keys_to_delete;
2596
2
        std::vector<std::string> ref_count_keys_to_delete;
2597
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
2
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
258
            keys_to_delete.push_back(key);
2606
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
258
        }
2610
2611
2
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
2
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
258
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
258
        }
2628
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
2
    });
2639
5
}
2640
2641
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2642
1
    const std::string task_name = "recycle_ref_rowsets";
2643
1
    *has_unrecycled_rowsets = false;
2644
2645
1
    std::string data_rowset_ref_count_key_start =
2646
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2647
1
    std::string data_rowset_ref_count_key_end =
2648
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2649
2650
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2651
2652
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2653
1
    register_recycle_task(task_name, start_time);
2654
2655
1
    DORIS_CLOUD_DEFER {
2656
1
        unregister_recycle_task(task_name);
2657
1
        int64_t cost =
2658
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2660
1
                .tag("instance_id", instance_id_);
2661
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2655
1
    DORIS_CLOUD_DEFER {
2656
1
        unregister_recycle_task(task_name);
2657
1
        int64_t cost =
2658
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2660
1
                .tag("instance_id", instance_id_);
2661
1
    };
2662
2663
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2664
1
    std::set<int64_t> tablets_with_refs;
2665
1
    int64_t num_scanned = 0;
2666
2667
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2668
0
        ++num_scanned;
2669
0
        int64_t tablet_id;
2670
0
        std::string rowset_id;
2671
0
        std::string_view key(k);
2672
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2673
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2674
0
            return 0; // Continue scanning
2675
0
        }
2676
2677
0
        tablets_with_refs.insert(tablet_id);
2678
0
        return 0;
2679
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2680
2681
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2682
1
                         std::move(scan_func)) != 0) {
2683
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2684
0
        return -1;
2685
0
    }
2686
2687
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2688
1
             tablets_with_refs.size(), num_scanned)
2689
1
            .tag("instance_id", instance_id_);
2690
2691
    // Phase 2: Recycle each tablet
2692
1
    int64_t num_recycled_tablets = 0;
2693
1
    for (int64_t tablet_id : tablets_with_refs) {
2694
0
        if (stopped()) {
2695
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2696
0
                    .tag("instance_id", instance_id_)
2697
0
                    .tag("tablets_processed", num_recycled_tablets)
2698
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2699
0
            break;
2700
0
        }
2701
2702
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2703
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2704
0
            LOG_WARNING("failed to recycle tablet")
2705
0
                    .tag("instance_id", instance_id_)
2706
0
                    .tag("tablet_id", tablet_id);
2707
0
            return -1;
2708
0
        }
2709
0
        ++num_recycled_tablets;
2710
0
    }
2711
2712
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2713
1
            .tag("instance_id", instance_id_)
2714
1
            .tag("total_tablets", tablets_with_refs.size());
2715
2716
    // Phase 3: Scan again to check if any ref count keys still exist
2717
1
    std::unique_ptr<Transaction> txn;
2718
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2719
1
    if (err != TxnErrorCode::TXN_OK) {
2720
0
        LOG_WARNING("failed to create txn for final check")
2721
0
                .tag("instance_id", instance_id_)
2722
0
                .tag("err", err);
2723
0
        return -1;
2724
0
    }
2725
2726
1
    std::unique_ptr<RangeGetIterator> iter;
2727
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2728
1
    if (err != TxnErrorCode::TXN_OK) {
2729
0
        LOG_WARNING("failed to create range iterator for final check")
2730
0
                .tag("instance_id", instance_id_)
2731
0
                .tag("err", err);
2732
0
        return -1;
2733
0
    }
2734
2735
1
    *has_unrecycled_rowsets = iter->has_next();
2736
1
    if (*has_unrecycled_rowsets) {
2737
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2738
0
                .tag("instance_id", instance_id_);
2739
0
    }
2740
2741
1
    return 0;
2742
1
}
2743
2744
17
int InstanceRecycler::recycle_indexes() {
2745
17
    const std::string task_name = "recycle_indexes";
2746
17
    int64_t num_scanned = 0;
2747
17
    int64_t num_expired = 0;
2748
17
    int64_t num_recycled = 0;
2749
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2750
2751
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2752
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2753
17
    std::string index_key0;
2754
17
    std::string index_key1;
2755
17
    recycle_index_key(index_key_info0, &index_key0);
2756
17
    recycle_index_key(index_key_info1, &index_key1);
2757
2758
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2759
2760
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2761
17
    register_recycle_task(task_name, start_time);
2762
2763
17
    DORIS_CLOUD_DEFER {
2764
17
        unregister_recycle_task(task_name);
2765
17
        int64_t cost =
2766
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
17
        metrics_context.finish_report();
2768
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
17
                .tag("instance_id", instance_id_)
2770
17
                .tag("num_scanned", num_scanned)
2771
17
                .tag("num_expired", num_expired)
2772
17
                .tag("num_recycled", num_recycled);
2773
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2763
2
    DORIS_CLOUD_DEFER {
2764
2
        unregister_recycle_task(task_name);
2765
2
        int64_t cost =
2766
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
2
        metrics_context.finish_report();
2768
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
2
                .tag("instance_id", instance_id_)
2770
2
                .tag("num_scanned", num_scanned)
2771
2
                .tag("num_expired", num_expired)
2772
2
                .tag("num_recycled", num_recycled);
2773
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2763
15
    DORIS_CLOUD_DEFER {
2764
15
        unregister_recycle_task(task_name);
2765
15
        int64_t cost =
2766
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
15
        metrics_context.finish_report();
2768
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
15
                .tag("instance_id", instance_id_)
2770
15
                .tag("num_scanned", num_scanned)
2771
15
                .tag("num_expired", num_expired)
2772
15
                .tag("num_recycled", num_recycled);
2773
15
    };
2774
2775
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2776
2777
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2778
17
    std::vector<std::string_view> index_keys;
2779
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
10
        ++num_scanned;
2781
10
        RecycleIndexPB index_pb;
2782
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
10
        int64_t current_time = ::time(nullptr);
2787
10
        if (current_time <
2788
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
10
        ++num_expired;
2792
        // decode index_id
2793
10
        auto k1 = k;
2794
10
        k1.remove_prefix(1);
2795
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
10
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
10
        std::unique_ptr<Transaction> txn;
2804
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
10
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
10
        std::string val;
2810
10
        err = txn->get(k, &val);
2811
10
        if (err ==
2812
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
10
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
10
        index_pb.Clear();
2821
10
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
9
            txn->put(k, index_pb.SerializeAsString());
2828
9
            err = txn->commit();
2829
9
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
9
        }
2834
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
1
            LOG_WARNING("failed to recycle tablets under index")
2836
1
                    .tag("table_id", index_pb.table_id())
2837
1
                    .tag("instance_id", instance_id_)
2838
1
                    .tag("index_id", index_id);
2839
1
            return -1;
2840
1
        }
2841
2842
9
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
3
            std::unique_ptr<Transaction> txn;
2845
3
            err = txn_kv_->create_txn(&txn);
2846
3
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
3
            std::string index_inverted_key = versioned::index_inverted_key(
2853
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
3
            versioned_remove_all(txn.get(), meta_key);
2855
3
            txn->remove(index_key);
2856
3
            txn->remove(index_inverted_key);
2857
3
            err = txn->commit();
2858
3
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
3
        }
2863
2864
9
        metrics_context.total_recycled_num = ++num_recycled;
2865
9
        metrics_context.report();
2866
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
9
        index_keys.push_back(k);
2868
9
        return 0;
2869
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2779
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
2
        ++num_scanned;
2781
2
        RecycleIndexPB index_pb;
2782
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
2
        int64_t current_time = ::time(nullptr);
2787
2
        if (current_time <
2788
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
2
        ++num_expired;
2792
        // decode index_id
2793
2
        auto k1 = k;
2794
2
        k1.remove_prefix(1);
2795
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
2
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
2
        std::unique_ptr<Transaction> txn;
2804
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
2
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
2
        std::string val;
2810
2
        err = txn->get(k, &val);
2811
2
        if (err ==
2812
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
2
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
2
        index_pb.Clear();
2821
2
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
1
            txn->put(k, index_pb.SerializeAsString());
2828
1
            err = txn->commit();
2829
1
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
1
        }
2834
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
1
            LOG_WARNING("failed to recycle tablets under index")
2836
1
                    .tag("table_id", index_pb.table_id())
2837
1
                    .tag("instance_id", instance_id_)
2838
1
                    .tag("index_id", index_id);
2839
1
            return -1;
2840
1
        }
2841
2842
1
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
1
            std::unique_ptr<Transaction> txn;
2845
1
            err = txn_kv_->create_txn(&txn);
2846
1
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
1
            std::string index_inverted_key = versioned::index_inverted_key(
2853
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
1
            versioned_remove_all(txn.get(), meta_key);
2855
1
            txn->remove(index_key);
2856
1
            txn->remove(index_inverted_key);
2857
1
            err = txn->commit();
2858
1
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
1
        }
2863
2864
1
        metrics_context.total_recycled_num = ++num_recycled;
2865
1
        metrics_context.report();
2866
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
1
        index_keys.push_back(k);
2868
1
        return 0;
2869
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2779
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
8
        ++num_scanned;
2781
8
        RecycleIndexPB index_pb;
2782
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
8
        int64_t current_time = ::time(nullptr);
2787
8
        if (current_time <
2788
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
8
        ++num_expired;
2792
        // decode index_id
2793
8
        auto k1 = k;
2794
8
        k1.remove_prefix(1);
2795
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
8
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
8
        std::unique_ptr<Transaction> txn;
2804
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
8
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
8
        std::string val;
2810
8
        err = txn->get(k, &val);
2811
8
        if (err ==
2812
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
8
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
8
        index_pb.Clear();
2821
8
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
8
            txn->put(k, index_pb.SerializeAsString());
2828
8
            err = txn->commit();
2829
8
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
8
        }
2834
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
0
            LOG_WARNING("failed to recycle tablets under index")
2836
0
                    .tag("table_id", index_pb.table_id())
2837
0
                    .tag("instance_id", instance_id_)
2838
0
                    .tag("index_id", index_id);
2839
0
            return -1;
2840
0
        }
2841
2842
8
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
2
            std::unique_ptr<Transaction> txn;
2845
2
            err = txn_kv_->create_txn(&txn);
2846
2
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
2
            std::string index_inverted_key = versioned::index_inverted_key(
2853
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
2
            versioned_remove_all(txn.get(), meta_key);
2855
2
            txn->remove(index_key);
2856
2
            txn->remove(index_inverted_key);
2857
2
            err = txn->commit();
2858
2
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
2
        }
2863
2864
8
        metrics_context.total_recycled_num = ++num_recycled;
2865
8
        metrics_context.report();
2866
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
8
        index_keys.push_back(k);
2868
8
        return 0;
2869
8
    };
2870
2871
17
    auto loop_done = [&index_keys, this]() -> int {
2872
6
        if (index_keys.empty()) return 0;
2873
5
        DORIS_CLOUD_DEFER {
2874
5
            index_keys.clear();
2875
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2873
1
        DORIS_CLOUD_DEFER {
2874
1
            index_keys.clear();
2875
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2873
4
        DORIS_CLOUD_DEFER {
2874
4
            index_keys.clear();
2875
4
        };
2876
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
5
        return 0;
2881
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2871
2
    auto loop_done = [&index_keys, this]() -> int {
2872
2
        if (index_keys.empty()) return 0;
2873
1
        DORIS_CLOUD_DEFER {
2874
1
            index_keys.clear();
2875
1
        };
2876
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
1
        return 0;
2881
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2871
4
    auto loop_done = [&index_keys, this]() -> int {
2872
4
        if (index_keys.empty()) return 0;
2873
4
        DORIS_CLOUD_DEFER {
2874
4
            index_keys.clear();
2875
4
        };
2876
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
4
        return 0;
2881
4
    };
2882
2883
17
    if (config::enable_recycler_stats_metrics) {
2884
0
        scan_and_statistics_indexes();
2885
0
    }
2886
    // recycle_func and loop_done for scan and recycle
2887
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2888
17
}
2889
2890
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2891
8.25k
                             int64_t tablet_id) {
2892
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2893
2894
8.25k
    std::unique_ptr<Transaction> txn;
2895
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2896
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2897
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2898
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2899
0
        return false;
2900
0
    }
2901
2902
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2903
8.25k
    std::string tablet_idx_val;
2904
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2905
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2906
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2907
0
                     << " tablet_id=" << tablet_id << " err=" << err
2908
0
                     << " key=" << hex(tablet_idx_key);
2909
0
        return false;
2910
0
    }
2911
2912
8.25k
    TabletIndexPB tablet_idx_pb;
2913
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2914
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2915
0
                     << " tablet_id=" << tablet_id;
2916
0
        return false;
2917
0
    }
2918
2919
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2920
        // In the previous version, the db_id was not set in the index_pb.
2921
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2922
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2923
0
                  << " instance_id=" << instance_id
2924
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2925
0
        return true;
2926
0
    }
2927
2928
8.25k
    std::string ver_val;
2929
8.25k
    std::string ver_key =
2930
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2931
8.25k
                                   tablet_idx_pb.partition_id()});
2932
8.25k
    err = txn->get(ver_key, &ver_val);
2933
2934
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2935
216
        LOG(INFO) << ""
2936
216
                     "partition version not found, instance_id="
2937
216
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2938
216
                  << " table_id=" << tablet_idx_pb.table_id()
2939
216
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2940
216
                  << " key=" << hex(ver_key);
2941
216
        return true;
2942
216
    }
2943
2944
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2945
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2946
0
                     << " db_id=" << tablet_idx_pb.db_id()
2947
0
                     << " table_id=" << tablet_idx_pb.table_id()
2948
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2949
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2950
0
        return false;
2951
0
    }
2952
2953
8.03k
    VersionPB version_pb;
2954
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2955
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2956
0
                     << " db_id=" << tablet_idx_pb.db_id()
2957
0
                     << " table_id=" << tablet_idx_pb.table_id()
2958
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2959
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2960
0
        return false;
2961
0
    }
2962
2963
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2964
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2965
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2966
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2967
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2968
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2969
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2970
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2971
4.00k
                     << " key=" << hex(ver_key);
2972
4.00k
        return false;
2973
4.00k
    }
2974
4.03k
    return true;
2975
8.03k
}
2976
2977
15
int InstanceRecycler::recycle_partitions() {
2978
15
    const std::string task_name = "recycle_partitions";
2979
15
    int64_t num_scanned = 0;
2980
15
    int64_t num_expired = 0;
2981
15
    int64_t num_recycled = 0;
2982
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2983
2984
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2985
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2986
15
    std::string part_key0;
2987
15
    std::string part_key1;
2988
15
    recycle_partition_key(part_key_info0, &part_key0);
2989
15
    recycle_partition_key(part_key_info1, &part_key1);
2990
2991
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2992
2993
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2994
15
    register_recycle_task(task_name, start_time);
2995
2996
15
    DORIS_CLOUD_DEFER {
2997
15
        unregister_recycle_task(task_name);
2998
15
        int64_t cost =
2999
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
15
        metrics_context.finish_report();
3001
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
15
                .tag("instance_id", instance_id_)
3003
15
                .tag("num_scanned", num_scanned)
3004
15
                .tag("num_expired", num_expired)
3005
15
                .tag("num_recycled", num_recycled);
3006
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2996
2
    DORIS_CLOUD_DEFER {
2997
2
        unregister_recycle_task(task_name);
2998
2
        int64_t cost =
2999
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
2
        metrics_context.finish_report();
3001
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
2
                .tag("instance_id", instance_id_)
3003
2
                .tag("num_scanned", num_scanned)
3004
2
                .tag("num_expired", num_expired)
3005
2
                .tag("num_recycled", num_recycled);
3006
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2996
13
    DORIS_CLOUD_DEFER {
2997
13
        unregister_recycle_task(task_name);
2998
13
        int64_t cost =
2999
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
13
        metrics_context.finish_report();
3001
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
13
                .tag("instance_id", instance_id_)
3003
13
                .tag("num_scanned", num_scanned)
3004
13
                .tag("num_expired", num_expired)
3005
13
                .tag("num_recycled", num_recycled);
3006
13
    };
3007
3008
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3009
3010
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3011
15
    std::vector<std::string_view> partition_keys;
3012
15
    std::vector<std::string> partition_version_keys;
3013
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
9
        ++num_scanned;
3015
9
        RecyclePartitionPB part_pb;
3016
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
9
        int64_t current_time = ::time(nullptr);
3021
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
9
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
9
        ++num_expired;
3026
        // decode partition_id
3027
9
        auto k1 = k;
3028
9
        k1.remove_prefix(1);
3029
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
9
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
9
        std::unique_ptr<Transaction> txn;
3038
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
9
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
9
        std::string val;
3044
9
        err = txn->get(k, &val);
3045
9
        if (err ==
3046
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
9
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
9
        part_pb.Clear();
3055
9
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
8
            txn->put(k, part_pb.SerializeAsString());
3063
8
            err = txn->commit();
3064
8
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
8
        }
3069
3070
9
        int ret = 0;
3071
33
        for (int64_t index_id : part_pb.index_id()) {
3072
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
1
                LOG_WARNING("failed to recycle tablets under partition")
3074
1
                        .tag("table_id", part_pb.table_id())
3075
1
                        .tag("instance_id", instance_id_)
3076
1
                        .tag("index_id", index_id)
3077
1
                        .tag("partition_id", partition_id);
3078
1
                ret = -1;
3079
1
            }
3080
33
        }
3081
9
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
8
            std::unique_ptr<Transaction> txn;
3084
8
            err = txn_kv_->create_txn(&txn);
3085
8
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
8
            std::string partition_version_key =
3094
8
                    versioned::partition_version_key({instance_id_, partition_id});
3095
8
            versioned_remove_all(txn.get(), meta_key);
3096
8
            txn->remove(index_key);
3097
8
            txn->remove(inverted_index_key);
3098
8
            versioned_remove_all(txn.get(), partition_version_key);
3099
8
            err = txn->commit();
3100
8
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
8
        }
3105
3106
9
        if (ret == 0) {
3107
8
            ++num_recycled;
3108
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
8
            partition_keys.push_back(k);
3110
8
            if (part_pb.db_id() > 0) {
3111
8
                partition_version_keys.push_back(partition_version_key(
3112
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
8
            }
3114
8
            metrics_context.total_recycled_num = num_recycled;
3115
8
            metrics_context.report();
3116
8
        }
3117
9
        return ret;
3118
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3013
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
2
        ++num_scanned;
3015
2
        RecyclePartitionPB part_pb;
3016
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
2
        int64_t current_time = ::time(nullptr);
3021
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
2
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
2
        ++num_expired;
3026
        // decode partition_id
3027
2
        auto k1 = k;
3028
2
        k1.remove_prefix(1);
3029
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
2
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
2
        std::unique_ptr<Transaction> txn;
3038
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
2
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
2
        std::string val;
3044
2
        err = txn->get(k, &val);
3045
2
        if (err ==
3046
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
2
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
2
        part_pb.Clear();
3055
2
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
1
            txn->put(k, part_pb.SerializeAsString());
3063
1
            err = txn->commit();
3064
1
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
1
        }
3069
3070
2
        int ret = 0;
3071
2
        for (int64_t index_id : part_pb.index_id()) {
3072
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
1
                LOG_WARNING("failed to recycle tablets under partition")
3074
1
                        .tag("table_id", part_pb.table_id())
3075
1
                        .tag("instance_id", instance_id_)
3076
1
                        .tag("index_id", index_id)
3077
1
                        .tag("partition_id", partition_id);
3078
1
                ret = -1;
3079
1
            }
3080
2
        }
3081
2
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
1
            std::unique_ptr<Transaction> txn;
3084
1
            err = txn_kv_->create_txn(&txn);
3085
1
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
1
            std::string partition_version_key =
3094
1
                    versioned::partition_version_key({instance_id_, partition_id});
3095
1
            versioned_remove_all(txn.get(), meta_key);
3096
1
            txn->remove(index_key);
3097
1
            txn->remove(inverted_index_key);
3098
1
            versioned_remove_all(txn.get(), partition_version_key);
3099
1
            err = txn->commit();
3100
1
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
1
        }
3105
3106
2
        if (ret == 0) {
3107
1
            ++num_recycled;
3108
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
1
            partition_keys.push_back(k);
3110
1
            if (part_pb.db_id() > 0) {
3111
1
                partition_version_keys.push_back(partition_version_key(
3112
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
1
            }
3114
1
            metrics_context.total_recycled_num = num_recycled;
3115
1
            metrics_context.report();
3116
1
        }
3117
2
        return ret;
3118
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3013
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
7
        ++num_scanned;
3015
7
        RecyclePartitionPB part_pb;
3016
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
7
        int64_t current_time = ::time(nullptr);
3021
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
7
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
7
        ++num_expired;
3026
        // decode partition_id
3027
7
        auto k1 = k;
3028
7
        k1.remove_prefix(1);
3029
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
7
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
7
        std::unique_ptr<Transaction> txn;
3038
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
7
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
7
        std::string val;
3044
7
        err = txn->get(k, &val);
3045
7
        if (err ==
3046
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
7
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
7
        part_pb.Clear();
3055
7
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
7
            txn->put(k, part_pb.SerializeAsString());
3063
7
            err = txn->commit();
3064
7
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
7
        }
3069
3070
7
        int ret = 0;
3071
31
        for (int64_t index_id : part_pb.index_id()) {
3072
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
0
                LOG_WARNING("failed to recycle tablets under partition")
3074
0
                        .tag("table_id", part_pb.table_id())
3075
0
                        .tag("instance_id", instance_id_)
3076
0
                        .tag("index_id", index_id)
3077
0
                        .tag("partition_id", partition_id);
3078
0
                ret = -1;
3079
0
            }
3080
31
        }
3081
7
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
7
            std::unique_ptr<Transaction> txn;
3084
7
            err = txn_kv_->create_txn(&txn);
3085
7
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
7
            std::string partition_version_key =
3094
7
                    versioned::partition_version_key({instance_id_, partition_id});
3095
7
            versioned_remove_all(txn.get(), meta_key);
3096
7
            txn->remove(index_key);
3097
7
            txn->remove(inverted_index_key);
3098
7
            versioned_remove_all(txn.get(), partition_version_key);
3099
7
            err = txn->commit();
3100
7
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
7
        }
3105
3106
7
        if (ret == 0) {
3107
7
            ++num_recycled;
3108
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
7
            partition_keys.push_back(k);
3110
7
            if (part_pb.db_id() > 0) {
3111
7
                partition_version_keys.push_back(partition_version_key(
3112
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
7
            }
3114
7
            metrics_context.total_recycled_num = num_recycled;
3115
7
            metrics_context.report();
3116
7
        }
3117
7
        return ret;
3118
7
    };
3119
3120
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
5
        if (partition_keys.empty()) return 0;
3122
4
        DORIS_CLOUD_DEFER {
3123
4
            partition_keys.clear();
3124
4
            partition_version_keys.clear();
3125
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3122
1
        DORIS_CLOUD_DEFER {
3123
1
            partition_keys.clear();
3124
1
            partition_version_keys.clear();
3125
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3122
3
        DORIS_CLOUD_DEFER {
3123
3
            partition_keys.clear();
3124
3
            partition_version_keys.clear();
3125
3
        };
3126
4
        std::unique_ptr<Transaction> txn;
3127
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
4
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
8
        for (auto& k : partition_keys) {
3133
8
            txn->remove(k);
3134
8
        }
3135
8
        for (auto& k : partition_version_keys) {
3136
8
            txn->remove(k);
3137
8
        }
3138
4
        err = txn->commit();
3139
4
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
4
        return 0;
3145
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3120
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
2
        if (partition_keys.empty()) return 0;
3122
1
        DORIS_CLOUD_DEFER {
3123
1
            partition_keys.clear();
3124
1
            partition_version_keys.clear();
3125
1
        };
3126
1
        std::unique_ptr<Transaction> txn;
3127
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
1
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
1
        for (auto& k : partition_keys) {
3133
1
            txn->remove(k);
3134
1
        }
3135
1
        for (auto& k : partition_version_keys) {
3136
1
            txn->remove(k);
3137
1
        }
3138
1
        err = txn->commit();
3139
1
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
1
        return 0;
3145
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3120
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
3
        if (partition_keys.empty()) return 0;
3122
3
        DORIS_CLOUD_DEFER {
3123
3
            partition_keys.clear();
3124
3
            partition_version_keys.clear();
3125
3
        };
3126
3
        std::unique_ptr<Transaction> txn;
3127
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
3
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
7
        for (auto& k : partition_keys) {
3133
7
            txn->remove(k);
3134
7
        }
3135
7
        for (auto& k : partition_version_keys) {
3136
7
            txn->remove(k);
3137
7
        }
3138
3
        err = txn->commit();
3139
3
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
3
        return 0;
3145
3
    };
3146
3147
15
    if (config::enable_recycler_stats_metrics) {
3148
0
        scan_and_statistics_partitions();
3149
0
    }
3150
    // recycle_func and loop_done for scan and recycle
3151
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3152
15
}
3153
3154
14
int InstanceRecycler::recycle_versions() {
3155
14
    if (should_recycle_versioned_keys()) {
3156
2
        return recycle_orphan_partitions();
3157
2
    }
3158
3159
12
    int64_t num_scanned = 0;
3160
12
    int64_t num_recycled = 0;
3161
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3162
3163
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3164
3165
12
    auto start_time = steady_clock::now();
3166
3167
12
    DORIS_CLOUD_DEFER {
3168
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3169
12
        metrics_context.finish_report();
3170
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3171
12
                .tag("instance_id", instance_id_)
3172
12
                .tag("num_scanned", num_scanned)
3173
12
                .tag("num_recycled", num_recycled);
3174
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3167
12
    DORIS_CLOUD_DEFER {
3168
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3169
12
        metrics_context.finish_report();
3170
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3171
12
                .tag("instance_id", instance_id_)
3172
12
                .tag("num_scanned", num_scanned)
3173
12
                .tag("num_recycled", num_recycled);
3174
12
    };
3175
3176
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3177
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3178
12
    int64_t last_scanned_table_id = 0;
3179
12
    bool is_recycled = false; // Is last scanned kv recycled
3180
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3181
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3182
2
        ++num_scanned;
3183
2
        auto k1 = k;
3184
2
        k1.remove_prefix(1);
3185
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3186
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3187
2
        decode_key(&k1, &out);
3188
2
        DCHECK_EQ(out.size(), 6) << k;
3189
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3190
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3191
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3192
0
            return 0;
3193
0
        }
3194
2
        last_scanned_table_id = table_id;
3195
2
        is_recycled = false;
3196
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3197
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3198
2
        std::unique_ptr<Transaction> txn;
3199
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3200
2
        if (err != TxnErrorCode::TXN_OK) {
3201
0
            return -1;
3202
0
        }
3203
2
        std::unique_ptr<RangeGetIterator> iter;
3204
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3205
2
        if (err != TxnErrorCode::TXN_OK) {
3206
0
            return -1;
3207
0
        }
3208
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3209
1
            return 0;
3210
1
        }
3211
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3212
        // 1. Remove all partition version kvs of this table
3213
1
        auto partition_version_key_begin =
3214
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3215
1
        auto partition_version_key_end =
3216
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3217
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3218
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3219
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3220
1
                     << " table_id=" << table_id;
3221
        // 2. Remove the table version kv of this table
3222
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3223
1
        txn->remove(tbl_version_key);
3224
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3225
        // 3. Remove mow delete bitmap update lock and tablet job lock
3226
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3227
1
        txn->remove(lock_key);
3228
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3229
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3230
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3231
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3232
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3233
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3234
1
                     << " table_id=" << table_id;
3235
1
        err = txn->commit();
3236
1
        if (err != TxnErrorCode::TXN_OK) {
3237
0
            return -1;
3238
0
        }
3239
1
        metrics_context.total_recycled_num = ++num_recycled;
3240
1
        metrics_context.report();
3241
1
        is_recycled = true;
3242
1
        return 0;
3243
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3181
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3182
2
        ++num_scanned;
3183
2
        auto k1 = k;
3184
2
        k1.remove_prefix(1);
3185
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3186
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3187
2
        decode_key(&k1, &out);
3188
2
        DCHECK_EQ(out.size(), 6) << k;
3189
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3190
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3191
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3192
0
            return 0;
3193
0
        }
3194
2
        last_scanned_table_id = table_id;
3195
2
        is_recycled = false;
3196
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3197
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3198
2
        std::unique_ptr<Transaction> txn;
3199
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3200
2
        if (err != TxnErrorCode::TXN_OK) {
3201
0
            return -1;
3202
0
        }
3203
2
        std::unique_ptr<RangeGetIterator> iter;
3204
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3205
2
        if (err != TxnErrorCode::TXN_OK) {
3206
0
            return -1;
3207
0
        }
3208
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3209
1
            return 0;
3210
1
        }
3211
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3212
        // 1. Remove all partition version kvs of this table
3213
1
        auto partition_version_key_begin =
3214
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3215
1
        auto partition_version_key_end =
3216
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3217
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3218
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3219
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3220
1
                     << " table_id=" << table_id;
3221
        // 2. Remove the table version kv of this table
3222
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3223
1
        txn->remove(tbl_version_key);
3224
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3225
        // 3. Remove mow delete bitmap update lock and tablet job lock
3226
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3227
1
        txn->remove(lock_key);
3228
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3229
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3230
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3231
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3232
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3233
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3234
1
                     << " table_id=" << table_id;
3235
1
        err = txn->commit();
3236
1
        if (err != TxnErrorCode::TXN_OK) {
3237
0
            return -1;
3238
0
        }
3239
1
        metrics_context.total_recycled_num = ++num_recycled;
3240
1
        metrics_context.report();
3241
1
        is_recycled = true;
3242
1
        return 0;
3243
1
    };
3244
3245
12
    if (config::enable_recycler_stats_metrics) {
3246
0
        scan_and_statistics_versions();
3247
0
    }
3248
    // recycle_func and loop_done for scan and recycle
3249
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3250
14
}
3251
3252
3
int InstanceRecycler::recycle_orphan_partitions() {
3253
3
    int64_t num_scanned = 0;
3254
3
    int64_t num_recycled = 0;
3255
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3256
3257
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3258
3
            .tag("instance_id", instance_id_);
3259
3260
3
    auto start_time = steady_clock::now();
3261
3262
3
    DORIS_CLOUD_DEFER {
3263
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3264
3
        metrics_context.finish_report();
3265
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3266
3
                .tag("instance_id", instance_id_)
3267
3
                .tag("num_scanned", num_scanned)
3268
3
                .tag("num_recycled", num_recycled);
3269
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3262
3
    DORIS_CLOUD_DEFER {
3263
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3264
3
        metrics_context.finish_report();
3265
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3266
3
                .tag("instance_id", instance_id_)
3267
3
                .tag("num_scanned", num_scanned)
3268
3
                .tag("num_recycled", num_recycled);
3269
3
    };
3270
3271
3
    bool is_empty_table = false;        // whether the table has no indexes
3272
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3273
3
    int64_t current_table_id = 0;       // current scanning table id
3274
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3275
3
                         &current_table_id, &is_table_kvs_recycled,
3276
3
                         this](std::string_view k, std::string_view) {
3277
2
        ++num_scanned;
3278
3279
2
        std::string_view k1(k);
3280
2
        int64_t db_id, table_id, partition_id;
3281
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3282
2
                                                            &partition_id)) {
3283
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3284
0
            return -1;
3285
2
        } else if (table_id != current_table_id) {
3286
2
            current_table_id = table_id;
3287
2
            is_table_kvs_recycled = false;
3288
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3289
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3290
2
            if (err != TxnErrorCode::TXN_OK) {
3291
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3292
0
                             << " table_id=" << table_id << " err=" << err;
3293
0
                return -1;
3294
0
            }
3295
2
        }
3296
3297
2
        if (!is_empty_table) {
3298
            // table is not empty, skip recycle
3299
1
            return 0;
3300
1
        }
3301
3302
1
        std::unique_ptr<Transaction> txn;
3303
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3304
1
        if (err != TxnErrorCode::TXN_OK) {
3305
0
            return -1;
3306
0
        }
3307
3308
        // 1. Remove all partition related kvs
3309
1
        std::string partition_meta_key =
3310
1
                versioned::meta_partition_key({instance_id_, partition_id});
3311
1
        std::string partition_index_key =
3312
1
                versioned::partition_index_key({instance_id_, partition_id});
3313
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3314
1
                {instance_id_, db_id, table_id, partition_id});
3315
1
        std::string partition_version_key =
3316
1
                versioned::partition_version_key({instance_id_, partition_id});
3317
1
        txn->remove(partition_index_key);
3318
1
        txn->remove(partition_inverted_key);
3319
1
        versioned_remove_all(txn.get(), partition_meta_key);
3320
1
        versioned_remove_all(txn.get(), partition_version_key);
3321
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3322
1
                     << " table_id=" << table_id << " db_id=" << db_id
3323
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3324
1
                     << " partition_version_key=" << hex(partition_version_key);
3325
3326
1
        if (!is_table_kvs_recycled) {
3327
1
            is_table_kvs_recycled = true;
3328
3329
            // 2. Remove the table version kv of this table
3330
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3331
1
            versioned_remove_all(txn.get(), table_version_key);
3332
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3333
            // 3. Remove mow delete bitmap update lock and tablet job lock
3334
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3335
1
            txn->remove(lock_key);
3336
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3337
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3338
1
            std::string tablet_job_key_end =
3339
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3340
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3341
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3342
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3343
1
                         << " table_id=" << table_id;
3344
1
        }
3345
3346
1
        err = txn->commit();
3347
1
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            return -1;
3349
0
        }
3350
1
        metrics_context.total_recycled_num = ++num_recycled;
3351
1
        metrics_context.report();
3352
1
        return 0;
3353
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
3276
2
                         this](std::string_view k, std::string_view) {
3277
2
        ++num_scanned;
3278
3279
2
        std::string_view k1(k);
3280
2
        int64_t db_id, table_id, partition_id;
3281
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3282
2
                                                            &partition_id)) {
3283
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3284
0
            return -1;
3285
2
        } else if (table_id != current_table_id) {
3286
2
            current_table_id = table_id;
3287
2
            is_table_kvs_recycled = false;
3288
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3289
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3290
2
            if (err != TxnErrorCode::TXN_OK) {
3291
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3292
0
                             << " table_id=" << table_id << " err=" << err;
3293
0
                return -1;
3294
0
            }
3295
2
        }
3296
3297
2
        if (!is_empty_table) {
3298
            // table is not empty, skip recycle
3299
1
            return 0;
3300
1
        }
3301
3302
1
        std::unique_ptr<Transaction> txn;
3303
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3304
1
        if (err != TxnErrorCode::TXN_OK) {
3305
0
            return -1;
3306
0
        }
3307
3308
        // 1. Remove all partition related kvs
3309
1
        std::string partition_meta_key =
3310
1
                versioned::meta_partition_key({instance_id_, partition_id});
3311
1
        std::string partition_index_key =
3312
1
                versioned::partition_index_key({instance_id_, partition_id});
3313
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3314
1
                {instance_id_, db_id, table_id, partition_id});
3315
1
        std::string partition_version_key =
3316
1
                versioned::partition_version_key({instance_id_, partition_id});
3317
1
        txn->remove(partition_index_key);
3318
1
        txn->remove(partition_inverted_key);
3319
1
        versioned_remove_all(txn.get(), partition_meta_key);
3320
1
        versioned_remove_all(txn.get(), partition_version_key);
3321
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3322
1
                     << " table_id=" << table_id << " db_id=" << db_id
3323
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3324
1
                     << " partition_version_key=" << hex(partition_version_key);
3325
3326
1
        if (!is_table_kvs_recycled) {
3327
1
            is_table_kvs_recycled = true;
3328
3329
            // 2. Remove the table version kv of this table
3330
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3331
1
            versioned_remove_all(txn.get(), table_version_key);
3332
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3333
            // 3. Remove mow delete bitmap update lock and tablet job lock
3334
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3335
1
            txn->remove(lock_key);
3336
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3337
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3338
1
            std::string tablet_job_key_end =
3339
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3340
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3341
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3342
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3343
1
                         << " table_id=" << table_id;
3344
1
        }
3345
3346
1
        err = txn->commit();
3347
1
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            return -1;
3349
0
        }
3350
1
        metrics_context.total_recycled_num = ++num_recycled;
3351
1
        metrics_context.report();
3352
1
        return 0;
3353
1
    };
3354
3355
    // recycle_func and loop_done for scan and recycle
3356
3
    return scan_and_recycle(
3357
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3358
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3359
3
            std::move(recycle_func));
3360
3
}
3361
3362
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3363
                                      RecyclerMetricsContext& metrics_context,
3364
54
                                      int64_t partition_id) {
3365
54
    int64_t num_scanned = 0;
3366
54
    std::atomic_long num_recycled = 0;
3367
3368
54
    std::string tablet_key_begin, tablet_key_end;
3369
54
    std::string stats_key_begin, stats_key_end;
3370
54
    std::string job_key_begin, job_key_end;
3371
3372
54
    std::string tablet_belongs;
3373
54
    if (partition_id > 0) {
3374
        // recycle tablets in a partition belonging to the index
3375
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3376
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3377
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3378
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3379
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3380
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3381
33
        tablet_belongs = "partition";
3382
33
    } else {
3383
        // recycle tablets in the index
3384
21
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3385
21
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3386
21
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3387
21
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3388
21
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3389
21
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3390
21
        tablet_belongs = "index";
3391
21
    }
3392
3393
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3394
54
            .tag("table_id", table_id)
3395
54
            .tag("index_id", index_id)
3396
54
            .tag("partition_id", partition_id);
3397
3398
54
    auto start_time = steady_clock::now();
3399
3400
54
    DORIS_CLOUD_DEFER {
3401
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
54
                .tag("instance_id", instance_id_)
3404
54
                .tag("table_id", table_id)
3405
54
                .tag("index_id", index_id)
3406
54
                .tag("partition_id", partition_id)
3407
54
                .tag("num_scanned", num_scanned)
3408
54
                .tag("num_recycled", num_recycled);
3409
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3400
4
    DORIS_CLOUD_DEFER {
3401
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
4
                .tag("instance_id", instance_id_)
3404
4
                .tag("table_id", table_id)
3405
4
                .tag("index_id", index_id)
3406
4
                .tag("partition_id", partition_id)
3407
4
                .tag("num_scanned", num_scanned)
3408
4
                .tag("num_recycled", num_recycled);
3409
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3400
50
    DORIS_CLOUD_DEFER {
3401
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
50
                .tag("instance_id", instance_id_)
3404
50
                .tag("table_id", table_id)
3405
50
                .tag("index_id", index_id)
3406
50
                .tag("partition_id", partition_id)
3407
50
                .tag("num_scanned", num_scanned)
3408
50
                .tag("num_recycled", num_recycled);
3409
50
    };
3410
3411
    // The tablet key and id which have been recycled.
3412
54
    struct TabletInfo {
3413
54
        std::string_view tablet_meta_key;
3414
54
        int64_t tablet_id;
3415
54
    };
3416
54
    SyncExecutor<TabletInfo> sync_executor(
3417
54
            _thread_pool_group.recycle_tablet_pool,
3418
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3419
54
                        index_id, partition_id),
3420
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3420
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3420
243
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3421
3422
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3423
54
    std::vector<std::string> init_rs_keys;
3424
54
    bool has_failure = false;
3425
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
8.25k
        ++num_scanned;
3427
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
4.00k
            has_failure = true;
3439
4.00k
            return -1;
3440
4.00k
        }
3441
3442
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
4.25k
        sync_executor.add(
3444
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
2
                        LOG_WARNING("failed to recycle tablet")
3447
2
                                .tag("instance_id", instance_id_)
3448
2
                                .tag("tablet_id", tid);
3449
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
2
                    }
3451
4.25k
                    ++num_recycled;
3452
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3444
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
0
                        LOG_WARNING("failed to recycle tablet")
3447
0
                                .tag("instance_id", instance_id_)
3448
0
                                .tag("tablet_id", tid);
3449
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
0
                    }
3451
4.00k
                    ++num_recycled;
3452
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3444
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
2
                        LOG_WARNING("failed to recycle tablet")
3447
2
                                .tag("instance_id", instance_id_)
3448
2
                                .tag("tablet_id", tid);
3449
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
2
                    }
3451
250
                    ++num_recycled;
3452
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
252
                });
3455
4.25k
        return 0;
3456
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3425
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
8.00k
        ++num_scanned;
3427
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
4.00k
            has_failure = true;
3439
4.00k
            return -1;
3440
4.00k
        }
3441
3442
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
4.00k
        sync_executor.add(
3444
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
4.00k
                        LOG_WARNING("failed to recycle tablet")
3447
4.00k
                                .tag("instance_id", instance_id_)
3448
4.00k
                                .tag("tablet_id", tid);
3449
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
4.00k
                    }
3451
4.00k
                    ++num_recycled;
3452
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.00k
                });
3455
4.00k
        return 0;
3456
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3425
253
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
253
        ++num_scanned;
3427
253
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
253
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
253
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
253
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
253
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
1
            has_failure = true;
3439
1
            return -1;
3440
1
        }
3441
3442
253
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
252
        sync_executor.add(
3444
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
252
                        LOG_WARNING("failed to recycle tablet")
3447
252
                                .tag("instance_id", instance_id_)
3448
252
                                .tag("tablet_id", tid);
3449
252
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
252
                    }
3451
252
                    ++num_recycled;
3452
252
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
252
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
252
                });
3455
252
        return 0;
3456
252
    };
3457
3458
54
    auto loop_done = [&, this]() -> int {
3459
54
        int ret = 0;
3460
54
        bool finished = true;
3461
54
        bool has_empty_key = false;
3462
54
        DORIS_CLOUD_DEFER {
3463
54
            init_rs_keys.clear();
3464
54
            has_failure = false;
3465
54
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3462
4
        DORIS_CLOUD_DEFER {
3463
4
            init_rs_keys.clear();
3464
4
            has_failure = false;
3465
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3462
50
        DORIS_CLOUD_DEFER {
3463
50
            init_rs_keys.clear();
3464
50
            has_failure = false;
3465
50
        };
3466
54
        auto tablets_info = sync_executor.when_all(&finished);
3467
54
        if (!finished) {
3468
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
1
            return -1;
3470
1
        }
3471
3472
53
        size_t size_before_erase = tablets_info.size();
3473
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
3473
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
3473
251
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
53
        if (tablets_info.empty()) {
3475
2
            return size_before_erase == 0 ? 0 : -1;
3476
51
        } else if (size_before_erase != tablets_info.size()) {
3477
1
            has_empty_key = true;
3478
1
        }
3479
3480
51
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3482
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3482
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
958
        });
3485
51
        std::unique_ptr<Transaction> txn;
3486
51
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
51
        std::string tablet_key_end;
3491
51
        if (!tablets_info.empty()) {
3492
51
            if (!has_empty_key && !has_failure) {
3493
49
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
49
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
49
            } else {
3496
8
                for (auto& tablet_info : tablets_info) {
3497
8
                    txn->remove(tablet_info.tablet_meta_key);
3498
8
                }
3499
2
            }
3500
51
        }
3501
51
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
7
            std::vector<std::string> versioned_idx_keys;
3504
7
            versioned_idx_keys.reserve(tablets_info.size());
3505
8
            for (const auto& tablet_info : tablets_info) {
3506
8
                versioned_idx_keys.push_back(
3507
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
8
            }
3509
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
7
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
8
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
8
                const auto& tablet_info = tablets_info[i];
3524
8
                TabletIndexPB tablet_index_pb;
3525
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
8
                         tablet_info.tablet_id});
3535
8
                txn->remove(versioned_inverted_idx_key);
3536
8
                txn->remove(versioned_idx_keys[i]);
3537
8
            }
3538
8
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
8
                LOG_INFO("remove versioned tablet compact stats key")
3542
8
                        .tag("compact_stats_key", hex(k));
3543
8
                versioned_remove_all(txn.get(), k);
3544
8
            }
3545
8
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
8
                versioned_remove_all(txn.get(), k);
3550
8
            }
3551
8
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
8
                versioned_remove_all(txn.get(), k);
3556
8
            }
3557
7
        }
3558
4.25k
        for (auto& tablet_info : tablets_info) {
3559
4.25k
            std::string k;
3560
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
4.25k
            txn->remove(k);
3562
4.25k
        }
3563
4.25k
        for (auto& tablet_info : tablets_info) {
3564
4.25k
            std::string k;
3565
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
4.25k
            txn->remove(k);
3567
4.25k
        }
3568
51
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
51
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
51
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
1
                         << ", err=" << err;
3575
1
            return -1;
3576
1
        }
3577
50
        return ret;
3578
51
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3458
4
    auto loop_done = [&, this]() -> int {
3459
4
        int ret = 0;
3460
4
        bool finished = true;
3461
4
        bool has_empty_key = false;
3462
4
        DORIS_CLOUD_DEFER {
3463
4
            init_rs_keys.clear();
3464
4
            has_failure = false;
3465
4
        };
3466
4
        auto tablets_info = sync_executor.when_all(&finished);
3467
4
        if (!finished) {
3468
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
0
            return -1;
3470
0
        }
3471
3472
4
        size_t size_before_erase = tablets_info.size();
3473
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
4
        if (tablets_info.empty()) {
3475
2
            return size_before_erase == 0 ? 0 : -1;
3476
2
        } else if (size_before_erase != tablets_info.size()) {
3477
0
            has_empty_key = true;
3478
0
        }
3479
3480
2
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
2
        });
3485
2
        std::unique_ptr<Transaction> txn;
3486
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
2
        std::string tablet_key_end;
3491
2
        if (!tablets_info.empty()) {
3492
2
            if (!has_empty_key && !has_failure) {
3493
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
2
            } else {
3496
0
                for (auto& tablet_info : tablets_info) {
3497
0
                    txn->remove(tablet_info.tablet_meta_key);
3498
0
                }
3499
0
            }
3500
2
        }
3501
2
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
0
            std::vector<std::string> versioned_idx_keys;
3504
0
            versioned_idx_keys.reserve(tablets_info.size());
3505
0
            for (const auto& tablet_info : tablets_info) {
3506
0
                versioned_idx_keys.push_back(
3507
0
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
0
            }
3509
0
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
0
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
0
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
0
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
0
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
0
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
0
                const auto& tablet_info = tablets_info[i];
3524
0
                TabletIndexPB tablet_index_pb;
3525
0
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
0
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
0
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
0
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
0
                         tablet_info.tablet_id});
3535
0
                txn->remove(versioned_inverted_idx_key);
3536
0
                txn->remove(versioned_idx_keys[i]);
3537
0
            }
3538
0
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
0
                LOG_INFO("remove versioned tablet compact stats key")
3542
0
                        .tag("compact_stats_key", hex(k));
3543
0
                versioned_remove_all(txn.get(), k);
3544
0
            }
3545
0
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
0
                versioned_remove_all(txn.get(), k);
3550
0
            }
3551
0
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
0
                versioned_remove_all(txn.get(), k);
3556
0
            }
3557
0
        }
3558
4.00k
        for (auto& tablet_info : tablets_info) {
3559
4.00k
            std::string k;
3560
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
4.00k
            txn->remove(k);
3562
4.00k
        }
3563
4.00k
        for (auto& tablet_info : tablets_info) {
3564
4.00k
            std::string k;
3565
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
4.00k
            txn->remove(k);
3567
4.00k
        }
3568
2
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
2
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
0
                         << ", err=" << err;
3575
0
            return -1;
3576
0
        }
3577
2
        return ret;
3578
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3458
50
    auto loop_done = [&, this]() -> int {
3459
50
        int ret = 0;
3460
50
        bool finished = true;
3461
50
        bool has_empty_key = false;
3462
50
        DORIS_CLOUD_DEFER {
3463
50
            init_rs_keys.clear();
3464
50
            has_failure = false;
3465
50
        };
3466
50
        auto tablets_info = sync_executor.when_all(&finished);
3467
50
        if (!finished) {
3468
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
1
            return -1;
3470
1
        }
3471
3472
49
        size_t size_before_erase = tablets_info.size();
3473
49
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
49
        if (tablets_info.empty()) {
3475
0
            return size_before_erase == 0 ? 0 : -1;
3476
49
        } else if (size_before_erase != tablets_info.size()) {
3477
1
            has_empty_key = true;
3478
1
        }
3479
3480
49
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
49
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
49
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
49
        });
3485
49
        std::unique_ptr<Transaction> txn;
3486
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
49
        std::string tablet_key_end;
3491
49
        if (!tablets_info.empty()) {
3492
49
            if (!has_empty_key && !has_failure) {
3493
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
47
            } else {
3496
8
                for (auto& tablet_info : tablets_info) {
3497
8
                    txn->remove(tablet_info.tablet_meta_key);
3498
8
                }
3499
2
            }
3500
49
        }
3501
49
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
7
            std::vector<std::string> versioned_idx_keys;
3504
7
            versioned_idx_keys.reserve(tablets_info.size());
3505
8
            for (const auto& tablet_info : tablets_info) {
3506
8
                versioned_idx_keys.push_back(
3507
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
8
            }
3509
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
7
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
8
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
8
                const auto& tablet_info = tablets_info[i];
3524
8
                TabletIndexPB tablet_index_pb;
3525
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
8
                         tablet_info.tablet_id});
3535
8
                txn->remove(versioned_inverted_idx_key);
3536
8
                txn->remove(versioned_idx_keys[i]);
3537
8
            }
3538
8
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
8
                LOG_INFO("remove versioned tablet compact stats key")
3542
8
                        .tag("compact_stats_key", hex(k));
3543
8
                versioned_remove_all(txn.get(), k);
3544
8
            }
3545
8
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
8
                versioned_remove_all(txn.get(), k);
3550
8
            }
3551
8
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
8
                versioned_remove_all(txn.get(), k);
3556
8
            }
3557
7
        }
3558
250
        for (auto& tablet_info : tablets_info) {
3559
250
            std::string k;
3560
250
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
250
            txn->remove(k);
3562
250
        }
3563
250
        for (auto& tablet_info : tablets_info) {
3564
250
            std::string k;
3565
250
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
250
            txn->remove(k);
3567
250
        }
3568
49
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
49
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
1
                         << ", err=" << err;
3575
1
            return -1;
3576
1
        }
3577
48
        return ret;
3578
49
    };
3579
3580
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3581
54
                               std::move(loop_done));
3582
54
    if (ret != 0) {
3583
6
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3584
6
        return ret;
3585
6
    }
3586
3587
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3588
48
    std::unique_ptr<Transaction> txn;
3589
48
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3590
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3591
0
        return -1;
3592
0
    }
3593
48
    txn->remove(stats_key_begin, stats_key_end);
3594
48
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3595
48
                 << " end=" << hex(stats_key_end);
3596
48
    txn->remove(job_key_begin, job_key_end);
3597
48
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3598
48
    std::string schema_key_begin, schema_key_end;
3599
48
    std::string schema_dict_key;
3600
48
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3601
48
    if (partition_id <= 0) {
3602
        // Delete schema kv of this index
3603
16
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3604
16
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3605
16
        txn->remove(schema_key_begin, schema_key_end);
3606
16
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3607
16
                     << " end=" << hex(schema_key_end);
3608
16
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3609
16
        txn->remove(schema_dict_key);
3610
16
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3611
16
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3612
16
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3613
16
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3614
16
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3615
16
                     << " end=" << hex(versioned_schema_key_end);
3616
16
    }
3617
3618
48
    TxnErrorCode err = txn->commit();
3619
48
    if (err != TxnErrorCode::TXN_OK) {
3620
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3621
0
                     << " err=" << err;
3622
0
        return -1;
3623
0
    }
3624
3625
48
    return ret;
3626
48
}
3627
3628
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3629
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3630
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3631
5.61k
    if (num_segments <= 0) return 0;
3632
3633
5.61k
    std::vector<std::string> file_paths;
3634
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3635
0
        return -1;
3636
0
    }
3637
3638
    // Process inverted indexes
3639
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3640
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3641
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3642
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3643
5.61k
    bool delete_rowset_data_by_prefix = false;
3644
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3645
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3646
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3647
0
        delete_rowset_data_by_prefix = true;
3648
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3649
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3650
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3651
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3652
10.0k
            }
3653
10.0k
        }
3654
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3655
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3656
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3657
2.00k
        }
3658
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3659
        // schema version and index id are not found, delete rowset data by prefix directly.
3660
0
        delete_rowset_data_by_prefix = true;
3661
809
    } else {
3662
        // otherwise, try to get schema kv
3663
809
        InvertedIndexInfo index_info;
3664
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3665
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3666
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3667
809
                                 &inverted_index_get_ret);
3668
809
        if (inverted_index_get_ret == 0) {
3669
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3670
809
                index_format = index_info.first;
3671
809
            }
3672
809
            index_ids = index_info.second;
3673
809
        } else if (inverted_index_get_ret == 1) {
3674
            // 1. Schema kv not found means tablet has been recycled
3675
            // Maybe some tablet recycle failed by some bugs
3676
            // We need to delete again to double check
3677
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3678
            // because we are uncertain about the inverted index information.
3679
            // If there are inverted indexes, some data might not be deleted,
3680
            // but this is acceptable as we have made our best effort to delete the data.
3681
0
            LOG_INFO(
3682
0
                    "delete rowset data schema kv not found, need to delete again to double "
3683
0
                    "check")
3684
0
                    .tag("instance_id", instance_id_)
3685
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3686
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3687
            // Currently index_ids is guaranteed to be empty,
3688
            // but we clear it again here as a safeguard against future code changes
3689
            // that might cause index_ids to no longer be empty
3690
0
            index_format = InvertedIndexStorageFormatPB::V2;
3691
0
            index_ids.clear();
3692
0
        } else {
3693
            // failed to get schema kv, delete rowset data by prefix directly.
3694
0
            delete_rowset_data_by_prefix = true;
3695
0
        }
3696
809
    }
3697
3698
5.61k
    if (delete_rowset_data_by_prefix) {
3699
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3700
0
                                  rs_meta_pb.rowset_id_v2());
3701
0
    }
3702
3703
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3704
5.61k
    if (it == accessor_map_.end()) {
3705
1.59k
        LOG_WARNING("instance has no such resource id")
3706
1.59k
                .tag("instance_id", instance_id_)
3707
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3708
1.59k
        return -1;
3709
1.59k
    }
3710
4.01k
    auto& accessor = it->second;
3711
3712
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3713
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3714
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3715
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3716
20.0k
                                         &file_paths);
3717
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3718
40.0k
            for (const auto& index_id : index_ids) {
3719
40.0k
                add_file_to_delete_if_not_packed(
3720
40.0k
                        rs_meta_pb,
3721
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3722
40.0k
                                               index_id.second),
3723
40.0k
                        &file_paths);
3724
40.0k
            }
3725
20.0k
        } else if (!index_ids.empty()) {
3726
0
            add_file_to_delete_if_not_packed(
3727
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3728
0
        }
3729
20.0k
    }
3730
3731
4.01k
    int should_delete_dbm = may_have_versioned_delete_bitmap(rs_meta_pb.partition_id(), tablet_id);
3732
4.01k
    if (should_delete_dbm == 1) {
3733
4.00k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3734
4.00k
        std::vector<std::string> rowset_dbm_keys;
3735
4.00k
        if (decrement_delete_bitmap_packed_file_ref_counts(
3736
4.00k
                    tablet_id, rowset_id, &delete_bitmap_storage_type, nullptr) != 0) {
3737
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3738
0
                    .tag("instance_id", instance_id_)
3739
0
                    .tag("tablet_id", tablet_id)
3740
0
                    .tag("rowset_id", rowset_id);
3741
0
            return -1;
3742
0
        }
3743
4.00k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3744
2.00k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3745
2.00k
        }
3746
4.00k
    } else if (should_delete_dbm != 0) {
3747
0
        return -1;
3748
0
    }
3749
    // TODO(AlexYue): seems could do do batch
3750
4.01k
    return accessor->delete_files(file_paths);
3751
4.01k
}
3752
3753
102k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3754
102k
    LOG_INFO("begin process_packed_file_location_index")
3755
102k
            .tag("instance_id", instance_id_)
3756
102k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3757
102k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3758
102k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3759
102k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3760
102k
    if (index_map.empty()) {
3761
87.5k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3762
87.5k
                .tag("instance_id", instance_id_)
3763
87.5k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3764
87.5k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3765
87.5k
        return 0;
3766
87.5k
    }
3767
3768
15.0k
    struct PackedSmallFileInfo {
3769
15.0k
        std::string small_file_path;
3770
15.0k
    };
3771
15.0k
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3772
15.0k
    packed_file_updates.reserve(index_map.size());
3773
29.9k
    for (const auto& [small_path, index_pb] : index_map) {
3774
30.0k
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3775
0
            continue;
3776
0
        }
3777
29.9k
        packed_file_updates[index_pb.packed_file_path()].push_back(
3778
29.9k
                PackedSmallFileInfo {small_path});
3779
29.9k
    }
3780
15.0k
    if (packed_file_updates.empty()) {
3781
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3782
0
                .tag("instance_id", instance_id_)
3783
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3784
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3785
0
                .tag("index_map_size", index_map.size());
3786
0
        return 0;
3787
0
    }
3788
3789
15.0k
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3790
15.0k
    int ret = 0;
3791
15.0k
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3792
15.0k
        if (small_files.empty()) {
3793
0
            continue;
3794
0
        }
3795
3796
15.0k
        bool success = false;
3797
15.0k
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3798
14.9k
            std::unique_ptr<Transaction> txn;
3799
14.9k
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3800
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3801
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3802
0
                        .tag("instance_id", instance_id_)
3803
0
                        .tag("packed_file_path", packed_file_path)
3804
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3805
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3806
0
                        .tag("err", err);
3807
0
                ret = -1;
3808
0
                break;
3809
0
            }
3810
3811
14.9k
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3812
14.9k
            std::string packed_val;
3813
14.9k
            err = txn->get(packed_key, &packed_val);
3814
14.9k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3815
0
                LOG_WARNING("packed file info not found when recycling rowset")
3816
0
                        .tag("instance_id", instance_id_)
3817
0
                        .tag("packed_file_path", packed_file_path)
3818
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3819
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3820
0
                        .tag("key", hex(packed_key))
3821
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3822
                // Skip this packed file entry and continue with others
3823
0
                success = true;
3824
0
                break;
3825
0
            }
3826
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3827
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3828
0
                        .tag("instance_id", instance_id_)
3829
0
                        .tag("packed_file_path", packed_file_path)
3830
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3831
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3832
0
                        .tag("err", err);
3833
0
                ret = -1;
3834
0
                break;
3835
0
            }
3836
3837
14.9k
            cloud::PackedFileInfoPB packed_info;
3838
14.9k
            if (!packed_info.ParseFromString(packed_val)) {
3839
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3840
0
                        .tag("instance_id", instance_id_)
3841
0
                        .tag("packed_file_path", packed_file_path)
3842
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3843
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3844
0
                ret = -1;
3845
0
                break;
3846
0
            }
3847
3848
14.9k
            LOG_INFO("packed file update check")
3849
14.9k
                    .tag("instance_id", instance_id_)
3850
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3851
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3852
14.9k
                    .tag("merged_file_path", packed_file_path)
3853
14.9k
                    .tag("requested_small_files", small_files.size())
3854
14.9k
                    .tag("merge_entries", packed_info.slices_size());
3855
3856
14.9k
            auto* small_file_entries = packed_info.mutable_slices();
3857
14.9k
            int64_t changed_files = 0;
3858
14.9k
            int64_t missing_entries = 0;
3859
14.9k
            int64_t already_deleted = 0;
3860
29.9k
            for (const auto& small_file_info : small_files) {
3861
29.9k
                bool found = false;
3862
74.8k
                for (auto& small_file_entry : *small_file_entries) {
3863
74.8k
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3864
30.0k
                        if (!small_file_entry.deleted()) {
3865
29.9k
                            small_file_entry.set_deleted(true);
3866
29.9k
                            if (!small_file_entry.corrected()) {
3867
29.9k
                                small_file_entry.set_corrected(true);
3868
29.9k
                            }
3869
29.9k
                            ++changed_files;
3870
29.9k
                        } else {
3871
15
                            ++already_deleted;
3872
15
                        }
3873
30.0k
                        found = true;
3874
30.0k
                        break;
3875
30.0k
                    }
3876
74.8k
                }
3877
29.9k
                if (!found) {
3878
0
                    ++missing_entries;
3879
0
                    LOG_WARNING("packed file info missing small file entry")
3880
0
                            .tag("instance_id", instance_id_)
3881
0
                            .tag("packed_file_path", packed_file_path)
3882
0
                            .tag("small_file_path", small_file_info.small_file_path)
3883
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3884
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3885
0
                }
3886
29.9k
            }
3887
3888
14.9k
            if (changed_files == 0) {
3889
0
                LOG_INFO("skip merge file update: no merge entries changed")
3890
0
                        .tag("instance_id", instance_id_)
3891
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3892
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3893
0
                        .tag("merged_file_path", packed_file_path)
3894
0
                        .tag("missing_entries", missing_entries)
3895
0
                        .tag("already_deleted", already_deleted)
3896
0
                        .tag("requested_small_files", small_files.size())
3897
0
                        .tag("merge_entries", packed_info.slices_size());
3898
0
                success = true;
3899
0
                break;
3900
0
            }
3901
3902
            // Calculate remaining files
3903
14.9k
            int64_t left_file_count = 0;
3904
14.9k
            int64_t left_file_bytes = 0;
3905
60.0k
            for (const auto& small_file_entry : packed_info.slices()) {
3906
60.0k
                if (!small_file_entry.deleted()) {
3907
15.0k
                    ++left_file_count;
3908
15.0k
                    left_file_bytes += small_file_entry.size();
3909
15.0k
                }
3910
60.0k
            }
3911
14.9k
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3912
14.9k
            packed_info.set_ref_cnt(left_file_count);
3913
14.9k
            LOG_INFO("updated packed file reference info")
3914
14.9k
                    .tag("instance_id", instance_id_)
3915
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3916
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3917
14.9k
                    .tag("packed_file_path", packed_file_path)
3918
14.9k
                    .tag("ref_cnt", left_file_count)
3919
14.9k
                    .tag("left_file_bytes", left_file_bytes);
3920
3921
14.9k
            if (left_file_count == 0) {
3922
7.50k
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3923
7.50k
            }
3924
3925
14.9k
            std::string updated_val;
3926
14.9k
            if (!packed_info.SerializeToString(&updated_val)) {
3927
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3928
0
                        .tag("instance_id", instance_id_)
3929
0
                        .tag("packed_file_path", packed_file_path)
3930
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3931
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3932
0
                ret = -1;
3933
0
                break;
3934
0
            }
3935
3936
14.9k
            txn->put(packed_key, updated_val);
3937
14.9k
            err = txn->commit();
3938
15.0k
            if (err == TxnErrorCode::TXN_OK) {
3939
15.0k
                success = true;
3940
15.0k
                if (left_file_count == 0) {
3941
7.50k
                    LOG_INFO("packed file ready to delete, deleting immediately")
3942
7.50k
                            .tag("instance_id", instance_id_)
3943
7.50k
                            .tag("packed_file_path", packed_file_path);
3944
7.50k
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3945
0
                        ret = -1;
3946
0
                    }
3947
7.50k
                }
3948
15.0k
                break;
3949
15.0k
            }
3950
18.4E
            if (err == TxnErrorCode::TXN_CONFLICT) {
3951
0
                if (attempt >= max_retry_times) {
3952
0
                    LOG_WARNING("packed file info update conflict after max retry")
3953
0
                            .tag("instance_id", instance_id_)
3954
0
                            .tag("packed_file_path", packed_file_path)
3955
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3956
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3957
0
                            .tag("changed_files", changed_files)
3958
0
                            .tag("attempt", attempt);
3959
0
                    ret = -1;
3960
0
                    break;
3961
0
                }
3962
0
                LOG_WARNING("packed file info update conflict, retrying")
3963
0
                        .tag("instance_id", instance_id_)
3964
0
                        .tag("packed_file_path", packed_file_path)
3965
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3966
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3967
0
                        .tag("changed_files", changed_files)
3968
0
                        .tag("attempt", attempt);
3969
0
                sleep_for_packed_file_retry();
3970
0
                continue;
3971
0
            }
3972
3973
18.4E
            LOG_WARNING("failed to commit packed file info update")
3974
18.4E
                    .tag("instance_id", instance_id_)
3975
18.4E
                    .tag("packed_file_path", packed_file_path)
3976
18.4E
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3977
18.4E
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3978
18.4E
                    .tag("err", err)
3979
18.4E
                    .tag("changed_files", changed_files);
3980
18.4E
            ret = -1;
3981
18.4E
            break;
3982
18.4E
        }
3983
3984
15.0k
        if (!success) {
3985
0
            ret = -1;
3986
0
        }
3987
15.0k
    }
3988
3989
15.0k
    return ret;
3990
15.0k
}
3991
3992
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3993
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
3994
79.9k
        std::vector<std::string>* keys) {
3995
79.9k
    TEST_SYNC_POINT("InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts");
3996
79.9k
    if (out_storage_type) {
3997
79.9k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3998
79.9k
    }
3999
4000
    // Get delete bitmap storage info from FDB
4001
79.9k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4002
79.9k
    std::unique_ptr<Transaction> txn;
4003
79.9k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4004
79.9k
    if (err != TxnErrorCode::TXN_OK) {
4005
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4006
0
                .tag("instance_id", instance_id_)
4007
0
                .tag("tablet_id", tablet_id)
4008
0
                .tag("rowset_id", rowset_id)
4009
0
                .tag("err", err);
4010
0
        return -1;
4011
0
    }
4012
4013
79.9k
    ValueBuf dbm_val;
4014
79.9k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4015
79.9k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4016
        // No delete bitmap for this rowset, nothing to do
4017
15.1k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4018
15.1k
                .tag("instance_id", instance_id_)
4019
15.1k
                .tag("tablet_id", tablet_id)
4020
15.1k
                .tag("rowset_id", rowset_id);
4021
15.1k
        return 0;
4022
15.1k
    }
4023
64.8k
    if (err != TxnErrorCode::TXN_OK) {
4024
0
        LOG_WARNING("failed to get delete bitmap storage")
4025
0
                .tag("instance_id", instance_id_)
4026
0
                .tag("tablet_id", tablet_id)
4027
0
                .tag("rowset_id", rowset_id)
4028
0
                .tag("err", err);
4029
0
        return -1;
4030
0
    }
4031
4032
64.8k
    if (keys) {
4033
11.5k
        for (auto& key : dbm_val.keys()) {
4034
11.5k
            keys->push_back(std::move(key));
4035
11.5k
        }
4036
11.5k
    }
4037
4038
64.8k
    DeleteBitmapStoragePB storage;
4039
64.8k
    if (!dbm_val.to_pb(&storage)) {
4040
0
        LOG_WARNING("failed to parse delete bitmap storage")
4041
0
                .tag("instance_id", instance_id_)
4042
0
                .tag("tablet_id", tablet_id)
4043
0
                .tag("rowset_id", rowset_id);
4044
0
        return -1;
4045
0
    }
4046
4047
64.8k
    if (storage.store_in_fdb()) {
4048
1
        if (out_storage_type) {
4049
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4050
1
        }
4051
1
        return 0;
4052
1
    }
4053
4054
    // Check if delete bitmap is stored in standalone file.
4055
64.8k
    if (!storage.has_packed_slice_location() ||
4056
64.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4057
64.8k
        if (out_storage_type) {
4058
64.8k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4059
64.8k
        }
4060
64.8k
        return 0;
4061
64.8k
    }
4062
4063
10
    if (out_storage_type) {
4064
1
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4065
1
    }
4066
4067
10
    const auto& packed_loc = storage.packed_slice_location();
4068
10
    const std::string& packed_file_path = packed_loc.packed_file_path();
4069
4070
10
    LOG_INFO("decrementing delete bitmap packed file ref count")
4071
10
            .tag("instance_id", instance_id_)
4072
10
            .tag("tablet_id", tablet_id)
4073
10
            .tag("rowset_id", rowset_id)
4074
10
            .tag("packed_file_path", packed_file_path);
4075
4076
10
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4077
10
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4078
1
        std::unique_ptr<Transaction> update_txn;
4079
1
        err = txn_kv_->create_txn(&update_txn);
4080
1
        if (err != TxnErrorCode::TXN_OK) {
4081
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4082
0
                    .tag("instance_id", instance_id_)
4083
0
                    .tag("tablet_id", tablet_id)
4084
0
                    .tag("rowset_id", rowset_id)
4085
0
                    .tag("err", err);
4086
0
            return -1;
4087
0
        }
4088
4089
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4090
1
        std::string packed_val;
4091
1
        err = update_txn->get(packed_key, &packed_val);
4092
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4093
0
            LOG_WARNING("packed file info not found for delete bitmap")
4094
0
                    .tag("instance_id", instance_id_)
4095
0
                    .tag("tablet_id", tablet_id)
4096
0
                    .tag("rowset_id", rowset_id)
4097
0
                    .tag("packed_file_path", packed_file_path);
4098
0
            return 0;
4099
0
        }
4100
1
        if (err != TxnErrorCode::TXN_OK) {
4101
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4102
0
                    .tag("instance_id", instance_id_)
4103
0
                    .tag("tablet_id", tablet_id)
4104
0
                    .tag("rowset_id", rowset_id)
4105
0
                    .tag("packed_file_path", packed_file_path)
4106
0
                    .tag("err", err);
4107
0
            return -1;
4108
0
        }
4109
4110
1
        cloud::PackedFileInfoPB packed_info;
4111
1
        if (!packed_info.ParseFromString(packed_val)) {
4112
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4113
0
                    .tag("instance_id", instance_id_)
4114
0
                    .tag("tablet_id", tablet_id)
4115
0
                    .tag("rowset_id", rowset_id)
4116
0
                    .tag("packed_file_path", packed_file_path);
4117
0
            return -1;
4118
0
        }
4119
4120
        // Find and mark the small file entry as deleted
4121
        // Use tablet_id and rowset_id to match entry instead of path,
4122
        // because path format may vary with path_version (with or without shard prefix)
4123
1
        auto* entries = packed_info.mutable_slices();
4124
1
        bool found = false;
4125
1
        bool already_deleted = false;
4126
1
        for (auto& entry : *entries) {
4127
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4128
1
                if (!entry.deleted()) {
4129
1
                    entry.set_deleted(true);
4130
1
                    if (!entry.corrected()) {
4131
1
                        entry.set_corrected(true);
4132
1
                    }
4133
1
                } else {
4134
0
                    already_deleted = true;
4135
0
                }
4136
1
                found = true;
4137
1
                break;
4138
1
            }
4139
1
        }
4140
4141
1
        if (!found) {
4142
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4143
0
                    .tag("instance_id", instance_id_)
4144
0
                    .tag("tablet_id", tablet_id)
4145
0
                    .tag("rowset_id", rowset_id)
4146
0
                    .tag("packed_file_path", packed_file_path);
4147
0
            return 0;
4148
0
        }
4149
4150
1
        if (already_deleted) {
4151
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4152
0
                    .tag("instance_id", instance_id_)
4153
0
                    .tag("tablet_id", tablet_id)
4154
0
                    .tag("rowset_id", rowset_id)
4155
0
                    .tag("packed_file_path", packed_file_path);
4156
0
            return 0;
4157
0
        }
4158
4159
        // Calculate remaining files
4160
1
        int64_t left_file_count = 0;
4161
1
        int64_t left_file_bytes = 0;
4162
1
        for (const auto& entry : packed_info.slices()) {
4163
1
            if (!entry.deleted()) {
4164
0
                ++left_file_count;
4165
0
                left_file_bytes += entry.size();
4166
0
            }
4167
1
        }
4168
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4169
1
        packed_info.set_ref_cnt(left_file_count);
4170
4171
1
        if (left_file_count == 0) {
4172
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4173
1
        }
4174
4175
1
        std::string updated_val;
4176
1
        if (!packed_info.SerializeToString(&updated_val)) {
4177
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4178
0
                    .tag("instance_id", instance_id_)
4179
0
                    .tag("tablet_id", tablet_id)
4180
0
                    .tag("rowset_id", rowset_id)
4181
0
                    .tag("packed_file_path", packed_file_path);
4182
0
            return -1;
4183
0
        }
4184
4185
1
        update_txn->put(packed_key, updated_val);
4186
1
        err = update_txn->commit();
4187
1
        if (err == TxnErrorCode::TXN_OK) {
4188
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4189
1
                    .tag("instance_id", instance_id_)
4190
1
                    .tag("tablet_id", tablet_id)
4191
1
                    .tag("rowset_id", rowset_id)
4192
1
                    .tag("packed_file_path", packed_file_path)
4193
1
                    .tag("left_file_count", left_file_count);
4194
1
            if (left_file_count == 0) {
4195
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4196
0
                    return -1;
4197
0
                }
4198
1
            }
4199
1
            return 0;
4200
1
        }
4201
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4202
0
            if (attempt >= max_retry_times) {
4203
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4204
0
                        .tag("instance_id", instance_id_)
4205
0
                        .tag("tablet_id", tablet_id)
4206
0
                        .tag("rowset_id", rowset_id)
4207
0
                        .tag("packed_file_path", packed_file_path)
4208
0
                        .tag("attempt", attempt);
4209
0
                return -1;
4210
0
            }
4211
0
            sleep_for_packed_file_retry();
4212
0
            continue;
4213
0
        }
4214
4215
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4216
0
                .tag("instance_id", instance_id_)
4217
0
                .tag("tablet_id", tablet_id)
4218
0
                .tag("rowset_id", rowset_id)
4219
0
                .tag("packed_file_path", packed_file_path)
4220
0
                .tag("err", err);
4221
0
        return -1;
4222
0
    }
4223
4224
9
    return -1;
4225
10
}
4226
4227
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4228
                                                const std::string& packed_key,
4229
7.50k
                                                const cloud::PackedFileInfoPB& packed_info) {
4230
7.50k
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4231
0
        LOG_WARNING("packed file missing resource id when recycling")
4232
0
                .tag("instance_id", instance_id_)
4233
0
                .tag("packed_file_path", packed_file_path);
4234
0
        return -1;
4235
0
    }
4236
4237
7.50k
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4238
7.50k
    if (!accessor) {
4239
0
        LOG_WARNING("no accessor available to delete packed file")
4240
0
                .tag("instance_id", instance_id_)
4241
0
                .tag("packed_file_path", packed_file_path)
4242
0
                .tag("resource_id", packed_info.resource_id());
4243
0
        return -1;
4244
0
    }
4245
4246
7.50k
    int del_ret = accessor->delete_file(packed_file_path);
4247
7.50k
    if (del_ret != 0 && del_ret != 1) {
4248
0
        LOG_WARNING("failed to delete packed file")
4249
0
                .tag("instance_id", instance_id_)
4250
0
                .tag("packed_file_path", packed_file_path)
4251
0
                .tag("resource_id", resource_id)
4252
0
                .tag("ret", del_ret);
4253
0
        return -1;
4254
0
    }
4255
7.50k
    if (del_ret == 1) {
4256
0
        LOG_INFO("packed file already removed")
4257
0
                .tag("instance_id", instance_id_)
4258
0
                .tag("packed_file_path", packed_file_path)
4259
0
                .tag("resource_id", resource_id);
4260
7.50k
    } else {
4261
7.50k
        LOG_INFO("deleted packed file")
4262
7.50k
                .tag("instance_id", instance_id_)
4263
7.50k
                .tag("packed_file_path", packed_file_path)
4264
7.50k
                .tag("resource_id", resource_id);
4265
7.50k
    }
4266
4267
7.50k
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4268
7.50k
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4269
7.50k
        std::unique_ptr<Transaction> del_txn;
4270
7.50k
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4271
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4272
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4273
0
                    .tag("instance_id", instance_id_)
4274
0
                    .tag("packed_file_path", packed_file_path)
4275
0
                    .tag("attempt", attempt)
4276
0
                    .tag("err", err);
4277
0
            return -1;
4278
0
        }
4279
4280
7.50k
        std::string latest_val;
4281
7.50k
        err = del_txn->get(packed_key, &latest_val);
4282
7.50k
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4283
0
            return 0;
4284
0
        }
4285
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4286
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4287
0
                    .tag("instance_id", instance_id_)
4288
0
                    .tag("packed_file_path", packed_file_path)
4289
0
                    .tag("attempt", attempt)
4290
0
                    .tag("err", err);
4291
0
            return -1;
4292
0
        }
4293
4294
7.50k
        cloud::PackedFileInfoPB latest_info;
4295
7.50k
        if (!latest_info.ParseFromString(latest_val)) {
4296
0
            LOG_WARNING("failed to parse packed file info before removal")
4297
0
                    .tag("instance_id", instance_id_)
4298
0
                    .tag("packed_file_path", packed_file_path)
4299
0
                    .tag("attempt", attempt);
4300
0
            return -1;
4301
0
        }
4302
4303
7.50k
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4304
7.50k
              latest_info.ref_cnt() == 0)) {
4305
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4306
0
                    .tag("instance_id", instance_id_)
4307
0
                    .tag("packed_file_path", packed_file_path)
4308
0
                    .tag("attempt", attempt);
4309
0
            return 0;
4310
0
        }
4311
4312
7.50k
        del_txn->remove(packed_key);
4313
7.50k
        err = del_txn->commit();
4314
7.50k
        if (err == TxnErrorCode::TXN_OK) {
4315
7.50k
            LOG_INFO("removed packed file metadata")
4316
7.50k
                    .tag("instance_id", instance_id_)
4317
7.50k
                    .tag("packed_file_path", packed_file_path);
4318
7.50k
            return 0;
4319
7.50k
        }
4320
18.4E
        if (err == TxnErrorCode::TXN_CONFLICT) {
4321
0
            if (attempt >= max_retry_times) {
4322
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4323
0
                        .tag("instance_id", instance_id_)
4324
0
                        .tag("packed_file_path", packed_file_path)
4325
0
                        .tag("attempt", attempt);
4326
0
                return -1;
4327
0
            }
4328
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4329
0
                    .tag("instance_id", instance_id_)
4330
0
                    .tag("packed_file_path", packed_file_path)
4331
0
                    .tag("attempt", attempt);
4332
0
            sleep_for_packed_file_retry();
4333
0
            continue;
4334
0
        }
4335
18.4E
        LOG_WARNING("failed to remove packed file kv")
4336
18.4E
                .tag("instance_id", instance_id_)
4337
18.4E
                .tag("packed_file_path", packed_file_path)
4338
18.4E
                .tag("attempt", attempt)
4339
18.4E
                .tag("err", err);
4340
18.4E
        return -1;
4341
18.4E
    }
4342
18.4E
    return -1;
4343
7.50k
}
4344
4345
int InstanceRecycler::delete_rowset_data(
4346
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4347
        RecyclerMetricsContext& metrics_context,
4348
445
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4349
445
    int ret = 0;
4350
    // resource_id -> file_paths
4351
445
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4352
    // (resource_id, tablet_id, rowset_id)
4353
445
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4354
445
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4355
4356
106k
    for (const auto& [_, rs] : rowsets) {
4357
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4358
        // due to aborted schema change.
4359
106k
        if (is_formal_rowset) {
4360
53.1k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4361
                // Tablet has been recycled and this rowset has no packed slices, so file data
4362
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4363
                // slice info must still run to decrement packed file ref counts.
4364
0
                continue;
4365
0
            }
4366
53.1k
        }
4367
4368
106k
        int64_t num_segments = rs.num_segments();
4369
        // Check num_segments before accessor lookup, because empty rowsets
4370
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4371
        // set. Skipping them early avoids a spurious "no such resource id" error
4372
        // that marks the entire batch as failed and prevents txn_remove from
4373
        // cleaning up recycle KV keys.
4374
106k
        if (num_segments <= 0) {
4375
10.0k
            metrics_context.total_recycled_num++;
4376
10.0k
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4377
10.0k
            continue;
4378
10.0k
        }
4379
4380
96.4k
        auto it = accessor_map_.find(rs.resource_id());
4381
        // possible if the accessor is not initilized correctly
4382
96.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4383
2.00k
            LOG_WARNING("instance has no such resource id")
4384
2.00k
                    .tag("instance_id", instance_id_)
4385
2.00k
                    .tag("resource_id", rs.resource_id());
4386
2.00k
            ret = -1;
4387
2.00k
            continue;
4388
2.00k
        }
4389
4390
94.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4391
94.4k
        const auto& rowset_id = rs.rowset_id_v2();
4392
94.4k
        int64_t tablet_id = rs.tablet_id();
4393
94.4k
        LOG_INFO("recycle rowset merge index size")
4394
94.4k
                .tag("instance_id", instance_id_)
4395
94.4k
                .tag("tablet_id", tablet_id)
4396
94.4k
                .tag("rowset_id", rowset_id)
4397
94.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4398
94.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4399
0
            ret = -1;
4400
0
            continue;
4401
0
        }
4402
4403
94.4k
        int should_delete_dbm = may_have_versioned_delete_bitmap(rs.partition_id(), tablet_id);
4404
94.4k
        if (should_delete_dbm == 1) {
4405
73.4k
            DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4406
73.4k
            std::vector<std::string> rowset_dbm_keys;
4407
73.4k
            if (decrement_delete_bitmap_packed_file_ref_counts(
4408
73.4k
                        tablet_id, rowset_id, &delete_bitmap_storage_type,
4409
73.4k
                        delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4410
0
                LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4411
0
                        .tag("instance_id", instance_id_)
4412
0
                        .tag("tablet_id", tablet_id)
4413
0
                        .tag("rowset_id", rowset_id)
4414
0
                        .tag("task_type", metrics_context.operation_type);
4415
0
                ret = -1;
4416
0
                continue;
4417
0
            }
4418
73.4k
            if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4419
11.5k
                delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4420
11.5k
            }
4421
73.4k
            if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4422
61.5k
                file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4423
61.5k
            }
4424
73.4k
        } else if (should_delete_dbm != 0) {
4425
0
            ret = -1;
4426
0
            continue;
4427
0
        }
4428
4429
        // Process inverted indexes
4430
94.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4431
        // default format as v1.
4432
94.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4433
94.4k
                                                            ? rs.inverted_index_storage_format()
4434
94.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4435
94.4k
        int inverted_index_get_ret = 0;
4436
94.4k
        if (rs.has_tablet_schema()) {
4437
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4438
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4439
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4440
53.5k
                }
4441
53.5k
            }
4442
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4443
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4444
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4445
26.5k
            }
4446
67.5k
        } else {
4447
67.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4448
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4449
0
                                "instance_id="
4450
0
                             << instance_id_ << " tablet_id=" << tablet_id
4451
0
                             << " rowset_id=" << rowset_id;
4452
0
                ret = -1;
4453
0
                continue;
4454
0
            }
4455
67.5k
            InvertedIndexInfo index_info;
4456
67.5k
            inverted_index_get_ret =
4457
67.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4458
67.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4459
67.5k
                                     &inverted_index_get_ret);
4460
67.5k
            if (inverted_index_get_ret == 0) {
4461
62.0k
                if (!rs.has_inverted_index_storage_format()) {
4462
62.0k
                    index_format = index_info.first;
4463
62.0k
                }
4464
62.0k
                index_ids = index_info.second;
4465
62.0k
            } else if (inverted_index_get_ret == 1) {
4466
                // 1. Schema kv not found means tablet has been recycled
4467
                // Maybe some tablet recycle failed by some bugs
4468
                // We need to delete again to double check
4469
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4470
                // because we are uncertain about the inverted index information.
4471
                // If there are inverted indexes, some data might not be deleted,
4472
                // but this is acceptable as we have made our best effort to delete the data.
4473
5.49k
                LOG_INFO(
4474
5.49k
                        "delete rowset data schema kv not found, need to delete again to "
4475
5.49k
                        "double "
4476
5.49k
                        "check")
4477
5.49k
                        .tag("instance_id", instance_id_)
4478
5.49k
                        .tag("tablet_id", tablet_id)
4479
5.49k
                        .tag("rowset", rs.ShortDebugString());
4480
                // Currently index_ids is guaranteed to be empty,
4481
                // but we clear it again here as a safeguard against future code changes
4482
                // that might cause index_ids to no longer be empty
4483
5.49k
                index_format = InvertedIndexStorageFormatPB::V2;
4484
5.49k
                index_ids.clear();
4485
5.49k
            } else {
4486
7
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4487
7
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4488
7
                ret = -1;
4489
7
                continue;
4490
7
            }
4491
67.5k
        }
4492
94.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE && !is_formal_rowset) {
4493
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4494
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4495
6
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4496
6
            continue;
4497
6
        }
4498
405k
        for (int64_t i = 0; i < num_segments; ++i) {
4499
310k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4500
310k
                                             &file_paths);
4501
310k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4502
572k
                for (const auto& index_id : index_ids) {
4503
572k
                    add_file_to_delete_if_not_packed(
4504
572k
                            rs,
4505
572k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4506
572k
                                                   index_id.second),
4507
572k
                            &file_paths);
4508
572k
                }
4509
303k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4510
                // try to recycle inverted index v2 when get_ret == 1
4511
                // we treat schema not found as if it has a v2 format inverted index
4512
                // to reduce chance of data leakage
4513
7.49k
                if (inverted_index_get_ret == 1) {
4514
7.49k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4515
7.49k
                            .tag("instance_id", instance_id_)
4516
7.49k
                            .tag("inverted index v2 path",
4517
7.49k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4518
7.49k
                }
4519
7.49k
                add_file_to_delete_if_not_packed(
4520
7.49k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4521
7.49k
            }
4522
310k
        }
4523
94.4k
    }
4524
4525
445
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4526
445
                                                 "delete_rowset_data",
4527
445
                                                 [](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
4527
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
4527
204
                                                 [](const int& ret) { return ret != 0; });
4528
445
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4529
204
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4530
204
            DCHECK(accessor_map_.count(*rid))
4531
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4532
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4533
204
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4534
204
                                     &accessor_map_);
4535
204
            if (!accessor_map_.contains(*rid)) {
4536
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4537
0
                        .tag("resource_id", resource_id)
4538
0
                        .tag("instance_id", instance_id_);
4539
0
                return -1;
4540
0
            }
4541
204
            auto& accessor = accessor_map_[*rid];
4542
204
            int ret = accessor->delete_files(*paths);
4543
204
            if (!ret) {
4544
                // deduplication of different files with the same rowset id
4545
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4546
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4547
204
                std::set<std::string> deleted_rowset_id;
4548
4549
204
                std::for_each(paths->begin(), paths->end(),
4550
204
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4551
922k
                               this](const std::string& path) {
4552
922k
                                  std::vector<std::string> str;
4553
922k
                                  butil::SplitString(path, '/', &str);
4554
922k
                                  std::string rowset_id;
4555
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4556
920k
                                      rowset_id = str.back().substr(0, pos);
4557
920k
                                  } else {
4558
2.18k
                                      if (path.find("packed_file/") != std::string::npos) {
4559
0
                                          return; // packed files do not have rowset_id encoded
4560
0
                                      }
4561
2.18k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4562
2.18k
                                      return;
4563
2.18k
                                  }
4564
920k
                                  auto rs_meta = rowsets.find(rowset_id);
4565
920k
                                  if (rs_meta != rowsets.end() &&
4566
920k
                                      !deleted_rowset_id.contains(rowset_id)) {
4567
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4568
84.4k
                                      metrics_context.total_recycled_data_size +=
4569
84.4k
                                              rs_meta->second.total_disk_size();
4570
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4571
84.4k
                                              rs_meta->second.num_segments();
4572
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4573
84.4k
                                              rs_meta->second.total_disk_size();
4574
84.4k
                                      metrics_context.total_recycled_num++;
4575
84.4k
                                  }
4576
920k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4551
7
                               this](const std::string& path) {
4552
7
                                  std::vector<std::string> str;
4553
7
                                  butil::SplitString(path, '/', &str);
4554
7
                                  std::string rowset_id;
4555
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4556
7
                                      rowset_id = str.back().substr(0, pos);
4557
7
                                  } else {
4558
0
                                      if (path.find("packed_file/") != std::string::npos) {
4559
0
                                          return; // packed files do not have rowset_id encoded
4560
0
                                      }
4561
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4562
0
                                      return;
4563
0
                                  }
4564
7
                                  auto rs_meta = rowsets.find(rowset_id);
4565
7
                                  if (rs_meta != rowsets.end() &&
4566
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4567
7
                                      deleted_rowset_id.emplace(rowset_id);
4568
7
                                      metrics_context.total_recycled_data_size +=
4569
7
                                              rs_meta->second.total_disk_size();
4570
7
                                      segment_metrics_context_.total_recycled_num +=
4571
7
                                              rs_meta->second.num_segments();
4572
7
                                      segment_metrics_context_.total_recycled_data_size +=
4573
7
                                              rs_meta->second.total_disk_size();
4574
7
                                      metrics_context.total_recycled_num++;
4575
7
                                  }
4576
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
4551
922k
                               this](const std::string& path) {
4552
922k
                                  std::vector<std::string> str;
4553
922k
                                  butil::SplitString(path, '/', &str);
4554
922k
                                  std::string rowset_id;
4555
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4556
920k
                                      rowset_id = str.back().substr(0, pos);
4557
920k
                                  } else {
4558
2.18k
                                      if (path.find("packed_file/") != std::string::npos) {
4559
0
                                          return; // packed files do not have rowset_id encoded
4560
0
                                      }
4561
2.18k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4562
2.18k
                                      return;
4563
2.18k
                                  }
4564
920k
                                  auto rs_meta = rowsets.find(rowset_id);
4565
920k
                                  if (rs_meta != rowsets.end() &&
4566
920k
                                      !deleted_rowset_id.contains(rowset_id)) {
4567
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4568
84.4k
                                      metrics_context.total_recycled_data_size +=
4569
84.4k
                                              rs_meta->second.total_disk_size();
4570
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4571
84.4k
                                              rs_meta->second.num_segments();
4572
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4573
84.4k
                                              rs_meta->second.total_disk_size();
4574
84.4k
                                      metrics_context.total_recycled_num++;
4575
84.4k
                                  }
4576
920k
                              });
4577
204
            }
4578
204
            return ret;
4579
204
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4529
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4530
6
            DCHECK(accessor_map_.count(*rid))
4531
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4532
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4533
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4534
6
                                     &accessor_map_);
4535
6
            if (!accessor_map_.contains(*rid)) {
4536
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4537
0
                        .tag("resource_id", resource_id)
4538
0
                        .tag("instance_id", instance_id_);
4539
0
                return -1;
4540
0
            }
4541
6
            auto& accessor = accessor_map_[*rid];
4542
6
            int ret = accessor->delete_files(*paths);
4543
6
            if (!ret) {
4544
                // deduplication of different files with the same rowset id
4545
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4546
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4547
6
                std::set<std::string> deleted_rowset_id;
4548
4549
6
                std::for_each(paths->begin(), paths->end(),
4550
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4551
6
                               this](const std::string& path) {
4552
6
                                  std::vector<std::string> str;
4553
6
                                  butil::SplitString(path, '/', &str);
4554
6
                                  std::string rowset_id;
4555
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4556
6
                                      rowset_id = str.back().substr(0, pos);
4557
6
                                  } else {
4558
6
                                      if (path.find("packed_file/") != std::string::npos) {
4559
6
                                          return; // packed files do not have rowset_id encoded
4560
6
                                      }
4561
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4562
6
                                      return;
4563
6
                                  }
4564
6
                                  auto rs_meta = rowsets.find(rowset_id);
4565
6
                                  if (rs_meta != rowsets.end() &&
4566
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4567
6
                                      deleted_rowset_id.emplace(rowset_id);
4568
6
                                      metrics_context.total_recycled_data_size +=
4569
6
                                              rs_meta->second.total_disk_size();
4570
6
                                      segment_metrics_context_.total_recycled_num +=
4571
6
                                              rs_meta->second.num_segments();
4572
6
                                      segment_metrics_context_.total_recycled_data_size +=
4573
6
                                              rs_meta->second.total_disk_size();
4574
6
                                      metrics_context.total_recycled_num++;
4575
6
                                  }
4576
6
                              });
4577
6
            }
4578
6
            return ret;
4579
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4529
198
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4530
198
            DCHECK(accessor_map_.count(*rid))
4531
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4532
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4533
198
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4534
198
                                     &accessor_map_);
4535
198
            if (!accessor_map_.contains(*rid)) {
4536
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4537
0
                        .tag("resource_id", resource_id)
4538
0
                        .tag("instance_id", instance_id_);
4539
0
                return -1;
4540
0
            }
4541
198
            auto& accessor = accessor_map_[*rid];
4542
198
            int ret = accessor->delete_files(*paths);
4543
198
            if (!ret) {
4544
                // deduplication of different files with the same rowset id
4545
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4546
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4547
198
                std::set<std::string> deleted_rowset_id;
4548
4549
198
                std::for_each(paths->begin(), paths->end(),
4550
198
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4551
198
                               this](const std::string& path) {
4552
198
                                  std::vector<std::string> str;
4553
198
                                  butil::SplitString(path, '/', &str);
4554
198
                                  std::string rowset_id;
4555
198
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4556
198
                                      rowset_id = str.back().substr(0, pos);
4557
198
                                  } else {
4558
198
                                      if (path.find("packed_file/") != std::string::npos) {
4559
198
                                          return; // packed files do not have rowset_id encoded
4560
198
                                      }
4561
198
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4562
198
                                      return;
4563
198
                                  }
4564
198
                                  auto rs_meta = rowsets.find(rowset_id);
4565
198
                                  if (rs_meta != rowsets.end() &&
4566
198
                                      !deleted_rowset_id.contains(rowset_id)) {
4567
198
                                      deleted_rowset_id.emplace(rowset_id);
4568
198
                                      metrics_context.total_recycled_data_size +=
4569
198
                                              rs_meta->second.total_disk_size();
4570
198
                                      segment_metrics_context_.total_recycled_num +=
4571
198
                                              rs_meta->second.num_segments();
4572
198
                                      segment_metrics_context_.total_recycled_data_size +=
4573
198
                                              rs_meta->second.total_disk_size();
4574
198
                                      metrics_context.total_recycled_num++;
4575
198
                                  }
4576
198
                              });
4577
198
            }
4578
198
            return ret;
4579
198
        });
4580
204
    }
4581
445
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4582
6
        LOG_INFO(
4583
6
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4584
6
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4585
6
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4586
6
        concurrent_delete_executor.add([&]() -> int {
4587
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4588
6
            if (!ret) {
4589
6
                auto rs = rowsets.at(rowset_id);
4590
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4591
6
                metrics_context.total_recycled_num++;
4592
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4593
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4594
6
            }
4595
6
            return ret;
4596
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
4586
6
        concurrent_delete_executor.add([&]() -> int {
4587
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4588
6
            if (!ret) {
4589
6
                auto rs = rowsets.at(rowset_id);
4590
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4591
6
                metrics_context.total_recycled_num++;
4592
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4593
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4594
6
            }
4595
6
            return ret;
4596
6
        });
4597
6
    }
4598
4599
445
    bool finished = true;
4600
445
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4601
445
    for (int r : rets) {
4602
210
        if (r != 0) {
4603
0
            ret = -1;
4604
0
            break;
4605
0
        }
4606
210
    }
4607
445
    ret = finished ? ret : -1;
4608
445
    return ret;
4609
445
}
4610
4611
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4612
43.5k
                                         const std::string& rowset_id) {
4613
43.5k
    auto it = accessor_map_.find(resource_id);
4614
43.5k
    if (it == accessor_map_.end()) {
4615
400
        LOG_WARNING("instance has no such resource id")
4616
400
                .tag("instance_id", instance_id_)
4617
400
                .tag("resource_id", resource_id)
4618
400
                .tag("tablet_id", tablet_id)
4619
400
                .tag("rowset_id", rowset_id);
4620
400
        return -1;
4621
400
    }
4622
43.1k
    auto& accessor = it->second;
4623
43.1k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4624
43.5k
}
4625
4626
206k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4627
206k
    std::lock_guard lock(recycled_tablets_mtx_);
4628
206k
    return recycled_tablets_.contains(tablet_id);
4629
206k
}
4630
4631
193k
int InstanceRecycler::may_have_versioned_delete_bitmap(int64_t partition_id, int64_t tablet_id) {
4632
193k
    bool is_mow = true;
4633
193k
    if (partition_id != -1) {
4634
183k
        std::lock_guard lock(partition_mow_cache_mutex);
4635
183k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4636
            // cache hit
4637
40.0k
            is_mow = it->second;
4638
40.0k
            return is_mow ? 1 : 0;
4639
40.0k
        }
4640
183k
    }
4641
4642
153k
    TabletIndexPB tablet_index;
4643
153k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4644
153k
    if (ret == 1) {
4645
        // maybe recycled
4646
150k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4647
150k
    }
4648
2.58k
    if (ret != 0) {
4649
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4650
0
                     << ", tablet_id=" << tablet_id;
4651
0
        return ret;
4652
0
    }
4653
4654
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4655
    // obtaining its partition ID from the tablet index.
4656
2.58k
    if (partition_id == -1) {
4657
0
        partition_id = tablet_index.partition_id();
4658
0
        std::lock_guard lock(partition_mow_cache_mutex);
4659
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4660
0
            is_mow = it->second;
4661
0
            return is_mow ? 1 : 0;
4662
0
        }
4663
0
    }
4664
4665
2.58k
    std::string tablet_meta_key =
4666
2.58k
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4667
2.58k
                             partition_id, tablet_id});
4668
2.58k
    std::string tablet_meta_value;
4669
2.58k
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4670
2.58k
    if (ret == 1) {
4671
        // maybe recycled
4672
2.56k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4673
2.56k
    }
4674
23
    if (ret != 0) {
4675
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4676
0
                     << ", tablet_id=" << tablet_id;
4677
0
        return ret;
4678
0
    }
4679
4680
23
    TabletMetaCloudPB tablet_meta;
4681
23
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4682
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4683
0
                     << ", tablet_id=" << tablet_id;
4684
0
        return -1;
4685
0
    }
4686
23
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4687
23
    std::lock_guard lock(partition_mow_cache_mutex);
4688
23
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4689
23
    return it->second ? 1 : 0;
4690
23
}
4691
4692
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4693
92.4k
                                                         const std::string& rowset_id) {
4694
92.4k
    int ret = may_have_versioned_delete_bitmap(partition_id, tablet_id);
4695
92.4k
    if (ret <= 0) {
4696
1.00k
        return ret;
4697
1.00k
    }
4698
4699
91.4k
    std::string dbm_start_key =
4700
91.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4701
91.4k
    std::string dbm_end_key = dbm_start_key;
4702
91.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4703
91.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4704
91.4k
    if (ret != 0) {
4705
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4706
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4707
0
                     << " rowset_id=" << rowset_id;
4708
0
    }
4709
91.4k
    return ret;
4710
92.4k
}
4711
4712
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4713
51.2k
    std::string delete_bitmap_start =
4714
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4715
51.2k
    std::string delete_bitmap_end =
4716
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4717
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4718
51.2k
    if (ret != 0) {
4719
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4720
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4721
0
    }
4722
51.2k
    return ret;
4723
51.2k
}
4724
4725
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4726
4
    if (key.empty()) {
4727
0
        return false;
4728
0
    }
4729
4
    std::string_view key_view = key;
4730
4
    key_view.remove_prefix(1); // remove keyspace prefix
4731
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4732
4
    if (decode_key(&key_view, &decoded) != 0) {
4733
0
        return false;
4734
0
    }
4735
4
    if (decoded.size() < 4) {
4736
0
        return false;
4737
0
    }
4738
4
    try {
4739
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4740
4
    } catch (const std::bad_variant_access&) {
4741
0
        return false;
4742
0
    }
4743
4
    return true;
4744
4
}
4745
4746
14
int InstanceRecycler::recycle_packed_files() {
4747
14
    const std::string task_name = "recycle_packed_files";
4748
14
    auto start_tp = steady_clock::now();
4749
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4750
14
    int ret = 0;
4751
14
    PackedFileRecycleStats stats;
4752
4753
14
    register_recycle_task(task_name, start_time);
4754
14
    DORIS_CLOUD_DEFER {
4755
14
        unregister_recycle_task(task_name);
4756
14
        int64_t cost =
4757
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4758
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4759
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4760
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4761
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4762
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4763
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4764
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4765
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4766
14
                                                             stats.bytes_object_deleted);
4767
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4768
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4769
14
                .tag("instance_id", instance_id_)
4770
14
                .tag("num_scanned", stats.num_scanned)
4771
14
                .tag("num_corrected", stats.num_corrected)
4772
14
                .tag("num_deleted", stats.num_deleted)
4773
14
                .tag("num_failed", stats.num_failed)
4774
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4775
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4776
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4777
14
                .tag("bytes_deleted", stats.bytes_deleted)
4778
14
                .tag("ret", ret);
4779
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4754
14
    DORIS_CLOUD_DEFER {
4755
14
        unregister_recycle_task(task_name);
4756
14
        int64_t cost =
4757
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4758
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4759
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4760
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4761
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4762
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4763
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4764
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4765
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4766
14
                                                             stats.bytes_object_deleted);
4767
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4768
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4769
14
                .tag("instance_id", instance_id_)
4770
14
                .tag("num_scanned", stats.num_scanned)
4771
14
                .tag("num_corrected", stats.num_corrected)
4772
14
                .tag("num_deleted", stats.num_deleted)
4773
14
                .tag("num_failed", stats.num_failed)
4774
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4775
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4776
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4777
14
                .tag("bytes_deleted", stats.bytes_deleted)
4778
14
                .tag("ret", ret);
4779
14
    };
4780
4781
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4782
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4783
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4784
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
4781
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4782
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4783
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4784
4
    };
4785
4786
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4787
4788
14
    std::string begin = packed_file_key({instance_id_, ""});
4789
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4790
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4791
0
        ret = -1;
4792
0
    }
4793
4794
14
    return ret;
4795
14
}
4796
4797
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4798
                                                  RecyclerMetricsContext& metrics_context,
4799
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4800
0
    std::string tablet_key_begin, tablet_key_end;
4801
4802
0
    if (partition_id > 0) {
4803
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4804
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4805
0
    } else {
4806
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4807
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4808
0
    }
4809
    // for calculate the total num or bytes of recyled objects
4810
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4811
0
                                                          std::string_view v) -> int {
4812
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4813
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4814
0
            return 0;
4815
0
        }
4816
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4817
4818
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4819
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4820
0
            return 0;
4821
0
        }
4822
4823
0
        if (!is_empty_tablet) {
4824
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4825
0
                return 0;
4826
0
            }
4827
0
            tablet_metrics_context_.total_need_recycle_num++;
4828
0
        }
4829
0
        return 0;
4830
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_
4831
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4832
0
    metrics_context.report(true);
4833
0
    tablet_metrics_context_.report(true);
4834
0
    segment_metrics_context_.report(true);
4835
0
    return ret;
4836
0
}
4837
4838
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4839
0
                                                 RecyclerMetricsContext& metrics_context) {
4840
0
    int ret = 0;
4841
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4842
0
    std::unique_ptr<Transaction> txn;
4843
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4844
0
        LOG_WARNING("failed to recycle tablet ")
4845
0
                .tag("tablet id", tablet_id)
4846
0
                .tag("instance_id", instance_id_)
4847
0
                .tag("reason", "failed to create txn");
4848
0
        ret = -1;
4849
0
    }
4850
0
    GetRowsetResponse resp;
4851
0
    std::string msg;
4852
0
    MetaServiceCode code = MetaServiceCode::OK;
4853
    // get rowsets in tablet
4854
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4855
0
                        tablet_id, code, msg, &resp);
4856
0
    if (code != MetaServiceCode::OK) {
4857
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4858
0
                .tag("tablet id", tablet_id)
4859
0
                .tag("msg", msg)
4860
0
                .tag("code", code)
4861
0
                .tag("instance id", instance_id_);
4862
0
        ret = -1;
4863
0
    }
4864
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4865
        /*
4866
        * For compatibility, we skip the loop for [0-1] here.
4867
        * The purpose of this loop is to delete object files,
4868
        * and since [0-1] only has meta and doesn't have object files,
4869
        * skipping it doesn't affect system correctness.
4870
        *
4871
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4872
        * would return error -1 directly, causing the recycle operation to fail.
4873
        *
4874
        * [0-1] doesn't have resource id is a bug.
4875
        * In the future, we will fix this problem, after that,
4876
        * we can remove this if statement.
4877
        *
4878
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4879
        */
4880
4881
0
        if (rs_meta.end_version() == 1) {
4882
            // Assert that [0-1] has no resource_id to make sure
4883
            // this if statement will not be forgetted to remove
4884
            // when the resource id bug is fixed
4885
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4886
0
            continue;
4887
0
        }
4888
0
        if (!rs_meta.has_resource_id()) {
4889
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4890
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4891
0
                    .tag("instance_id", instance_id_)
4892
0
                    .tag("tablet_id", tablet_id);
4893
0
            continue;
4894
0
        }
4895
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4896
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4897
        // possible if the accessor is not initilized correctly
4898
0
        if (it == accessor_map_.end()) [[unlikely]] {
4899
0
            LOG_WARNING(
4900
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4901
0
                    "recycle process")
4902
0
                    .tag("tablet id", tablet_id)
4903
0
                    .tag("instance_id", instance_id_)
4904
0
                    .tag("resource_id", rs_meta.resource_id())
4905
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4906
0
            continue;
4907
0
        }
4908
4909
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4910
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4911
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4912
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4913
0
    }
4914
0
    return ret;
4915
0
}
4916
4917
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4918
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4919
4.26k
            .tag("instance_id", instance_id_)
4920
4.26k
            .tag("tablet_id", tablet_id);
4921
4922
4.26k
    if (should_recycle_versioned_keys()) {
4923
16
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4924
16
        if (ret != 0) {
4925
0
            return ret;
4926
0
        }
4927
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4928
        // during the recycle_versioned_tablet process.
4929
        //
4930
        // .. And remove restore job rowsets of this tablet too
4931
16
    }
4932
4933
4.26k
    int ret = 0;
4934
4.26k
    auto start_time = steady_clock::now();
4935
4936
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4937
4938
    // collect resource ids
4939
262
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4940
262
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4941
262
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4942
262
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4943
262
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4944
262
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4945
4946
262
    std::set<std::string> resource_ids;
4947
262
    int64_t recycle_rowsets_number = 0;
4948
262
    int64_t recycle_segments_number = 0;
4949
262
    int64_t recycle_rowsets_data_size = 0;
4950
262
    int64_t recycle_rowsets_index_size = 0;
4951
262
    int64_t recycle_restore_job_rowsets_number = 0;
4952
262
    int64_t recycle_restore_job_segments_number = 0;
4953
262
    int64_t recycle_restore_job_rowsets_data_size = 0;
4954
262
    int64_t recycle_restore_job_rowsets_index_size = 0;
4955
262
    int64_t max_rowset_version = 0;
4956
262
    int64_t min_rowset_creation_time = INT64_MAX;
4957
262
    int64_t max_rowset_creation_time = 0;
4958
262
    int64_t min_rowset_expiration_time = INT64_MAX;
4959
262
    int64_t max_rowset_expiration_time = 0;
4960
4961
262
    DORIS_CLOUD_DEFER {
4962
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4963
262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4964
262
                .tag("instance_id", instance_id_)
4965
262
                .tag("tablet_id", tablet_id)
4966
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4967
262
                .tag("recycle segments number", recycle_segments_number)
4968
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4969
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4970
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4971
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4972
262
                .tag("all restore job rowsets recycle data size",
4973
262
                     recycle_restore_job_rowsets_data_size)
4974
262
                .tag("all restore job rowsets recycle index size",
4975
262
                     recycle_restore_job_rowsets_index_size)
4976
262
                .tag("max rowset version", max_rowset_version)
4977
262
                .tag("min rowset creation time", min_rowset_creation_time)
4978
262
                .tag("max rowset creation time", max_rowset_creation_time)
4979
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4980
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4981
262
                .tag("task type", metrics_context.operation_type)
4982
262
                .tag("ret", ret);
4983
262
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4961
262
    DORIS_CLOUD_DEFER {
4962
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4963
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4964
262
                .tag("instance_id", instance_id_)
4965
262
                .tag("tablet_id", tablet_id)
4966
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4967
262
                .tag("recycle segments number", recycle_segments_number)
4968
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4969
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4970
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4971
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4972
262
                .tag("all restore job rowsets recycle data size",
4973
262
                     recycle_restore_job_rowsets_data_size)
4974
262
                .tag("all restore job rowsets recycle index size",
4975
262
                     recycle_restore_job_rowsets_index_size)
4976
262
                .tag("max rowset version", max_rowset_version)
4977
262
                .tag("min rowset creation time", min_rowset_creation_time)
4978
262
                .tag("max rowset creation time", max_rowset_creation_time)
4979
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4980
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4981
262
                .tag("task type", metrics_context.operation_type)
4982
262
                .tag("ret", ret);
4983
262
    };
4984
4985
262
    std::unique_ptr<Transaction> txn;
4986
262
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4987
0
        LOG_WARNING("failed to recycle tablet ")
4988
0
                .tag("tablet id", tablet_id)
4989
0
                .tag("instance_id", instance_id_)
4990
0
                .tag("reason", "failed to create txn");
4991
0
        ret = -1;
4992
0
    }
4993
262
    GetRowsetResponse resp;
4994
262
    std::string msg;
4995
262
    MetaServiceCode code = MetaServiceCode::OK;
4996
    // get rowsets in tablet
4997
262
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4998
262
                        tablet_id, code, msg, &resp);
4999
262
    if (code != MetaServiceCode::OK) {
5000
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5001
0
                .tag("tablet id", tablet_id)
5002
0
                .tag("msg", msg)
5003
0
                .tag("code", code)
5004
0
                .tag("instance id", instance_id_);
5005
0
        ret = -1;
5006
0
    }
5007
262
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5008
5009
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5010
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5011
3
            if (rs_meta.num_segments() <= 0) {
5012
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5013
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5014
2
                        .tag("instance_id", instance_id_)
5015
2
                        .tag("tablet_id", tablet_id);
5016
2
                recycle_rowsets_number += 1;
5017
2
                continue;
5018
2
            }
5019
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5020
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5021
1
                    .tag("instance_id", instance_id_)
5022
1
                    .tag("tablet_id", tablet_id);
5023
1
            return -1;
5024
3
        }
5025
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5026
0
                << "rs_meta" << rs_meta.ShortDebugString();
5027
2.55k
        auto it = accessor_map_.find(rs_meta.resource_id());
5028
        // possible if the accessor is not initilized correctly
5029
2.55k
        if (it == accessor_map_.end()) [[unlikely]] {
5030
1
            LOG_WARNING(
5031
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5032
1
                    "recycle process")
5033
1
                    .tag("tablet id", tablet_id)
5034
1
                    .tag("instance_id", instance_id_)
5035
1
                    .tag("resource_id", rs_meta.resource_id())
5036
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5037
1
            return -1;
5038
1
        }
5039
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5040
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5041
0
                    .tag("instance_id", instance_id_)
5042
0
                    .tag("tablet_id", tablet_id)
5043
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5044
0
            return -1;
5045
0
        }
5046
2.54k
        int should_delete_dbm = may_have_versioned_delete_bitmap(rs_meta.partition_id(), tablet_id);
5047
2.54k
        if (should_delete_dbm == 1) {
5048
2.54k
            DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
5049
2.54k
            std::vector<std::string> rowset_dbm_keys;
5050
2.54k
            if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5051
2.54k
                                                               &delete_bitmap_storage_type,
5052
2.54k
                                                               nullptr) != 0) {
5053
0
                LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5054
0
                        .tag("instance_id", instance_id_)
5055
0
                        .tag("tablet_id", tablet_id)
5056
0
                        .tag("rowset_id", rs_meta.rowset_id_v2())
5057
0
                        .tag("task_type", metrics_context.operation_type);
5058
0
                return -1;
5059
0
            }
5060
2.54k
        } else if (should_delete_dbm != 0) {
5061
0
            return -1;
5062
0
        }
5063
2.54k
        recycle_rowsets_number += 1;
5064
2.54k
        recycle_segments_number += rs_meta.num_segments();
5065
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5066
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5067
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5068
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5069
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5070
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5071
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5072
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5073
2.54k
    }
5074
5075
    // get restore job rowset in tablet
5076
260
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5077
260
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5078
260
    if (code != MetaServiceCode::OK) {
5079
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5080
0
                .tag("tablet id", tablet_id)
5081
0
                .tag("msg", msg)
5082
0
                .tag("code", code)
5083
0
                .tag("instance id", instance_id_);
5084
0
        return -1;
5085
0
    }
5086
5087
260
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5088
0
        if (!rs_meta.has_resource_id()) {
5089
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5090
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5091
0
                    .tag("instance_id", instance_id_)
5092
0
                    .tag("tablet_id", tablet_id);
5093
0
            return -1;
5094
0
        }
5095
5096
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5097
        // possible if the accessor is not initilized correctly
5098
0
        if (it == accessor_map_.end()) [[unlikely]] {
5099
0
            LOG_WARNING(
5100
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5101
0
                    "recycle process")
5102
0
                    .tag("tablet id", tablet_id)
5103
0
                    .tag("instance_id", instance_id_)
5104
0
                    .tag("resource_id", rs_meta.resource_id())
5105
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5106
0
            return -1;
5107
0
        }
5108
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5109
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5110
0
                    .tag("instance_id", instance_id_)
5111
0
                    .tag("tablet_id", tablet_id)
5112
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5113
0
            return -1;
5114
0
        }
5115
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5116
0
                                                           nullptr) != 0) {
5117
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5118
0
                    .tag("instance_id", instance_id_)
5119
0
                    .tag("tablet_id", tablet_id)
5120
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5121
0
            return -1;
5122
0
        }
5123
0
        recycle_restore_job_rowsets_number += 1;
5124
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5125
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5126
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5127
0
        resource_ids.emplace(rs_meta.resource_id());
5128
0
    }
5129
5130
260
    LOG_INFO("recycle tablet start to delete object")
5131
260
            .tag("instance id", instance_id_)
5132
260
            .tag("tablet id", tablet_id)
5133
260
            .tag("recycle tablet resource ids are",
5134
260
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5135
260
                                 [](std::string rs_id, const auto& it) {
5136
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5137
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
5135
217
                                 [](std::string rs_id, const auto& it) {
5136
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5137
217
                                 }));
5138
5139
260
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5140
260
            _thread_pool_group.s3_producer_pool,
5141
260
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5142
260
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
5142
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5143
5144
    // delete all rowset data in this tablet
5145
    // ATTN: there may be data leak if not all accessor initilized successfully
5146
    //       partial data deleted if the tablet is stored cross-storage vault
5147
    //       vault id is not attached to TabletMeta...
5148
260
    for (const auto& resource_id : resource_ids) {
5149
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5150
217
        concurrent_delete_executor.add(
5151
217
                [&, rs_id = resource_id,
5152
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5153
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5154
217
                    if (res != 0) {
5155
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5156
3
                                     << " path=" << accessor_ptr->uri()
5157
3
                                     << " task type=" << metrics_context.operation_type;
5158
3
                        return std::make_pair(-1, rs_id);
5159
3
                    }
5160
214
                    return std::make_pair(0, rs_id);
5161
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5152
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5153
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5154
217
                    if (res != 0) {
5155
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5156
3
                                     << " path=" << accessor_ptr->uri()
5157
3
                                     << " task type=" << metrics_context.operation_type;
5158
3
                        return std::make_pair(-1, rs_id);
5159
3
                    }
5160
214
                    return std::make_pair(0, rs_id);
5161
217
                });
5162
217
    }
5163
5164
260
    bool finished = true;
5165
260
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5166
260
    for (auto& r : rets) {
5167
217
        if (r.first != 0) {
5168
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5169
3
            ret = -1;
5170
3
        }
5171
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5172
217
    }
5173
260
    ret = finished ? ret : -1;
5174
5175
260
    if (ret != 0) { // failed recycle tablet data
5176
3
        LOG_WARNING("ret!=0")
5177
3
                .tag("finished", finished)
5178
3
                .tag("ret", ret)
5179
3
                .tag("instance_id", instance_id_)
5180
3
                .tag("tablet_id", tablet_id);
5181
3
        return ret;
5182
3
    }
5183
5184
257
    tablet_metrics_context_.total_recycled_data_size +=
5185
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5186
257
    tablet_metrics_context_.total_recycled_num += 1;
5187
257
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5188
257
    segment_metrics_context_.total_recycled_data_size +=
5189
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5190
257
    metrics_context.total_recycled_data_size +=
5191
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5192
257
    tablet_metrics_context_.report();
5193
257
    segment_metrics_context_.report();
5194
257
    metrics_context.report();
5195
5196
257
    txn.reset();
5197
257
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5198
0
        LOG_WARNING("failed to recycle tablet ")
5199
0
                .tag("tablet id", tablet_id)
5200
0
                .tag("instance_id", instance_id_)
5201
0
                .tag("reason", "failed to create txn");
5202
0
        ret = -1;
5203
0
    }
5204
    // delete all rowset kv in this tablet
5205
257
    txn->remove(rs_key0, rs_key1);
5206
257
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5207
257
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5208
5209
    // remove delete bitmap for MoW table
5210
257
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5211
257
    txn->remove(pending_key);
5212
257
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5213
257
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5214
257
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5215
5216
257
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5217
257
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5218
257
    txn->remove(dbm_start_key, dbm_end_key);
5219
257
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5220
257
              << " end=" << hex(dbm_end_key);
5221
5222
257
    TxnErrorCode err = txn->commit();
5223
257
    if (err != TxnErrorCode::TXN_OK) {
5224
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5225
0
        ret = -1;
5226
0
    }
5227
5228
257
    if (ret == 0) {
5229
        // All object files under tablet have been deleted
5230
257
        std::lock_guard lock(recycled_tablets_mtx_);
5231
257
        recycled_tablets_.insert(tablet_id);
5232
257
    }
5233
5234
257
    return ret;
5235
260
}
5236
5237
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5238
16
                                               RecyclerMetricsContext& metrics_context) {
5239
16
    int ret = 0;
5240
16
    auto start_time = steady_clock::now();
5241
5242
16
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5243
5244
    // collect resource ids
5245
13
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5246
13
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5247
13
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5248
13
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5249
5250
13
    int64_t recycle_rowsets_number = 0;
5251
13
    int64_t recycle_segments_number = 0;
5252
13
    int64_t recycle_rowsets_data_size = 0;
5253
13
    int64_t recycle_rowsets_index_size = 0;
5254
13
    int64_t max_rowset_version = 0;
5255
13
    int64_t min_rowset_creation_time = INT64_MAX;
5256
13
    int64_t max_rowset_creation_time = 0;
5257
13
    int64_t min_rowset_expiration_time = INT64_MAX;
5258
13
    int64_t max_rowset_expiration_time = 0;
5259
5260
13
    DORIS_CLOUD_DEFER {
5261
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5262
13
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5263
13
                .tag("instance_id", instance_id_)
5264
13
                .tag("tablet_id", tablet_id)
5265
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5266
13
                .tag("recycle segments number", recycle_segments_number)
5267
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5268
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5269
13
                .tag("max rowset version", max_rowset_version)
5270
13
                .tag("min rowset creation time", min_rowset_creation_time)
5271
13
                .tag("max rowset creation time", max_rowset_creation_time)
5272
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5273
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5274
13
                .tag("ret", ret);
5275
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5260
13
    DORIS_CLOUD_DEFER {
5261
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5263
13
                .tag("instance_id", instance_id_)
5264
13
                .tag("tablet_id", tablet_id)
5265
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5266
13
                .tag("recycle segments number", recycle_segments_number)
5267
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5268
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5269
13
                .tag("max rowset version", max_rowset_version)
5270
13
                .tag("min rowset creation time", min_rowset_creation_time)
5271
13
                .tag("max rowset creation time", max_rowset_creation_time)
5272
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5273
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5274
13
                .tag("ret", ret);
5275
13
    };
5276
5277
13
    std::unique_ptr<Transaction> txn;
5278
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5279
0
        LOG_WARNING("failed to recycle tablet ")
5280
0
                .tag("tablet id", tablet_id)
5281
0
                .tag("instance_id", instance_id_)
5282
0
                .tag("reason", "failed to create txn");
5283
0
        ret = -1;
5284
0
    }
5285
5286
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5287
    // by the related operation logs.
5288
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5289
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5290
13
    MetaReader meta_reader(instance_id_);
5291
13
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5292
13
    if (err == TxnErrorCode::TXN_OK) {
5293
13
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5294
13
    }
5295
13
    if (err != TxnErrorCode::TXN_OK) {
5296
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5297
0
                .tag("tablet id", tablet_id)
5298
0
                .tag("err", err)
5299
0
                .tag("instance id", instance_id_);
5300
0
        ret = -1;
5301
0
    }
5302
5303
13
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5304
13
             load_rowset_metas.size(), compact_rowset_metas.size())
5305
13
            .tag("instance_id", instance_id_)
5306
13
            .tag("tablet_id", tablet_id);
5307
5308
13
    SyncExecutor<int> concurrent_delete_executor(
5309
13
            _thread_pool_group.s3_producer_pool,
5310
13
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5311
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
5312
5313
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5314
61
        recycle_rowsets_number += 1;
5315
61
        recycle_segments_number += rs_meta.num_segments();
5316
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5317
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5318
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5319
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5320
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5321
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5322
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5323
61
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5313
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5314
61
        recycle_rowsets_number += 1;
5315
61
        recycle_segments_number += rs_meta.num_segments();
5316
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5317
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5318
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5319
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5320
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5321
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5322
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5323
61
    };
5324
5325
13
    std::vector<RowsetDeleteTask> all_tasks;
5326
61
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5327
61
        update_rowset_stats(rs_meta);
5328
        // Version 0-1 rowset has no resource_id and no actual data files,
5329
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5330
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5331
61
        RowsetDeleteTask task;
5332
61
        task.rowset_meta = rs_meta;
5333
61
        task.versioned_rowset_key =
5334
61
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5335
61
        task.non_versioned_rowset_key =
5336
61
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5337
61
        task.versionstamp = versionstamp;
5338
61
        all_tasks.push_back(std::move(task));
5339
61
    }
5340
5341
13
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5342
0
        update_rowset_stats(rs_meta);
5343
        // Version 0-1 rowset has no resource_id and no actual data files,
5344
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5345
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5346
0
        RowsetDeleteTask task;
5347
0
        task.rowset_meta = rs_meta;
5348
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5349
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5350
0
        task.non_versioned_rowset_key =
5351
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5352
0
        task.versionstamp = versionstamp;
5353
0
        all_tasks.push_back(std::move(task));
5354
0
    }
5355
5356
13
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5357
0
        RecycleRowsetPB recycle_rowset;
5358
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5359
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5360
0
            return -1;
5361
0
        }
5362
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5363
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5364
                // in old version, keep this key-value pair and it needs to be checked manually
5365
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5366
0
                return -1;
5367
0
            }
5368
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5369
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5370
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5371
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5372
0
                return -1;
5373
0
            }
5374
            // decode rowset_id
5375
0
            auto k1 = k;
5376
0
            k1.remove_prefix(1);
5377
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5378
0
            decode_key(&k1, &out);
5379
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5380
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5381
0
            LOG_INFO("delete old-version rowset data")
5382
0
                    .tag("instance_id", instance_id_)
5383
0
                    .tag("tablet_id", tablet_id)
5384
0
                    .tag("rowset_id", rowset_id);
5385
5386
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5387
            // so we must use prefix deletion directly instead of batch delete.
5388
0
            concurrent_delete_executor.add(
5389
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5390
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5391
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5392
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
5393
0
        } else {
5394
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5395
            // Version 0-1 rowset has no resource_id and no actual data files,
5396
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5397
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5398
0
            RowsetDeleteTask task;
5399
0
            task.rowset_meta = rowset_meta;
5400
0
            task.recycle_rowset_key = k;
5401
0
            all_tasks.push_back(std::move(task));
5402
0
        }
5403
0
        return 0;
5404
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_
5405
5406
13
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5407
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5408
0
                .tag("tablet id", tablet_id)
5409
0
                .tag("instance_id", instance_id_)
5410
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5411
0
        ret = -1;
5412
0
    }
5413
5414
    // Phase 1: Classify tasks by ref_count
5415
13
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5416
61
    for (auto& task : all_tasks) {
5417
61
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5418
61
        if (classify_ret < 0) {
5419
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5420
0
                    .tag("instance_id", instance_id_)
5421
0
                    .tag("tablet_id", tablet_id)
5422
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5423
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5424
0
                return recycle_rowset_meta_and_data(t);
5425
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5426
0
        }
5427
61
    }
5428
5429
13
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5430
5431
13
    LOG_INFO("batch delete plan created")
5432
13
            .tag("instance_id", instance_id_)
5433
13
            .tag("tablet_id", tablet_id)
5434
13
            .tag("plan_count", batch_delete_tasks.size());
5435
5436
    // Phase 2: Execute batch delete using existing delete_rowset_data
5437
13
    if (!batch_delete_tasks.empty()) {
5438
11
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5439
50
        for (const auto& task : batch_delete_tasks) {
5440
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5441
50
            if (task.rowset_meta.resource_id().empty()) {
5442
11
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5443
11
                        .tag("instance_id", instance_id_)
5444
11
                        .tag("tablet_id", tablet_id)
5445
11
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5446
11
                continue;
5447
11
            }
5448
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5449
39
        }
5450
5451
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5452
11
        bool delete_success = true;
5453
11
        if (!rowsets_to_delete.empty()) {
5454
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5455
9
                                                         "batch_delete_versioned_tablet");
5456
9
            int delete_ret = delete_rowset_data(
5457
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5458
9
            if (delete_ret != 0) {
5459
0
                LOG_WARNING("batch delete execution failed")
5460
0
                        .tag("instance_id", instance_id_)
5461
0
                        .tag("tablet_id", tablet_id);
5462
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5463
0
                ret = -1;
5464
0
                delete_success = false;
5465
0
            }
5466
9
        }
5467
5468
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5469
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5470
11
        if (delete_success) {
5471
11
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5472
11
            if (cleanup_ret != 0) {
5473
0
                LOG_WARNING("batch delete cleanup failed")
5474
0
                        .tag("instance_id", instance_id_)
5475
0
                        .tag("tablet_id", tablet_id);
5476
0
                ret = -1;
5477
0
            }
5478
11
        }
5479
11
    }
5480
5481
    // Always wait for fallback tasks to complete before returning
5482
13
    bool finished = true;
5483
13
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5484
13
    for (int r : rets) {
5485
0
        if (r != 0) {
5486
0
            ret = -1;
5487
0
        }
5488
0
    }
5489
5490
13
    ret = finished ? ret : -1;
5491
5492
13
    if (ret != 0) { // failed recycle tablet data
5493
0
        LOG_WARNING("recycle versioned tablet failed")
5494
0
                .tag("finished", finished)
5495
0
                .tag("ret", ret)
5496
0
                .tag("instance_id", instance_id_)
5497
0
                .tag("tablet_id", tablet_id);
5498
0
        return ret;
5499
0
    }
5500
5501
13
    tablet_metrics_context_.total_recycled_data_size +=
5502
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5503
13
    tablet_metrics_context_.total_recycled_num += 1;
5504
13
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5505
13
    segment_metrics_context_.total_recycled_data_size +=
5506
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5507
13
    metrics_context.total_recycled_data_size +=
5508
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5509
13
    tablet_metrics_context_.report();
5510
13
    segment_metrics_context_.report();
5511
13
    metrics_context.report();
5512
5513
13
    txn.reset();
5514
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5515
0
        LOG_WARNING("failed to recycle tablet ")
5516
0
                .tag("tablet id", tablet_id)
5517
0
                .tag("instance_id", instance_id_)
5518
0
                .tag("reason", "failed to create txn");
5519
0
        ret = -1;
5520
0
    }
5521
    // delete all rowset kv in this tablet
5522
13
    txn->remove(rs_key0, rs_key1);
5523
13
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5524
5525
    // remove delete bitmap for MoW table
5526
13
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5527
13
    txn->remove(pending_key);
5528
13
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5529
13
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5530
13
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5531
5532
13
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5533
13
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5534
13
    txn->remove(dbm_start_key, dbm_end_key);
5535
13
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5536
13
              << " end=" << hex(dbm_end_key);
5537
5538
13
    err = txn->commit();
5539
13
    if (err != TxnErrorCode::TXN_OK) {
5540
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5541
0
        ret = -1;
5542
0
    }
5543
5544
13
    if (ret == 0) {
5545
        // All object files under tablet have been deleted
5546
13
        std::lock_guard lock(recycled_tablets_mtx_);
5547
13
        recycled_tablets_.insert(tablet_id);
5548
13
    }
5549
5550
13
    return ret;
5551
13
}
5552
5553
66
int InstanceRecycler::recycle_rowsets() {
5554
66
    if (should_recycle_versioned_keys()) {
5555
5
        return recycle_versioned_rowsets();
5556
5
    }
5557
5558
61
    const std::string task_name = "recycle_rowsets";
5559
61
    int64_t num_scanned = 0;
5560
61
    int64_t num_expired = 0;
5561
61
    int64_t num_prepare = 0;
5562
61
    int64_t num_compacted = 0;
5563
61
    int64_t num_empty_rowset = 0;
5564
61
    size_t total_rowset_key_size = 0;
5565
61
    size_t total_rowset_value_size = 0;
5566
61
    size_t expired_rowset_size = 0;
5567
61
    std::atomic_long num_recycled = 0;
5568
61
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5569
5570
61
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5571
61
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5572
61
    std::string recyc_rs_key0;
5573
61
    std::string recyc_rs_key1;
5574
61
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5575
61
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5576
5577
61
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5578
5579
61
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5580
61
    register_recycle_task(task_name, start_time);
5581
5582
61
    DORIS_CLOUD_DEFER {
5583
61
        unregister_recycle_task(task_name);
5584
61
        int64_t cost =
5585
61
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5586
61
        metrics_context.finish_report();
5587
61
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5588
61
                .tag("instance_id", instance_id_)
5589
61
                .tag("num_scanned", num_scanned)
5590
61
                .tag("num_expired", num_expired)
5591
61
                .tag("num_recycled", num_recycled)
5592
61
                .tag("num_recycled.prepare", num_prepare)
5593
61
                .tag("num_recycled.compacted", num_compacted)
5594
61
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5595
61
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5596
61
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5597
61
                .tag("expired_rowset_meta_size", expired_rowset_size);
5598
61
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5582
7
    DORIS_CLOUD_DEFER {
5583
7
        unregister_recycle_task(task_name);
5584
7
        int64_t cost =
5585
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5586
7
        metrics_context.finish_report();
5587
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5588
7
                .tag("instance_id", instance_id_)
5589
7
                .tag("num_scanned", num_scanned)
5590
7
                .tag("num_expired", num_expired)
5591
7
                .tag("num_recycled", num_recycled)
5592
7
                .tag("num_recycled.prepare", num_prepare)
5593
7
                .tag("num_recycled.compacted", num_compacted)
5594
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5595
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5596
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5597
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5598
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5582
54
    DORIS_CLOUD_DEFER {
5583
54
        unregister_recycle_task(task_name);
5584
54
        int64_t cost =
5585
54
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5586
54
        metrics_context.finish_report();
5587
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5588
54
                .tag("instance_id", instance_id_)
5589
54
                .tag("num_scanned", num_scanned)
5590
54
                .tag("num_expired", num_expired)
5591
54
                .tag("num_recycled", num_recycled)
5592
54
                .tag("num_recycled.prepare", num_prepare)
5593
54
                .tag("num_recycled.compacted", num_compacted)
5594
54
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5595
54
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5596
54
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5597
54
                .tag("expired_rowset_meta_size", expired_rowset_size);
5598
54
    };
5599
5600
61
    std::vector<std::string> rowset_keys;
5601
61
    std::vector<std::string> rowset_keys_to_mark_recycled;
5602
61
    std::vector<std::string> rowset_keys_to_abort_job;
5603
    // rowset_id -> rowset_meta
5604
    // store rowset id and meta for statistics rs size when delete
5605
61
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5606
5607
61
    std::mutex async_recycled_rowset_keys_mutex;
5608
61
    std::vector<std::string> async_recycled_rowset_keys;
5609
61
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5610
61
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5611
61
    worker_pool->start();
5612
61
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5613
61
                                            int64_t partition_id, int64_t tablet_id,
5614
30.9k
                                            const std::string& rowset_id) {
5615
        // Try to delete rowset data in background thread
5616
30.9k
        int ret = worker_pool->submit_with_timeout(
5617
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5618
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5619
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5620
0
                        return;
5621
0
                    }
5622
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5623
28.4k
                        0) {
5624
0
                        return;
5625
0
                    }
5626
28.4k
                    std::vector<std::string> keys;
5627
28.4k
                    {
5628
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5629
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5630
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5631
278
                            keys.swap(async_recycled_rowset_keys);
5632
278
                        }
5633
28.4k
                    }
5634
28.4k
                    if (keys.empty()) return;
5635
282
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5636
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5637
0
                                     << instance_id_;
5638
282
                    } else {
5639
282
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5640
282
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5641
282
                                           num_recycled, start_time);
5642
282
                    }
5643
282
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5617
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5618
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5619
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5620
0
                        return;
5621
0
                    }
5622
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5623
1
                        0) {
5624
0
                        return;
5625
0
                    }
5626
1
                    std::vector<std::string> keys;
5627
1
                    {
5628
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5629
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5630
1
                        if (async_recycled_rowset_keys.size() > 100) {
5631
0
                            keys.swap(async_recycled_rowset_keys);
5632
0
                        }
5633
1
                    }
5634
1
                    if (keys.empty()) return;
5635
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5636
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5637
0
                                     << instance_id_;
5638
0
                    } else {
5639
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5640
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5641
0
                                           num_recycled, start_time);
5642
0
                    }
5643
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5617
28.4k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5618
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5619
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5620
0
                        return;
5621
0
                    }
5622
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5623
28.4k
                        0) {
5624
0
                        return;
5625
0
                    }
5626
28.4k
                    std::vector<std::string> keys;
5627
28.4k
                    {
5628
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5629
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5630
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5631
278
                            keys.swap(async_recycled_rowset_keys);
5632
278
                        }
5633
28.4k
                    }
5634
28.4k
                    if (keys.empty()) return;
5635
282
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5636
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5637
0
                                     << instance_id_;
5638
282
                    } else {
5639
282
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5640
282
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5641
282
                                           num_recycled, start_time);
5642
282
                    }
5643
282
                },
5644
30.9k
                0);
5645
30.9k
        if (ret == 0) return 0;
5646
        // Submit task failed, delete rowset data in current thread
5647
2.46k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5648
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5649
0
            return -1;
5650
0
        }
5651
2.46k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5652
0
            return -1;
5653
0
        }
5654
2.46k
        rowset_keys.push_back(std::move(key));
5655
2.46k
        return 0;
5656
2.46k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5614
1
                                            const std::string& rowset_id) {
5615
        // Try to delete rowset data in background thread
5616
1
        int ret = worker_pool->submit_with_timeout(
5617
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5618
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5619
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5620
1
                        return;
5621
1
                    }
5622
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5623
1
                        0) {
5624
1
                        return;
5625
1
                    }
5626
1
                    std::vector<std::string> keys;
5627
1
                    {
5628
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5629
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5630
1
                        if (async_recycled_rowset_keys.size() > 100) {
5631
1
                            keys.swap(async_recycled_rowset_keys);
5632
1
                        }
5633
1
                    }
5634
1
                    if (keys.empty()) return;
5635
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5636
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5637
1
                                     << instance_id_;
5638
1
                    } else {
5639
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5640
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5641
1
                                           num_recycled, start_time);
5642
1
                    }
5643
1
                },
5644
1
                0);
5645
1
        if (ret == 0) return 0;
5646
        // Submit task failed, delete rowset data in current thread
5647
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5648
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5649
0
            return -1;
5650
0
        }
5651
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5652
0
            return -1;
5653
0
        }
5654
0
        rowset_keys.push_back(std::move(key));
5655
0
        return 0;
5656
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5614
30.9k
                                            const std::string& rowset_id) {
5615
        // Try to delete rowset data in background thread
5616
30.9k
        int ret = worker_pool->submit_with_timeout(
5617
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5618
30.9k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5619
30.9k
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5620
30.9k
                        return;
5621
30.9k
                    }
5622
30.9k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5623
30.9k
                        0) {
5624
30.9k
                        return;
5625
30.9k
                    }
5626
30.9k
                    std::vector<std::string> keys;
5627
30.9k
                    {
5628
30.9k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5629
30.9k
                        async_recycled_rowset_keys.push_back(std::move(key));
5630
30.9k
                        if (async_recycled_rowset_keys.size() > 100) {
5631
30.9k
                            keys.swap(async_recycled_rowset_keys);
5632
30.9k
                        }
5633
30.9k
                    }
5634
30.9k
                    if (keys.empty()) return;
5635
30.9k
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5636
30.9k
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5637
30.9k
                                     << instance_id_;
5638
30.9k
                    } else {
5639
30.9k
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5640
30.9k
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5641
30.9k
                                           num_recycled, start_time);
5642
30.9k
                    }
5643
30.9k
                },
5644
30.9k
                0);
5645
30.9k
        if (ret == 0) return 0;
5646
        // Submit task failed, delete rowset data in current thread
5647
2.46k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5648
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5649
0
            return -1;
5650
0
        }
5651
2.46k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5652
0
            return -1;
5653
0
        }
5654
2.46k
        rowset_keys.push_back(std::move(key));
5655
2.46k
        return 0;
5656
2.46k
    };
5657
5658
61
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5659
5660
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5661
124k
        ++num_scanned;
5662
124k
        total_rowset_key_size += k.size();
5663
124k
        total_rowset_value_size += v.size();
5664
124k
        RecycleRowsetPB rowset;
5665
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5666
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5667
0
            return -1;
5668
0
        }
5669
5670
124k
        int64_t current_time = ::time(nullptr);
5671
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5672
5673
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5674
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5675
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5676
124k
        if (current_time < expiration) { // not expired
5677
0
            return 0;
5678
0
        }
5679
124k
        ++num_expired;
5680
124k
        expired_rowset_size += v.size();
5681
5682
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5683
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5684
                // in old version, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5689
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5690
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5691
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5692
10.0k
                rowset_keys.emplace_back(k);
5693
10.0k
                return 0;
5694
10.0k
            }
5695
            // decode rowset_id
5696
10.2k
            auto k1 = k;
5697
10.2k
            k1.remove_prefix(1);
5698
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5699
10.2k
            decode_key(&k1, &out);
5700
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5701
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5702
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5703
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5704
10.2k
                      << " task_type=" << metrics_context.operation_type;
5705
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5706
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5707
0
                return -1;
5708
0
            }
5709
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5710
10.2k
            metrics_context.total_recycled_num++;
5711
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5712
10.2k
                    rowset.rowset_meta().total_disk_size();
5713
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5714
10.2k
            return 0;
5715
10.2k
        }
5716
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5717
5718
        // TODO(plat1ko): check rowset not referenced
5719
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5720
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5721
0
                LOG_INFO("recycle rowset that has empty resource id");
5722
0
            } else {
5723
                // other situations, keep this key-value pair and it needs to be checked manually
5724
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5725
0
                return -1;
5726
0
            }
5727
0
        }
5728
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5729
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5730
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5731
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5732
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5733
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5734
104k
                  << " rowset_meta_size=" << v.size()
5735
104k
                  << " creation_time=" << rowset_meta->creation_time()
5736
104k
                  << " task_type=" << metrics_context.operation_type;
5737
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5738
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5739
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5740
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5741
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5742
20.0k
                                 "kv "
5743
20.0k
                                 "at next turn, instance_id="
5744
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5745
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5746
20.0k
                              << rowset_meta->end_version() << "]";
5747
20.0k
                    return 0;
5748
20.0k
                }
5749
50.0k
            }
5750
5751
30.9k
            num_prepare += 1;
5752
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5753
30.9k
                rowset_meta->end_version() != 1) {
5754
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5755
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5756
10.2k
                                 "instance_id="
5757
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5758
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5759
10.2k
                              << rowset_meta->end_version() << "]";
5760
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5761
10.2k
                    return 0;
5762
10.2k
                }
5763
30.2k
            }
5764
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5765
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5766
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5767
0
                return -1;
5768
0
            }
5769
53.1k
        } else {
5770
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5771
53.1k
            rowset_keys.emplace_back(k);
5772
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5773
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5774
53.1k
                ++num_empty_rowset;
5775
53.1k
            }
5776
53.1k
        }
5777
73.7k
        return 0;
5778
104k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5660
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5661
7
        ++num_scanned;
5662
7
        total_rowset_key_size += k.size();
5663
7
        total_rowset_value_size += v.size();
5664
7
        RecycleRowsetPB rowset;
5665
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5666
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5667
0
            return -1;
5668
0
        }
5669
5670
7
        int64_t current_time = ::time(nullptr);
5671
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5672
5673
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5674
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5675
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5676
7
        if (current_time < expiration) { // not expired
5677
0
            return 0;
5678
0
        }
5679
7
        ++num_expired;
5680
7
        expired_rowset_size += v.size();
5681
5682
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5683
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5684
                // in old version, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5689
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5690
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5691
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5692
0
                rowset_keys.emplace_back(k);
5693
0
                return 0;
5694
0
            }
5695
            // decode rowset_id
5696
0
            auto k1 = k;
5697
0
            k1.remove_prefix(1);
5698
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5699
0
            decode_key(&k1, &out);
5700
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5701
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5702
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5703
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5704
0
                      << " task_type=" << metrics_context.operation_type;
5705
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5706
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5707
0
                return -1;
5708
0
            }
5709
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5710
0
            metrics_context.total_recycled_num++;
5711
0
            segment_metrics_context_.total_recycled_data_size +=
5712
0
                    rowset.rowset_meta().total_disk_size();
5713
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5714
0
            return 0;
5715
0
        }
5716
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5717
5718
        // TODO(plat1ko): check rowset not referenced
5719
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5720
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5721
0
                LOG_INFO("recycle rowset that has empty resource id");
5722
0
            } else {
5723
                // other situations, keep this key-value pair and it needs to be checked manually
5724
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5725
0
                return -1;
5726
0
            }
5727
0
        }
5728
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5729
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5730
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5731
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5732
7
                  << "] txn_id=" << rowset_meta->txn_id()
5733
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5734
7
                  << " rowset_meta_size=" << v.size()
5735
7
                  << " creation_time=" << rowset_meta->creation_time()
5736
7
                  << " task_type=" << metrics_context.operation_type;
5737
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5738
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5739
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5740
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5741
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5742
4
                                 "kv "
5743
4
                                 "at next turn, instance_id="
5744
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5745
4
                              << " version=[" << rowset_meta->start_version() << '-'
5746
4
                              << rowset_meta->end_version() << "]";
5747
4
                    return 0;
5748
4
                }
5749
6
            }
5750
5751
3
            num_prepare += 1;
5752
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5753
3
                rowset_meta->end_version() != 1) {
5754
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5755
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5756
2
                                 "instance_id="
5757
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5758
2
                              << " version=[" << rowset_meta->start_version() << '-'
5759
2
                              << rowset_meta->end_version() << "]";
5760
2
                    rowset_keys_to_abort_job.emplace_back(k);
5761
2
                    return 0;
5762
2
                }
5763
2
            }
5764
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5765
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5766
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5767
0
                return -1;
5768
0
            }
5769
1
        } else {
5770
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5771
0
            rowset_keys.emplace_back(k);
5772
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5773
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5774
0
                ++num_empty_rowset;
5775
0
            }
5776
0
        }
5777
1
        return 0;
5778
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5660
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5661
124k
        ++num_scanned;
5662
124k
        total_rowset_key_size += k.size();
5663
124k
        total_rowset_value_size += v.size();
5664
124k
        RecycleRowsetPB rowset;
5665
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5666
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5667
0
            return -1;
5668
0
        }
5669
5670
124k
        int64_t current_time = ::time(nullptr);
5671
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5672
5673
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5674
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5675
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5676
124k
        if (current_time < expiration) { // not expired
5677
0
            return 0;
5678
0
        }
5679
124k
        ++num_expired;
5680
124k
        expired_rowset_size += v.size();
5681
5682
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5683
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5684
                // in old version, keep this key-value pair and it needs to be checked manually
5685
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5686
0
                return -1;
5687
0
            }
5688
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5689
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5690
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5691
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5692
10.0k
                rowset_keys.emplace_back(k);
5693
10.0k
                return 0;
5694
10.0k
            }
5695
            // decode rowset_id
5696
10.2k
            auto k1 = k;
5697
10.2k
            k1.remove_prefix(1);
5698
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5699
10.2k
            decode_key(&k1, &out);
5700
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5701
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5702
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5703
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5704
10.2k
                      << " task_type=" << metrics_context.operation_type;
5705
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5706
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5707
0
                return -1;
5708
0
            }
5709
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5710
10.2k
            metrics_context.total_recycled_num++;
5711
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5712
10.2k
                    rowset.rowset_meta().total_disk_size();
5713
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5714
10.2k
            return 0;
5715
10.2k
        }
5716
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5717
5718
        // TODO(plat1ko): check rowset not referenced
5719
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5720
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5721
0
                LOG_INFO("recycle rowset that has empty resource id");
5722
0
            } else {
5723
                // other situations, keep this key-value pair and it needs to be checked manually
5724
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5725
0
                return -1;
5726
0
            }
5727
0
        }
5728
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5729
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5730
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5731
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5732
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5733
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5734
104k
                  << " rowset_meta_size=" << v.size()
5735
104k
                  << " creation_time=" << rowset_meta->creation_time()
5736
104k
                  << " task_type=" << metrics_context.operation_type;
5737
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5738
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5739
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5740
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5741
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5742
20.0k
                                 "kv "
5743
20.0k
                                 "at next turn, instance_id="
5744
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5745
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5746
20.0k
                              << rowset_meta->end_version() << "]";
5747
20.0k
                    return 0;
5748
20.0k
                }
5749
50.0k
            }
5750
5751
30.9k
            num_prepare += 1;
5752
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5753
30.9k
                rowset_meta->end_version() != 1) {
5754
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5755
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5756
10.2k
                                 "instance_id="
5757
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5758
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5759
10.2k
                              << rowset_meta->end_version() << "]";
5760
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5761
10.2k
                    return 0;
5762
10.2k
                }
5763
30.2k
            }
5764
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5765
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5766
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5767
0
                return -1;
5768
0
            }
5769
53.1k
        } else {
5770
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5771
53.1k
            rowset_keys.emplace_back(k);
5772
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5773
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5774
53.1k
                ++num_empty_rowset;
5775
53.1k
            }
5776
53.1k
        }
5777
73.7k
        return 0;
5778
104k
    };
5779
5780
394
    auto loop_done = [&]() -> int {
5781
394
        std::vector<std::string> rowset_keys_to_delete;
5782
        // rowset_id -> rowset_meta
5783
        // store rowset id and meta for statistics rs size when delete
5784
394
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5785
394
        std::vector<std::string> mark_keys_to_process;
5786
394
        std::vector<std::string> abort_job_keys_to_process;
5787
394
        rowset_keys_to_delete.swap(rowset_keys);
5788
394
        rowsets_to_delete.swap(rowsets);
5789
394
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5790
394
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5791
394
        if (!mark_keys_to_process.empty()) {
5792
69
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5793
69
                    *worker_pool, std::move(mark_keys_to_process));
5794
69
        }
5795
394
        if (!abort_job_keys_to_process.empty()) {
5796
46
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5797
46
                                               &num_recycled);
5798
46
        }
5799
394
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5800
394
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5801
394
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5802
394
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5803
394
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5804
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5805
0
                return;
5806
0
            }
5807
394
            if (!versioned_delete_bitmap_key_groups.empty() &&
5808
394
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5809
50
                                                         versioned_delete_bitmap_key_groups) != 0) {
5810
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5811
0
                             << instance_id_;
5812
0
                return;
5813
0
            }
5814
394
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5815
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5816
0
                return;
5817
0
            }
5818
394
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5819
394
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5800
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5801
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5802
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5803
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5804
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5805
0
                return;
5806
0
            }
5807
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5808
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5809
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
5810
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5811
0
                             << instance_id_;
5812
0
                return;
5813
0
            }
5814
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5815
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5816
0
                return;
5817
0
            }
5818
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5819
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5800
387
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5801
387
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5802
387
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5803
387
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5804
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5805
0
                return;
5806
0
            }
5807
387
            if (!versioned_delete_bitmap_key_groups.empty() &&
5808
387
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5809
50
                                                         versioned_delete_bitmap_key_groups) != 0) {
5810
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5811
0
                             << instance_id_;
5812
0
                return;
5813
0
            }
5814
387
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5815
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5816
0
                return;
5817
0
            }
5818
387
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5819
387
        });
5820
394
        return 0;
5821
394
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5780
7
    auto loop_done = [&]() -> int {
5781
7
        std::vector<std::string> rowset_keys_to_delete;
5782
        // rowset_id -> rowset_meta
5783
        // store rowset id and meta for statistics rs size when delete
5784
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5785
7
        std::vector<std::string> mark_keys_to_process;
5786
7
        std::vector<std::string> abort_job_keys_to_process;
5787
7
        rowset_keys_to_delete.swap(rowset_keys);
5788
7
        rowsets_to_delete.swap(rowsets);
5789
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5790
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5791
7
        if (!mark_keys_to_process.empty()) {
5792
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5793
4
                    *worker_pool, std::move(mark_keys_to_process));
5794
4
        }
5795
7
        if (!abort_job_keys_to_process.empty()) {
5796
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5797
2
                                               &num_recycled);
5798
2
        }
5799
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5800
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5801
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5802
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5803
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5804
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5805
7
                return;
5806
7
            }
5807
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5808
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5809
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
5810
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5811
7
                             << instance_id_;
5812
7
                return;
5813
7
            }
5814
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5815
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5816
7
                return;
5817
7
            }
5818
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5819
7
        });
5820
7
        return 0;
5821
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5780
387
    auto loop_done = [&]() -> int {
5781
387
        std::vector<std::string> rowset_keys_to_delete;
5782
        // rowset_id -> rowset_meta
5783
        // store rowset id and meta for statistics rs size when delete
5784
387
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5785
387
        std::vector<std::string> mark_keys_to_process;
5786
387
        std::vector<std::string> abort_job_keys_to_process;
5787
387
        rowset_keys_to_delete.swap(rowset_keys);
5788
387
        rowsets_to_delete.swap(rowsets);
5789
387
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5790
387
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5791
387
        if (!mark_keys_to_process.empty()) {
5792
65
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5793
65
                    *worker_pool, std::move(mark_keys_to_process));
5794
65
        }
5795
387
        if (!abort_job_keys_to_process.empty()) {
5796
44
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5797
44
                                               &num_recycled);
5798
44
        }
5799
387
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5800
387
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5801
387
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5802
387
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5803
387
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5804
387
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5805
387
                return;
5806
387
            }
5807
387
            if (!versioned_delete_bitmap_key_groups.empty() &&
5808
387
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5809
387
                                                         versioned_delete_bitmap_key_groups) != 0) {
5810
387
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5811
387
                             << instance_id_;
5812
387
                return;
5813
387
            }
5814
387
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5815
387
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5816
387
                return;
5817
387
            }
5818
387
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5819
387
        });
5820
387
        return 0;
5821
387
    };
5822
5823
61
    if (config::enable_recycler_stats_metrics) {
5824
0
        scan_and_statistics_rowsets();
5825
0
    }
5826
    // recycle_func and loop_done for scan and recycle
5827
61
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5828
61
                               std::move(loop_done));
5829
5830
61
    worker_pool->stop();
5831
5832
61
    if (!async_recycled_rowset_keys.empty()) {
5833
9
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5834
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5835
0
            return -1;
5836
9
        } else {
5837
9
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5838
9
        }
5839
9
    }
5840
5841
    // Report final metrics after all concurrent tasks completed
5842
61
    segment_metrics_context_.report();
5843
61
    metrics_context.report();
5844
5845
61
    return ret;
5846
61
}
5847
5848
13
int InstanceRecycler::recycle_restore_jobs() {
5849
13
    const std::string task_name = "recycle_restore_jobs";
5850
13
    int64_t num_scanned = 0;
5851
13
    int64_t num_expired = 0;
5852
13
    int64_t num_recycled = 0;
5853
13
    int64_t num_aborted = 0;
5854
5855
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5856
5857
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5858
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5859
13
    std::string restore_job_key0;
5860
13
    std::string restore_job_key1;
5861
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5862
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5863
5864
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5865
5866
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5867
13
    register_recycle_task(task_name, start_time);
5868
5869
13
    DORIS_CLOUD_DEFER {
5870
13
        unregister_recycle_task(task_name);
5871
13
        int64_t cost =
5872
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5873
13
        metrics_context.finish_report();
5874
5875
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5876
13
                .tag("instance_id", instance_id_)
5877
13
                .tag("num_scanned", num_scanned)
5878
13
                .tag("num_expired", num_expired)
5879
13
                .tag("num_recycled", num_recycled)
5880
13
                .tag("num_aborted", num_aborted);
5881
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5869
13
    DORIS_CLOUD_DEFER {
5870
13
        unregister_recycle_task(task_name);
5871
13
        int64_t cost =
5872
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5873
13
        metrics_context.finish_report();
5874
5875
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5876
13
                .tag("instance_id", instance_id_)
5877
13
                .tag("num_scanned", num_scanned)
5878
13
                .tag("num_expired", num_expired)
5879
13
                .tag("num_recycled", num_recycled)
5880
13
                .tag("num_aborted", num_aborted);
5881
13
    };
5882
5883
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5884
5885
13
    std::vector<std::string_view> restore_job_keys;
5886
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5887
41
        ++num_scanned;
5888
41
        RestoreJobCloudPB restore_job_pb;
5889
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5890
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5891
0
            return -1;
5892
0
        }
5893
41
        int64_t expiration =
5894
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5895
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5896
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5897
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5898
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5899
0
                   << " state=" << restore_job_pb.state();
5900
41
        int64_t current_time = ::time(nullptr);
5901
41
        if (current_time < expiration) { // not expired
5902
0
            return 0;
5903
0
        }
5904
41
        ++num_expired;
5905
5906
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5907
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5908
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5909
5910
41
        std::unique_ptr<Transaction> txn;
5911
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5912
41
        if (err != TxnErrorCode::TXN_OK) {
5913
0
            LOG_WARNING("failed to recycle restore job")
5914
0
                    .tag("err", err)
5915
0
                    .tag("tablet id", tablet_id)
5916
0
                    .tag("instance_id", instance_id_)
5917
0
                    .tag("reason", "failed to create txn");
5918
0
            return -1;
5919
0
        }
5920
5921
41
        std::string val;
5922
41
        err = txn->get(k, &val);
5923
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5924
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5925
0
            return 0;
5926
0
        }
5927
41
        if (err != TxnErrorCode::TXN_OK) {
5928
0
            LOG_WARNING("failed to get kv");
5929
0
            return -1;
5930
0
        }
5931
41
        restore_job_pb.Clear();
5932
41
        if (!restore_job_pb.ParseFromString(val)) {
5933
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5934
0
            return -1;
5935
0
        }
5936
5937
        // PREPARED or COMMITTED, change state to DROPPED and return
5938
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5939
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5940
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5941
0
            restore_job_pb.set_need_recycle_data(true);
5942
0
            txn->put(k, restore_job_pb.SerializeAsString());
5943
0
            err = txn->commit();
5944
0
            if (err != TxnErrorCode::TXN_OK) {
5945
0
                LOG_WARNING("failed to commit txn: {}", err);
5946
0
                return -1;
5947
0
            }
5948
0
            num_aborted++;
5949
0
            return 0;
5950
0
        }
5951
5952
        // Change state to RECYCLING
5953
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5954
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5955
21
            txn->put(k, restore_job_pb.SerializeAsString());
5956
21
            err = txn->commit();
5957
21
            if (err != TxnErrorCode::TXN_OK) {
5958
0
                LOG_WARNING("failed to commit txn: {}", err);
5959
0
                return -1;
5960
0
            }
5961
21
            return 0;
5962
21
        }
5963
5964
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5965
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5966
5967
        // Recycle all data associated with the restore job.
5968
        // This includes rowsets, segments, and related resources.
5969
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5970
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5971
0
            LOG_WARNING("failed to recycle tablet")
5972
0
                    .tag("tablet_id", tablet_id)
5973
0
                    .tag("instance_id", instance_id_);
5974
0
            return -1;
5975
0
        }
5976
5977
        // delete all restore job rowset kv
5978
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5979
5980
20
        err = txn->commit();
5981
20
        if (err != TxnErrorCode::TXN_OK) {
5982
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5983
0
                    .tag("err", err)
5984
0
                    .tag("tablet id", tablet_id)
5985
0
                    .tag("instance_id", instance_id_)
5986
0
                    .tag("reason", "failed to commit txn");
5987
0
            return -1;
5988
0
        }
5989
5990
20
        metrics_context.total_recycled_num = ++num_recycled;
5991
20
        metrics_context.report();
5992
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5993
20
        restore_job_keys.push_back(k);
5994
5995
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5996
20
                  << " tablet_id=" << tablet_id;
5997
20
        return 0;
5998
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
5886
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5887
41
        ++num_scanned;
5888
41
        RestoreJobCloudPB restore_job_pb;
5889
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5890
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5891
0
            return -1;
5892
0
        }
5893
41
        int64_t expiration =
5894
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5895
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5896
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5897
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5898
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5899
0
                   << " state=" << restore_job_pb.state();
5900
41
        int64_t current_time = ::time(nullptr);
5901
41
        if (current_time < expiration) { // not expired
5902
0
            return 0;
5903
0
        }
5904
41
        ++num_expired;
5905
5906
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5907
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5908
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5909
5910
41
        std::unique_ptr<Transaction> txn;
5911
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5912
41
        if (err != TxnErrorCode::TXN_OK) {
5913
0
            LOG_WARNING("failed to recycle restore job")
5914
0
                    .tag("err", err)
5915
0
                    .tag("tablet id", tablet_id)
5916
0
                    .tag("instance_id", instance_id_)
5917
0
                    .tag("reason", "failed to create txn");
5918
0
            return -1;
5919
0
        }
5920
5921
41
        std::string val;
5922
41
        err = txn->get(k, &val);
5923
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5924
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5925
0
            return 0;
5926
0
        }
5927
41
        if (err != TxnErrorCode::TXN_OK) {
5928
0
            LOG_WARNING("failed to get kv");
5929
0
            return -1;
5930
0
        }
5931
41
        restore_job_pb.Clear();
5932
41
        if (!restore_job_pb.ParseFromString(val)) {
5933
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5934
0
            return -1;
5935
0
        }
5936
5937
        // PREPARED or COMMITTED, change state to DROPPED and return
5938
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5939
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5940
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5941
0
            restore_job_pb.set_need_recycle_data(true);
5942
0
            txn->put(k, restore_job_pb.SerializeAsString());
5943
0
            err = txn->commit();
5944
0
            if (err != TxnErrorCode::TXN_OK) {
5945
0
                LOG_WARNING("failed to commit txn: {}", err);
5946
0
                return -1;
5947
0
            }
5948
0
            num_aborted++;
5949
0
            return 0;
5950
0
        }
5951
5952
        // Change state to RECYCLING
5953
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5954
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5955
21
            txn->put(k, restore_job_pb.SerializeAsString());
5956
21
            err = txn->commit();
5957
21
            if (err != TxnErrorCode::TXN_OK) {
5958
0
                LOG_WARNING("failed to commit txn: {}", err);
5959
0
                return -1;
5960
0
            }
5961
21
            return 0;
5962
21
        }
5963
5964
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5965
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5966
5967
        // Recycle all data associated with the restore job.
5968
        // This includes rowsets, segments, and related resources.
5969
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5970
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5971
0
            LOG_WARNING("failed to recycle tablet")
5972
0
                    .tag("tablet_id", tablet_id)
5973
0
                    .tag("instance_id", instance_id_);
5974
0
            return -1;
5975
0
        }
5976
5977
        // delete all restore job rowset kv
5978
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5979
5980
20
        err = txn->commit();
5981
20
        if (err != TxnErrorCode::TXN_OK) {
5982
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5983
0
                    .tag("err", err)
5984
0
                    .tag("tablet id", tablet_id)
5985
0
                    .tag("instance_id", instance_id_)
5986
0
                    .tag("reason", "failed to commit txn");
5987
0
            return -1;
5988
0
        }
5989
5990
20
        metrics_context.total_recycled_num = ++num_recycled;
5991
20
        metrics_context.report();
5992
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5993
20
        restore_job_keys.push_back(k);
5994
5995
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5996
20
                  << " tablet_id=" << tablet_id;
5997
20
        return 0;
5998
20
    };
5999
6000
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6001
3
        if (restore_job_keys.empty()) return 0;
6002
1
        DORIS_CLOUD_DEFER {
6003
1
            restore_job_keys.clear();
6004
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6002
1
        DORIS_CLOUD_DEFER {
6003
1
            restore_job_keys.clear();
6004
1
        };
6005
6006
1
        std::unique_ptr<Transaction> txn;
6007
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6008
1
        if (err != TxnErrorCode::TXN_OK) {
6009
0
            LOG_WARNING("failed to recycle restore job")
6010
0
                    .tag("err", err)
6011
0
                    .tag("instance_id", instance_id_)
6012
0
                    .tag("reason", "failed to create txn");
6013
0
            return -1;
6014
0
        }
6015
20
        for (auto& k : restore_job_keys) {
6016
20
            txn->remove(k);
6017
20
        }
6018
1
        err = txn->commit();
6019
1
        if (err != TxnErrorCode::TXN_OK) {
6020
0
            LOG_WARNING("failed to recycle restore job")
6021
0
                    .tag("err", err)
6022
0
                    .tag("instance_id", instance_id_)
6023
0
                    .tag("reason", "failed to commit txn");
6024
0
            return -1;
6025
0
        }
6026
1
        return 0;
6027
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6000
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6001
3
        if (restore_job_keys.empty()) return 0;
6002
1
        DORIS_CLOUD_DEFER {
6003
1
            restore_job_keys.clear();
6004
1
        };
6005
6006
1
        std::unique_ptr<Transaction> txn;
6007
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6008
1
        if (err != TxnErrorCode::TXN_OK) {
6009
0
            LOG_WARNING("failed to recycle restore job")
6010
0
                    .tag("err", err)
6011
0
                    .tag("instance_id", instance_id_)
6012
0
                    .tag("reason", "failed to create txn");
6013
0
            return -1;
6014
0
        }
6015
20
        for (auto& k : restore_job_keys) {
6016
20
            txn->remove(k);
6017
20
        }
6018
1
        err = txn->commit();
6019
1
        if (err != TxnErrorCode::TXN_OK) {
6020
0
            LOG_WARNING("failed to recycle restore job")
6021
0
                    .tag("err", err)
6022
0
                    .tag("instance_id", instance_id_)
6023
0
                    .tag("reason", "failed to commit txn");
6024
0
            return -1;
6025
0
        }
6026
1
        return 0;
6027
1
    };
6028
6029
13
    if (config::enable_recycler_stats_metrics) {
6030
0
        scan_and_statistics_restore_jobs();
6031
0
    }
6032
6033
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6034
13
                            std::move(loop_done));
6035
13
}
6036
6037
11
int InstanceRecycler::recycle_versioned_rowsets() {
6038
11
    const std::string task_name = "recycle_rowsets";
6039
11
    int64_t num_scanned = 0;
6040
11
    int64_t num_expired = 0;
6041
11
    int64_t num_prepare = 0;
6042
11
    int64_t num_compacted = 0;
6043
11
    int64_t num_empty_rowset = 0;
6044
11
    size_t total_rowset_key_size = 0;
6045
11
    size_t total_rowset_value_size = 0;
6046
11
    size_t expired_rowset_size = 0;
6047
11
    std::atomic_long num_recycled = 0;
6048
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6049
6050
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6051
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6052
11
    std::string recyc_rs_key0;
6053
11
    std::string recyc_rs_key1;
6054
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6055
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6056
6057
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6058
6059
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6060
11
    register_recycle_task(task_name, start_time);
6061
6062
11
    DORIS_CLOUD_DEFER {
6063
11
        unregister_recycle_task(task_name);
6064
11
        int64_t cost =
6065
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6066
11
        metrics_context.finish_report();
6067
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6068
11
                .tag("instance_id", instance_id_)
6069
11
                .tag("num_scanned", num_scanned)
6070
11
                .tag("num_expired", num_expired)
6071
11
                .tag("num_recycled", num_recycled)
6072
11
                .tag("num_recycled.prepare", num_prepare)
6073
11
                .tag("num_recycled.compacted", num_compacted)
6074
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6075
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6076
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6077
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6078
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6062
11
    DORIS_CLOUD_DEFER {
6063
11
        unregister_recycle_task(task_name);
6064
11
        int64_t cost =
6065
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6066
11
        metrics_context.finish_report();
6067
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6068
11
                .tag("instance_id", instance_id_)
6069
11
                .tag("num_scanned", num_scanned)
6070
11
                .tag("num_expired", num_expired)
6071
11
                .tag("num_recycled", num_recycled)
6072
11
                .tag("num_recycled.prepare", num_prepare)
6073
11
                .tag("num_recycled.compacted", num_compacted)
6074
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6075
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6076
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6077
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6078
11
    };
6079
6080
11
    std::vector<std::string> orphan_rowset_keys;
6081
6082
    // Store keys of rowset recycled by background workers
6083
11
    std::mutex async_recycled_rowset_keys_mutex;
6084
11
    std::vector<std::string> async_recycled_rowset_keys;
6085
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6086
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6087
11
    worker_pool->start();
6088
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6089
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6090
        // Try to delete rowset data in background thread
6091
400
        int ret = worker_pool->submit_with_timeout(
6092
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6093
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6094
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6095
400
                        return;
6096
400
                    }
6097
                    // The async recycled rowsets are staled format or has not been used,
6098
                    // so we don't need to check the rowset ref count key.
6099
0
                    std::vector<std::string> keys;
6100
0
                    {
6101
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6102
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6103
0
                        if (async_recycled_rowset_keys.size() > 100) {
6104
0
                            keys.swap(async_recycled_rowset_keys);
6105
0
                        }
6106
0
                    }
6107
0
                    if (keys.empty()) return;
6108
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6109
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6110
0
                                     << instance_id_;
6111
0
                    } else {
6112
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6113
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6114
0
                                           num_recycled, start_time);
6115
0
                    }
6116
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
6092
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6093
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6094
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6095
400
                        return;
6096
400
                    }
6097
                    // The async recycled rowsets are staled format or has not been used,
6098
                    // so we don't need to check the rowset ref count key.
6099
0
                    std::vector<std::string> keys;
6100
0
                    {
6101
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6102
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6103
0
                        if (async_recycled_rowset_keys.size() > 100) {
6104
0
                            keys.swap(async_recycled_rowset_keys);
6105
0
                        }
6106
0
                    }
6107
0
                    if (keys.empty()) return;
6108
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6109
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6110
0
                                     << instance_id_;
6111
0
                    } else {
6112
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6113
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6114
0
                                           num_recycled, start_time);
6115
0
                    }
6116
0
                },
6117
400
                0);
6118
400
        if (ret == 0) return 0;
6119
        // Submit task failed, delete rowset data in current thread
6120
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6121
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6122
0
            return -1;
6123
0
        }
6124
0
        orphan_rowset_keys.push_back(std::move(key));
6125
0
        return 0;
6126
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
6089
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6090
        // Try to delete rowset data in background thread
6091
400
        int ret = worker_pool->submit_with_timeout(
6092
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6093
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6094
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6095
400
                        return;
6096
400
                    }
6097
                    // The async recycled rowsets are staled format or has not been used,
6098
                    // so we don't need to check the rowset ref count key.
6099
400
                    std::vector<std::string> keys;
6100
400
                    {
6101
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6102
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6103
400
                        if (async_recycled_rowset_keys.size() > 100) {
6104
400
                            keys.swap(async_recycled_rowset_keys);
6105
400
                        }
6106
400
                    }
6107
400
                    if (keys.empty()) return;
6108
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6109
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6110
400
                                     << instance_id_;
6111
400
                    } else {
6112
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6113
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6114
400
                                           num_recycled, start_time);
6115
400
                    }
6116
400
                },
6117
400
                0);
6118
400
        if (ret == 0) return 0;
6119
        // Submit task failed, delete rowset data in current thread
6120
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6121
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6122
0
            return -1;
6123
0
        }
6124
0
        orphan_rowset_keys.push_back(std::move(key));
6125
0
        return 0;
6126
0
    };
6127
6128
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6129
6130
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6131
2.01k
        ++num_scanned;
6132
2.01k
        total_rowset_key_size += k.size();
6133
2.01k
        total_rowset_value_size += v.size();
6134
2.01k
        RecycleRowsetPB rowset;
6135
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6136
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6137
0
            return -1;
6138
0
        }
6139
6140
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6141
6142
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6143
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6144
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6145
2.01k
        int64_t current_time = ::time(nullptr);
6146
2.01k
        if (current_time < final_expiration) { // not expired
6147
0
            return 0;
6148
0
        }
6149
2.01k
        ++num_expired;
6150
2.01k
        expired_rowset_size += v.size();
6151
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6152
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6153
                // in old version, keep this key-value pair and it needs to be checked manually
6154
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6155
0
                return -1;
6156
0
            }
6157
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6158
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6159
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6160
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6161
0
                orphan_rowset_keys.emplace_back(k);
6162
0
                return -1;
6163
0
            }
6164
            // decode rowset_id
6165
0
            auto k1 = k;
6166
0
            k1.remove_prefix(1);
6167
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6168
0
            decode_key(&k1, &out);
6169
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6170
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6171
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6172
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6173
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6174
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6175
0
                return -1;
6176
0
            }
6177
0
            return 0;
6178
0
        }
6179
        // TODO(plat1ko): check rowset not referenced
6180
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6181
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6182
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6183
0
                LOG_INFO("recycle rowset that has empty resource id");
6184
0
            } else {
6185
                // other situations, keep this key-value pair and it needs to be checked manually
6186
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6187
0
                return -1;
6188
0
            }
6189
0
        }
6190
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6191
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6192
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6193
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6194
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6195
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6196
2.01k
                  << " rowset_meta_size=" << v.size()
6197
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6198
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6199
            // unable to calculate file path, can only be deleted by rowset id prefix
6200
400
            num_prepare += 1;
6201
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6202
400
                                             rowset_meta->tablet_id(),
6203
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6204
0
                return -1;
6205
0
            }
6206
1.61k
        } else {
6207
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6208
1.61k
            worker_pool->submit(
6209
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6210
                        // The load & compact rowset keys are recycled during recycling operation logs.
6211
1.61k
                        RowsetDeleteTask task;
6212
1.61k
                        task.rowset_meta = rowset_meta;
6213
1.61k
                        task.recycle_rowset_key = k;
6214
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6215
1.59k
                            return;
6216
1.59k
                        }
6217
14
                        num_compacted += is_compacted;
6218
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6219
14
                        if (rowset_meta.num_segments() == 0) {
6220
0
                            ++num_empty_rowset;
6221
0
                        }
6222
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
6209
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6210
                        // The load & compact rowset keys are recycled during recycling operation logs.
6211
1.61k
                        RowsetDeleteTask task;
6212
1.61k
                        task.rowset_meta = rowset_meta;
6213
1.61k
                        task.recycle_rowset_key = k;
6214
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6215
1.59k
                            return;
6216
1.59k
                        }
6217
14
                        num_compacted += is_compacted;
6218
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6219
14
                        if (rowset_meta.num_segments() == 0) {
6220
0
                            ++num_empty_rowset;
6221
0
                        }
6222
14
                    });
6223
1.61k
        }
6224
2.01k
        return 0;
6225
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
6130
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6131
2.01k
        ++num_scanned;
6132
2.01k
        total_rowset_key_size += k.size();
6133
2.01k
        total_rowset_value_size += v.size();
6134
2.01k
        RecycleRowsetPB rowset;
6135
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6136
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6137
0
            return -1;
6138
0
        }
6139
6140
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6141
6142
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6143
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6144
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6145
2.01k
        int64_t current_time = ::time(nullptr);
6146
2.01k
        if (current_time < final_expiration) { // not expired
6147
0
            return 0;
6148
0
        }
6149
2.01k
        ++num_expired;
6150
2.01k
        expired_rowset_size += v.size();
6151
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6152
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6153
                // in old version, keep this key-value pair and it needs to be checked manually
6154
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6155
0
                return -1;
6156
0
            }
6157
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6158
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6159
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6160
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6161
0
                orphan_rowset_keys.emplace_back(k);
6162
0
                return -1;
6163
0
            }
6164
            // decode rowset_id
6165
0
            auto k1 = k;
6166
0
            k1.remove_prefix(1);
6167
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6168
0
            decode_key(&k1, &out);
6169
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6170
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6171
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6172
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6173
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6174
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6175
0
                return -1;
6176
0
            }
6177
0
            return 0;
6178
0
        }
6179
        // TODO(plat1ko): check rowset not referenced
6180
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6181
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6182
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6183
0
                LOG_INFO("recycle rowset that has empty resource id");
6184
0
            } else {
6185
                // other situations, keep this key-value pair and it needs to be checked manually
6186
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6187
0
                return -1;
6188
0
            }
6189
0
        }
6190
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6191
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6192
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6193
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6194
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6195
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6196
2.01k
                  << " rowset_meta_size=" << v.size()
6197
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6198
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6199
            // unable to calculate file path, can only be deleted by rowset id prefix
6200
400
            num_prepare += 1;
6201
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6202
400
                                             rowset_meta->tablet_id(),
6203
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6204
0
                return -1;
6205
0
            }
6206
1.61k
        } else {
6207
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6208
1.61k
            worker_pool->submit(
6209
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6210
                        // The load & compact rowset keys are recycled during recycling operation logs.
6211
1.61k
                        RowsetDeleteTask task;
6212
1.61k
                        task.rowset_meta = rowset_meta;
6213
1.61k
                        task.recycle_rowset_key = k;
6214
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6215
1.61k
                            return;
6216
1.61k
                        }
6217
1.61k
                        num_compacted += is_compacted;
6218
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6219
1.61k
                        if (rowset_meta.num_segments() == 0) {
6220
1.61k
                            ++num_empty_rowset;
6221
1.61k
                        }
6222
1.61k
                    });
6223
1.61k
        }
6224
2.01k
        return 0;
6225
2.01k
    };
6226
6227
11
    if (config::enable_recycler_stats_metrics) {
6228
0
        scan_and_statistics_rowsets();
6229
0
    }
6230
6231
11
    auto loop_done = [&]() -> int {
6232
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6233
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6234
0
        }
6235
6
        orphan_rowset_keys.clear();
6236
6
        return 0;
6237
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6231
6
    auto loop_done = [&]() -> int {
6232
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6233
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6234
0
        }
6235
6
        orphan_rowset_keys.clear();
6236
6
        return 0;
6237
6
    };
6238
6239
    // recycle_func and loop_done for scan and recycle
6240
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6241
11
                               std::move(loop_done));
6242
6243
11
    worker_pool->stop();
6244
6245
11
    if (!async_recycled_rowset_keys.empty()) {
6246
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6247
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6248
0
            return -1;
6249
0
        } else {
6250
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6251
0
        }
6252
0
    }
6253
6254
    // Report final metrics after all concurrent tasks completed
6255
11
    segment_metrics_context_.report();
6256
11
    metrics_context.report();
6257
6258
11
    return ret;
6259
11
}
6260
6261
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6262
1.61k
    constexpr int MAX_RETRY = 10;
6263
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6264
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6265
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6266
1.61k
    std::string_view reference_instance_id = instance_id_;
6267
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6268
8
        reference_instance_id = rowset_meta.reference_instance_id();
6269
8
    }
6270
6271
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6272
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6273
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6274
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6275
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6276
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6277
1.61k
        std::unique_ptr<Transaction> txn;
6278
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6279
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6280
0
            LOG_WARNING("failed to create txn").tag("err", err);
6281
0
            return -1;
6282
0
        }
6283
6284
1.61k
        std::string rowset_ref_count_key =
6285
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6286
1.61k
        int64_t ref_count = 0;
6287
1.61k
        {
6288
1.61k
            std::string value;
6289
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6290
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6291
                // This is the old version rowset, we could recycle it directly.
6292
1.60k
                ref_count = 1;
6293
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6294
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6295
0
                return -1;
6296
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6297
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6298
0
                return -1;
6299
0
            }
6300
1.61k
        }
6301
6302
1.61k
        if (ref_count == 1) {
6303
            // It would not be added since it is recycling.
6304
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6305
1.60k
                LOG_WARNING("failed to delete rowset data");
6306
1.60k
                return -1;
6307
1.60k
            }
6308
6309
            // Reset the transaction to avoid timeout.
6310
10
            err = txn_kv_->create_txn(&txn);
6311
10
            if (err != TxnErrorCode::TXN_OK) {
6312
0
                LOG_WARNING("failed to create txn").tag("err", err);
6313
0
                return -1;
6314
0
            }
6315
10
            txn->remove(rowset_ref_count_key);
6316
10
            LOG_INFO("delete rowset data ref count key")
6317
10
                    .tag("txn_id", rowset_meta.txn_id())
6318
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6319
6320
10
            std::string dbm_start_key =
6321
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6322
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6323
10
                    {reference_instance_id, tablet_id, rowset_id,
6324
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6325
10
            txn->remove(dbm_start_key, dbm_end_key);
6326
10
            LOG_INFO("remove delete bitmap kv")
6327
10
                    .tag("begin", hex(dbm_start_key))
6328
10
                    .tag("end", hex(dbm_end_key));
6329
6330
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6331
10
                    {reference_instance_id, tablet_id, rowset_id});
6332
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6333
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6334
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6335
10
            LOG_INFO("remove versioned delete bitmap kv")
6336
10
                    .tag("begin", hex(versioned_dbm_start_key))
6337
10
                    .tag("end", hex(versioned_dbm_end_key));
6338
10
        } else {
6339
            // Decrease the rowset ref count.
6340
            //
6341
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6342
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6343
3
            txn->atomic_add(rowset_ref_count_key, -1);
6344
3
            LOG_INFO("decrease rowset data ref count")
6345
3
                    .tag("txn_id", rowset_meta.txn_id())
6346
3
                    .tag("ref_count", ref_count - 1)
6347
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6348
3
        }
6349
6350
13
        if (!task.versioned_rowset_key.empty()) {
6351
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6352
0
                                                          task.versionstamp);
6353
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6354
0
        }
6355
6356
13
        if (!task.non_versioned_rowset_key.empty()) {
6357
0
            txn->remove(task.non_versioned_rowset_key);
6358
0
            LOG_INFO("remove non versioned rowset key")
6359
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6360
0
        }
6361
6362
        // empty when recycle ref rowsets for deleted instance
6363
13
        if (!task.recycle_rowset_key.empty()) {
6364
13
            txn->remove(task.recycle_rowset_key);
6365
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6366
13
        }
6367
6368
13
        err = txn->commit();
6369
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6370
            // The rowset ref count key has been changed, we need to retry.
6371
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6372
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6373
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6374
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6375
0
            continue;
6376
13
        } else if (err != TxnErrorCode::TXN_OK) {
6377
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6378
0
            return -1;
6379
0
        }
6380
13
        LOG_INFO("recycle rowset meta and data success");
6381
13
        return 0;
6382
13
    }
6383
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6384
0
            .tag("tablet_id", tablet_id)
6385
0
            .tag("rowset_id", rowset_id)
6386
0
            .tag("retry", MAX_RETRY);
6387
0
    return -1;
6388
1.61k
}
6389
6390
37
int InstanceRecycler::recycle_tmp_rowsets() {
6391
37
    const std::string task_name = "recycle_tmp_rowsets";
6392
37
    int64_t num_scanned = 0;
6393
37
    int64_t num_expired = 0;
6394
37
    std::atomic_long num_recycled = 0;
6395
37
    size_t expired_rowset_size = 0;
6396
37
    size_t total_rowset_key_size = 0;
6397
37
    size_t total_rowset_value_size = 0;
6398
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6399
6400
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6401
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6402
37
    std::string tmp_rs_key0;
6403
37
    std::string tmp_rs_key1;
6404
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6405
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6406
6407
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6408
6409
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6410
37
    register_recycle_task(task_name, start_time);
6411
6412
37
    DORIS_CLOUD_DEFER {
6413
37
        unregister_recycle_task(task_name);
6414
37
        int64_t cost =
6415
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6416
37
        metrics_context.finish_report();
6417
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6418
37
                .tag("instance_id", instance_id_)
6419
37
                .tag("num_scanned", num_scanned)
6420
37
                .tag("num_expired", num_expired)
6421
37
                .tag("num_recycled", num_recycled)
6422
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6423
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6424
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6425
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6412
12
    DORIS_CLOUD_DEFER {
6413
12
        unregister_recycle_task(task_name);
6414
12
        int64_t cost =
6415
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6416
12
        metrics_context.finish_report();
6417
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6418
12
                .tag("instance_id", instance_id_)
6419
12
                .tag("num_scanned", num_scanned)
6420
12
                .tag("num_expired", num_expired)
6421
12
                .tag("num_recycled", num_recycled)
6422
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6423
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6424
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6425
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6412
25
    DORIS_CLOUD_DEFER {
6413
25
        unregister_recycle_task(task_name);
6414
25
        int64_t cost =
6415
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6416
25
        metrics_context.finish_report();
6417
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6418
25
                .tag("instance_id", instance_id_)
6419
25
                .tag("num_scanned", num_scanned)
6420
25
                .tag("num_expired", num_expired)
6421
25
                .tag("num_recycled", num_recycled)
6422
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6423
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6424
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6425
25
    };
6426
6427
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6428
37
    std::vector<std::string> tmp_rowset_keys;
6429
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6430
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6431
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6432
6433
    // rowset_id -> rowset_meta
6434
    // store tmp_rowset id and meta for statistics rs size when delete
6435
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6436
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6437
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6438
37
    worker_pool->start();
6439
6440
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6441
6442
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6443
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6444
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6445
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6446
53.2k
                                    std::string_view k, std::string_view v) -> int {
6447
53.2k
        ++num_scanned;
6448
53.2k
        total_rowset_key_size += k.size();
6449
53.2k
        total_rowset_value_size += v.size();
6450
53.2k
        doris::RowsetMetaCloudPB rowset;
6451
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6452
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6453
0
            return -1;
6454
0
        }
6455
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6456
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6457
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6458
0
                   << " txn_expiration=" << rowset.txn_expiration()
6459
0
                   << " rowset_creation_time=" << rowset.creation_time();
6460
53.2k
        int64_t current_time = ::time(nullptr);
6461
53.2k
        if (current_time < expiration) { // not expired
6462
0
            return 0;
6463
0
        }
6464
53.2k
        ++num_expired;
6465
53.2k
        expired_rowset_size += v.size();
6466
53.2k
        if (!rowset.has_resource_id()) {
6467
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6468
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6469
0
                return -1;
6470
0
            }
6471
            // might be a delete pred rowset
6472
0
            tmp_rowset_keys.emplace_back(k);
6473
0
            return 0;
6474
0
        }
6475
6476
        // TODO(plat1ko): check rowset not referenced
6477
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6478
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6479
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6480
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6481
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6482
53.2k
                  << " num_expired=" << num_expired
6483
53.2k
                  << " task_type=" << metrics_context.operation_type;
6484
6485
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6486
16
            if (need_mark_rowset_as_recycled(rowset)) {
6487
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6488
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6489
9
                             "at next turn, instance_id="
6490
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6491
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6492
9
                return 0;
6493
9
            }
6494
16
        }
6495
6496
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6497
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6498
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6499
261
                             "instance_id="
6500
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6501
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6502
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6503
261
                return 0;
6504
261
            }
6505
265
        }
6506
6507
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6508
        // Remove the rowset ref count key directly since it has not been used.
6509
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6510
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6511
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6512
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6513
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6514
6515
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6516
53.0k
        return 0;
6517
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6446
16
                                    std::string_view k, std::string_view v) -> int {
6447
16
        ++num_scanned;
6448
16
        total_rowset_key_size += k.size();
6449
16
        total_rowset_value_size += v.size();
6450
16
        doris::RowsetMetaCloudPB rowset;
6451
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6452
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6453
0
            return -1;
6454
0
        }
6455
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6456
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6457
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6458
0
                   << " txn_expiration=" << rowset.txn_expiration()
6459
0
                   << " rowset_creation_time=" << rowset.creation_time();
6460
16
        int64_t current_time = ::time(nullptr);
6461
16
        if (current_time < expiration) { // not expired
6462
0
            return 0;
6463
0
        }
6464
16
        ++num_expired;
6465
16
        expired_rowset_size += v.size();
6466
16
        if (!rowset.has_resource_id()) {
6467
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6468
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6469
0
                return -1;
6470
0
            }
6471
            // might be a delete pred rowset
6472
0
            tmp_rowset_keys.emplace_back(k);
6473
0
            return 0;
6474
0
        }
6475
6476
        // TODO(plat1ko): check rowset not referenced
6477
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6478
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6479
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6480
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6481
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6482
16
                  << " num_expired=" << num_expired
6483
16
                  << " task_type=" << metrics_context.operation_type;
6484
6485
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6486
16
            if (need_mark_rowset_as_recycled(rowset)) {
6487
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6488
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6489
9
                             "at next turn, instance_id="
6490
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6491
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6492
9
                return 0;
6493
9
            }
6494
16
        }
6495
6496
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6497
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6498
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6499
3
                             "instance_id="
6500
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6501
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6502
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6503
3
                return 0;
6504
3
            }
6505
7
        }
6506
6507
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6508
        // Remove the rowset ref count key directly since it has not been used.
6509
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6510
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6511
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6512
4
                  << "key=" << hex(rowset_ref_count_key);
6513
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6514
6515
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6516
4
        return 0;
6517
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6446
53.2k
                                    std::string_view k, std::string_view v) -> int {
6447
53.2k
        ++num_scanned;
6448
53.2k
        total_rowset_key_size += k.size();
6449
53.2k
        total_rowset_value_size += v.size();
6450
53.2k
        doris::RowsetMetaCloudPB rowset;
6451
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6452
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6453
0
            return -1;
6454
0
        }
6455
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6456
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6457
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6458
0
                   << " txn_expiration=" << rowset.txn_expiration()
6459
0
                   << " rowset_creation_time=" << rowset.creation_time();
6460
53.2k
        int64_t current_time = ::time(nullptr);
6461
53.2k
        if (current_time < expiration) { // not expired
6462
0
            return 0;
6463
0
        }
6464
53.2k
        ++num_expired;
6465
53.2k
        expired_rowset_size += v.size();
6466
53.2k
        if (!rowset.has_resource_id()) {
6467
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6468
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6469
0
                return -1;
6470
0
            }
6471
            // might be a delete pred rowset
6472
0
            tmp_rowset_keys.emplace_back(k);
6473
0
            return 0;
6474
0
        }
6475
6476
        // TODO(plat1ko): check rowset not referenced
6477
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6478
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6479
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6480
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6481
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6482
53.2k
                  << " num_expired=" << num_expired
6483
53.2k
                  << " task_type=" << metrics_context.operation_type;
6484
6485
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6486
0
            if (need_mark_rowset_as_recycled(rowset)) {
6487
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6488
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6489
0
                             "at next turn, instance_id="
6490
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6491
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6492
0
                return 0;
6493
0
            }
6494
0
        }
6495
6496
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6497
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6498
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6499
258
                             "instance_id="
6500
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6501
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6502
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6503
258
                return 0;
6504
258
            }
6505
258
        }
6506
6507
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6508
        // Remove the rowset ref count key directly since it has not been used.
6509
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6510
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6511
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6512
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6513
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6514
6515
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6516
53.0k
        return 0;
6517
53.2k
    };
6518
6519
37
    auto loop_done = [&]() -> int {
6520
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6521
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6522
24
        std::vector<std::string> mark_keys_to_process;
6523
24
        std::vector<std::string> abort_keys_to_process;
6524
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6525
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6526
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6527
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6528
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6529
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6530
24
        if (!mark_keys_to_process.empty()) {
6531
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6532
7
                    *worker_pool, std::move(mark_keys_to_process));
6533
7
        }
6534
24
        if (!abort_keys_to_process.empty()) {
6535
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6536
5
                                           &num_recycled, &metrics_context);
6537
5
        }
6538
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6539
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6540
24
                             tmp_rowset_ref_count_keys_to_delete =
6541
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6542
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6543
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6544
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6545
24
                                   metrics_context) != 0) {
6546
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6547
2
                return;
6548
2
            }
6549
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6550
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6551
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6552
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6553
0
                                 << rs.ShortDebugString();
6554
0
                    return;
6555
0
                }
6556
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6557
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6558
0
                                 << rs.ShortDebugString();
6559
0
                    return;
6560
0
                }
6561
51.0k
            }
6562
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6563
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6564
0
                return;
6565
0
            }
6566
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6567
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6568
0
                return;
6569
0
            }
6570
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6571
22
            return;
6572
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6543
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6544
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6545
12
                                   metrics_context) != 0) {
6546
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6547
0
                return;
6548
0
            }
6549
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6550
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6551
4
                                                       rs.rowset_id_v2()) != 0) {
6552
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6553
0
                                 << rs.ShortDebugString();
6554
0
                    return;
6555
0
                }
6556
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6557
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6558
0
                                 << rs.ShortDebugString();
6559
0
                    return;
6560
0
                }
6561
4
            }
6562
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6563
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6564
0
                return;
6565
0
            }
6566
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6567
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6568
0
                return;
6569
0
            }
6570
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6571
12
            return;
6572
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6543
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6544
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6545
12
                                   metrics_context) != 0) {
6546
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6547
2
                return;
6548
2
            }
6549
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6550
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6551
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6552
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6553
0
                                 << rs.ShortDebugString();
6554
0
                    return;
6555
0
                }
6556
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6557
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6558
0
                                 << rs.ShortDebugString();
6559
0
                    return;
6560
0
                }
6561
51.0k
            }
6562
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6563
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6564
0
                return;
6565
0
            }
6566
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6567
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6568
0
                return;
6569
0
            }
6570
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6571
10
            return;
6572
10
        });
6573
24
        return 0;
6574
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6519
12
    auto loop_done = [&]() -> int {
6520
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6521
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6522
12
        std::vector<std::string> mark_keys_to_process;
6523
12
        std::vector<std::string> abort_keys_to_process;
6524
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6525
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6526
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6527
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6528
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6529
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6530
12
        if (!mark_keys_to_process.empty()) {
6531
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6532
7
                    *worker_pool, std::move(mark_keys_to_process));
6533
7
        }
6534
12
        if (!abort_keys_to_process.empty()) {
6535
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6536
3
                                           &num_recycled, &metrics_context);
6537
3
        }
6538
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6539
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6540
12
                             tmp_rowset_ref_count_keys_to_delete =
6541
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6542
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6543
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6544
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6545
12
                                   metrics_context) != 0) {
6546
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6547
12
                return;
6548
12
            }
6549
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6550
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6551
12
                                                       rs.rowset_id_v2()) != 0) {
6552
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6553
12
                                 << rs.ShortDebugString();
6554
12
                    return;
6555
12
                }
6556
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6557
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6558
12
                                 << rs.ShortDebugString();
6559
12
                    return;
6560
12
                }
6561
12
            }
6562
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6563
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6564
12
                return;
6565
12
            }
6566
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6567
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6568
12
                return;
6569
12
            }
6570
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6571
12
            return;
6572
12
        });
6573
12
        return 0;
6574
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6519
12
    auto loop_done = [&]() -> int {
6520
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6521
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6522
12
        std::vector<std::string> mark_keys_to_process;
6523
12
        std::vector<std::string> abort_keys_to_process;
6524
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6525
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6526
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6527
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6528
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6529
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6530
12
        if (!mark_keys_to_process.empty()) {
6531
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6532
0
                    *worker_pool, std::move(mark_keys_to_process));
6533
0
        }
6534
12
        if (!abort_keys_to_process.empty()) {
6535
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6536
2
                                           &num_recycled, &metrics_context);
6537
2
        }
6538
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6539
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6540
12
                             tmp_rowset_ref_count_keys_to_delete =
6541
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6542
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6543
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6544
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6545
12
                                   metrics_context) != 0) {
6546
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6547
12
                return;
6548
12
            }
6549
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6550
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6551
12
                                                       rs.rowset_id_v2()) != 0) {
6552
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6553
12
                                 << rs.ShortDebugString();
6554
12
                    return;
6555
12
                }
6556
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6557
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6558
12
                                 << rs.ShortDebugString();
6559
12
                    return;
6560
12
                }
6561
12
            }
6562
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6563
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6564
12
                return;
6565
12
            }
6566
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6567
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6568
12
                return;
6569
12
            }
6570
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6571
12
            return;
6572
12
        });
6573
12
        return 0;
6574
12
    };
6575
6576
37
    if (config::enable_recycler_stats_metrics) {
6577
0
        scan_and_statistics_tmp_rowsets();
6578
0
    }
6579
    // recycle_func and loop_done for scan and recycle
6580
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6581
37
                               std::move(loop_done));
6582
6583
37
    worker_pool->stop();
6584
6585
    // Report final metrics after all concurrent tasks completed
6586
37
    segment_metrics_context_.report();
6587
37
    metrics_context.report();
6588
6589
37
    return ret;
6590
37
}
6591
6592
int InstanceRecycler::scan_and_recycle(
6593
        std::string begin, std::string_view end,
6594
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6595
315
        std::function<int()> loop_done) {
6596
315
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6597
315
    int ret = 0;
6598
315
    int64_t cnt = 0;
6599
315
    int get_range_retried = 0;
6600
315
    std::string err;
6601
316
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6602
316
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6603
316
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6604
316
                  << " ret=" << ret << " err=" << err;
6605
316
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6601
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6602
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6603
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6604
31
                  << " ret=" << ret << " err=" << err;
6605
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6601
285
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6602
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6603
285
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6604
285
                  << " ret=" << ret << " err=" << err;
6605
285
    };
6606
6607
315
    std::unique_ptr<RangeGetIterator> it;
6608
843
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6609
673
        if (get_range_retried > 1000) {
6610
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6611
0
            ret = -3;
6612
0
            return ret;
6613
0
        }
6614
673
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6615
673
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6616
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6617
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6618
0
                         << " get_range_retried=" << get_range_retried;
6619
0
            ++get_range_retried;
6620
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6621
0
            continue; // try again
6622
0
        }
6623
673
        if (!it->has_next()) {
6624
145
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6625
145
            break; // scan finished
6626
145
        }
6627
238k
        while (it->has_next()) {
6628
237k
            ++cnt;
6629
            // recycle corresponding resources
6630
237k
            auto [k, v] = it->next();
6631
237k
            if (!it->has_next()) {
6632
528
                begin = k;
6633
528
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6634
528
            }
6635
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6636
237k
            if (recycle_func(k, v) != 0) {
6637
4.00k
                err = "recycle_func error";
6638
4.00k
                ret = -1;
6639
4.00k
            }
6640
237k
        }
6641
528
        begin.push_back('\x00'); // Update to next smallest key for iteration
6642
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6643
528
        if (loop_done && loop_done() != 0) {
6644
9
            err = "loop_done error";
6645
9
            ret = -1;
6646
9
        }
6647
528
    }
6648
315
    return ret;
6649
315
}
6650
6651
19
int InstanceRecycler::abort_timeout_txn() {
6652
19
    const std::string task_name = "abort_timeout_txn";
6653
19
    int64_t num_scanned = 0;
6654
19
    int64_t num_timeout = 0;
6655
19
    int64_t num_abort = 0;
6656
19
    int64_t num_advance = 0;
6657
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6658
6659
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6660
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6661
19
    std::string begin_txn_running_key;
6662
19
    std::string end_txn_running_key;
6663
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6664
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6665
6666
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6667
6668
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6669
19
    register_recycle_task(task_name, start_time);
6670
6671
19
    DORIS_CLOUD_DEFER {
6672
19
        unregister_recycle_task(task_name);
6673
19
        int64_t cost =
6674
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6675
19
        metrics_context.finish_report();
6676
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6677
19
                .tag("instance_id", instance_id_)
6678
19
                .tag("num_scanned", num_scanned)
6679
19
                .tag("num_timeout", num_timeout)
6680
19
                .tag("num_abort", num_abort)
6681
19
                .tag("num_advance", num_advance);
6682
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6671
3
    DORIS_CLOUD_DEFER {
6672
3
        unregister_recycle_task(task_name);
6673
3
        int64_t cost =
6674
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6675
3
        metrics_context.finish_report();
6676
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6677
3
                .tag("instance_id", instance_id_)
6678
3
                .tag("num_scanned", num_scanned)
6679
3
                .tag("num_timeout", num_timeout)
6680
3
                .tag("num_abort", num_abort)
6681
3
                .tag("num_advance", num_advance);
6682
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6671
16
    DORIS_CLOUD_DEFER {
6672
16
        unregister_recycle_task(task_name);
6673
16
        int64_t cost =
6674
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6675
16
        metrics_context.finish_report();
6676
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6677
16
                .tag("instance_id", instance_id_)
6678
16
                .tag("num_scanned", num_scanned)
6679
16
                .tag("num_timeout", num_timeout)
6680
16
                .tag("num_abort", num_abort)
6681
16
                .tag("num_advance", num_advance);
6682
16
    };
6683
6684
19
    int64_t current_time =
6685
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6686
6687
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6688
19
                                  &current_time, &metrics_context,
6689
19
                                  this](std::string_view k, std::string_view v) -> int {
6690
9
        ++num_scanned;
6691
6692
9
        std::unique_ptr<Transaction> txn;
6693
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6694
9
        if (err != TxnErrorCode::TXN_OK) {
6695
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6696
0
            return -1;
6697
0
        }
6698
9
        std::string_view k1 = k;
6699
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6700
9
        k1.remove_prefix(1); // Remove key space
6701
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6702
9
        if (decode_key(&k1, &out) != 0) {
6703
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6704
0
            return -1;
6705
0
        }
6706
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6707
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6708
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6709
        // Update txn_info
6710
9
        std::string txn_inf_key, txn_inf_val;
6711
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6712
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6713
9
        if (err != TxnErrorCode::TXN_OK) {
6714
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6715
0
            return -1;
6716
0
        }
6717
9
        TxnInfoPB txn_info;
6718
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6719
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6720
0
            return -1;
6721
0
        }
6722
6723
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6724
3
            txn.reset();
6725
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6726
3
            std::shared_ptr<TxnLazyCommitTask> task =
6727
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6728
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6729
3
            if (ret.first != MetaServiceCode::OK) {
6730
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6731
0
                             << "msg=" << ret.second;
6732
0
                return -1;
6733
0
            }
6734
3
            ++num_advance;
6735
3
            return 0;
6736
6
        } else {
6737
6
            TxnRunningPB txn_running_pb;
6738
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6739
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6740
0
                return -1;
6741
0
            }
6742
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6743
4
                return 0;
6744
4
            }
6745
2
            ++num_timeout;
6746
6747
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6748
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6749
2
            txn_info.set_finish_time(current_time);
6750
2
            txn_info.set_reason("timeout");
6751
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6752
2
            txn_inf_val.clear();
6753
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6754
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6755
0
                return -1;
6756
0
            }
6757
2
            txn->put(txn_inf_key, txn_inf_val);
6758
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6759
            // Put recycle txn key
6760
2
            std::string recyc_txn_key, recyc_txn_val;
6761
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6762
2
            RecycleTxnPB recycle_txn_pb;
6763
2
            recycle_txn_pb.set_creation_time(current_time);
6764
2
            recycle_txn_pb.set_label(txn_info.label());
6765
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6766
0
                LOG_WARNING("failed to serialize txn recycle info")
6767
0
                        .tag("key", hex(k))
6768
0
                        .tag("db_id", db_id)
6769
0
                        .tag("txn_id", txn_id);
6770
0
                return -1;
6771
0
            }
6772
2
            txn->put(recyc_txn_key, recyc_txn_val);
6773
            // Remove txn running key
6774
2
            txn->remove(k);
6775
2
            err = txn->commit();
6776
2
            if (err != TxnErrorCode::TXN_OK) {
6777
0
                LOG_WARNING("failed to commit txn err={}", err)
6778
0
                        .tag("key", hex(k))
6779
0
                        .tag("db_id", db_id)
6780
0
                        .tag("txn_id", txn_id);
6781
0
                return -1;
6782
0
            }
6783
2
            metrics_context.total_recycled_num = ++num_abort;
6784
2
            metrics_context.report();
6785
2
        }
6786
6787
2
        return 0;
6788
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6689
3
                                  this](std::string_view k, std::string_view v) -> int {
6690
3
        ++num_scanned;
6691
6692
3
        std::unique_ptr<Transaction> txn;
6693
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6694
3
        if (err != TxnErrorCode::TXN_OK) {
6695
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6696
0
            return -1;
6697
0
        }
6698
3
        std::string_view k1 = k;
6699
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6700
3
        k1.remove_prefix(1); // Remove key space
6701
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6702
3
        if (decode_key(&k1, &out) != 0) {
6703
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6704
0
            return -1;
6705
0
        }
6706
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6707
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6708
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6709
        // Update txn_info
6710
3
        std::string txn_inf_key, txn_inf_val;
6711
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6712
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6713
3
        if (err != TxnErrorCode::TXN_OK) {
6714
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6715
0
            return -1;
6716
0
        }
6717
3
        TxnInfoPB txn_info;
6718
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6719
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6720
0
            return -1;
6721
0
        }
6722
6723
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6724
3
            txn.reset();
6725
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6726
3
            std::shared_ptr<TxnLazyCommitTask> task =
6727
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6728
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6729
3
            if (ret.first != MetaServiceCode::OK) {
6730
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6731
0
                             << "msg=" << ret.second;
6732
0
                return -1;
6733
0
            }
6734
3
            ++num_advance;
6735
3
            return 0;
6736
3
        } else {
6737
0
            TxnRunningPB txn_running_pb;
6738
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6739
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6740
0
                return -1;
6741
0
            }
6742
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6743
0
                return 0;
6744
0
            }
6745
0
            ++num_timeout;
6746
6747
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6748
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6749
0
            txn_info.set_finish_time(current_time);
6750
0
            txn_info.set_reason("timeout");
6751
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6752
0
            txn_inf_val.clear();
6753
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6754
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6755
0
                return -1;
6756
0
            }
6757
0
            txn->put(txn_inf_key, txn_inf_val);
6758
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6759
            // Put recycle txn key
6760
0
            std::string recyc_txn_key, recyc_txn_val;
6761
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6762
0
            RecycleTxnPB recycle_txn_pb;
6763
0
            recycle_txn_pb.set_creation_time(current_time);
6764
0
            recycle_txn_pb.set_label(txn_info.label());
6765
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6766
0
                LOG_WARNING("failed to serialize txn recycle info")
6767
0
                        .tag("key", hex(k))
6768
0
                        .tag("db_id", db_id)
6769
0
                        .tag("txn_id", txn_id);
6770
0
                return -1;
6771
0
            }
6772
0
            txn->put(recyc_txn_key, recyc_txn_val);
6773
            // Remove txn running key
6774
0
            txn->remove(k);
6775
0
            err = txn->commit();
6776
0
            if (err != TxnErrorCode::TXN_OK) {
6777
0
                LOG_WARNING("failed to commit txn err={}", err)
6778
0
                        .tag("key", hex(k))
6779
0
                        .tag("db_id", db_id)
6780
0
                        .tag("txn_id", txn_id);
6781
0
                return -1;
6782
0
            }
6783
0
            metrics_context.total_recycled_num = ++num_abort;
6784
0
            metrics_context.report();
6785
0
        }
6786
6787
0
        return 0;
6788
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6689
6
                                  this](std::string_view k, std::string_view v) -> int {
6690
6
        ++num_scanned;
6691
6692
6
        std::unique_ptr<Transaction> txn;
6693
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6694
6
        if (err != TxnErrorCode::TXN_OK) {
6695
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6696
0
            return -1;
6697
0
        }
6698
6
        std::string_view k1 = k;
6699
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6700
6
        k1.remove_prefix(1); // Remove key space
6701
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6702
6
        if (decode_key(&k1, &out) != 0) {
6703
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6704
0
            return -1;
6705
0
        }
6706
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6707
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6708
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6709
        // Update txn_info
6710
6
        std::string txn_inf_key, txn_inf_val;
6711
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6712
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6713
6
        if (err != TxnErrorCode::TXN_OK) {
6714
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6715
0
            return -1;
6716
0
        }
6717
6
        TxnInfoPB txn_info;
6718
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6719
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6720
0
            return -1;
6721
0
        }
6722
6723
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6724
0
            txn.reset();
6725
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6726
0
            std::shared_ptr<TxnLazyCommitTask> task =
6727
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6728
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6729
0
            if (ret.first != MetaServiceCode::OK) {
6730
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6731
0
                             << "msg=" << ret.second;
6732
0
                return -1;
6733
0
            }
6734
0
            ++num_advance;
6735
0
            return 0;
6736
6
        } else {
6737
6
            TxnRunningPB txn_running_pb;
6738
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6739
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6740
0
                return -1;
6741
0
            }
6742
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6743
4
                return 0;
6744
4
            }
6745
2
            ++num_timeout;
6746
6747
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6748
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6749
2
            txn_info.set_finish_time(current_time);
6750
2
            txn_info.set_reason("timeout");
6751
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6752
2
            txn_inf_val.clear();
6753
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6754
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6755
0
                return -1;
6756
0
            }
6757
2
            txn->put(txn_inf_key, txn_inf_val);
6758
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6759
            // Put recycle txn key
6760
2
            std::string recyc_txn_key, recyc_txn_val;
6761
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6762
2
            RecycleTxnPB recycle_txn_pb;
6763
2
            recycle_txn_pb.set_creation_time(current_time);
6764
2
            recycle_txn_pb.set_label(txn_info.label());
6765
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6766
0
                LOG_WARNING("failed to serialize txn recycle info")
6767
0
                        .tag("key", hex(k))
6768
0
                        .tag("db_id", db_id)
6769
0
                        .tag("txn_id", txn_id);
6770
0
                return -1;
6771
0
            }
6772
2
            txn->put(recyc_txn_key, recyc_txn_val);
6773
            // Remove txn running key
6774
2
            txn->remove(k);
6775
2
            err = txn->commit();
6776
2
            if (err != TxnErrorCode::TXN_OK) {
6777
0
                LOG_WARNING("failed to commit txn err={}", err)
6778
0
                        .tag("key", hex(k))
6779
0
                        .tag("db_id", db_id)
6780
0
                        .tag("txn_id", txn_id);
6781
0
                return -1;
6782
0
            }
6783
2
            metrics_context.total_recycled_num = ++num_abort;
6784
2
            metrics_context.report();
6785
2
        }
6786
6787
2
        return 0;
6788
6
    };
6789
6790
19
    if (config::enable_recycler_stats_metrics) {
6791
0
        scan_and_statistics_abort_timeout_txn();
6792
0
    }
6793
    // recycle_func and loop_done for scan and recycle
6794
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6795
19
                            std::move(handle_txn_running_kv));
6796
19
}
6797
6798
22
int InstanceRecycler::recycle_expired_txn_label() {
6799
22
    const std::string task_name = "recycle_expired_txn_label";
6800
22
    int64_t num_scanned = 0;
6801
22
    int64_t num_expired = 0;
6802
22
    std::atomic_long num_recycled = 0;
6803
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6804
22
    int ret = 0;
6805
6806
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6807
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6808
22
    std::string begin_recycle_txn_key;
6809
22
    std::string end_recycle_txn_key;
6810
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6811
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6812
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
6813
6814
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6815
6816
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6817
22
    register_recycle_task(task_name, start_time);
6818
22
    DORIS_CLOUD_DEFER {
6819
22
        unregister_recycle_task(task_name);
6820
22
        int64_t cost =
6821
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6822
22
        metrics_context.finish_report();
6823
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6824
22
                .tag("instance_id", instance_id_)
6825
22
                .tag("num_scanned", num_scanned)
6826
22
                .tag("num_expired", num_expired)
6827
22
                .tag("num_recycled", num_recycled);
6828
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6818
1
    DORIS_CLOUD_DEFER {
6819
1
        unregister_recycle_task(task_name);
6820
1
        int64_t cost =
6821
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6822
1
        metrics_context.finish_report();
6823
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6824
1
                .tag("instance_id", instance_id_)
6825
1
                .tag("num_scanned", num_scanned)
6826
1
                .tag("num_expired", num_expired)
6827
1
                .tag("num_recycled", num_recycled);
6828
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6818
21
    DORIS_CLOUD_DEFER {
6819
21
        unregister_recycle_task(task_name);
6820
21
        int64_t cost =
6821
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6822
21
        metrics_context.finish_report();
6823
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6824
21
                .tag("instance_id", instance_id_)
6825
21
                .tag("num_scanned", num_scanned)
6826
21
                .tag("num_expired", num_expired)
6827
21
                .tag("num_recycled", num_recycled);
6828
21
    };
6829
6830
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6831
6832
22
    SyncExecutor<int> concurrent_delete_executor(
6833
22
            _thread_pool_group.s3_producer_pool,
6834
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6835
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6835
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6835
38.0k
            [](const int& ret) { return ret != 0; });
6836
6837
22
    int64_t current_time_ms =
6838
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6839
6840
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6841
50.0k
        ++num_scanned;
6842
50.0k
        RecycleTxnPB recycle_txn_pb;
6843
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6844
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6845
0
            return -1;
6846
0
        }
6847
50.0k
        if ((config::force_immediate_recycle) ||
6848
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6849
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6850
50.0k
             current_time_ms)) {
6851
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6852
38.0k
            num_expired++;
6853
6854
38.0k
            std::string_view k1 = k;
6855
38.0k
            k1.remove_prefix(1); // Remove key space
6856
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6857
38.0k
            if (decode_key(&k1, &out) != 0) {
6858
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6859
0
                return -1;
6860
0
            }
6861
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6862
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6863
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6864
38.0k
        }
6865
50.0k
        return 0;
6866
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6840
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6841
1
        ++num_scanned;
6842
1
        RecycleTxnPB recycle_txn_pb;
6843
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6844
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6845
0
            return -1;
6846
0
        }
6847
1
        if ((config::force_immediate_recycle) ||
6848
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6849
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6850
1
             current_time_ms)) {
6851
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6852
1
            num_expired++;
6853
6854
1
            std::string_view k1 = k;
6855
1
            k1.remove_prefix(1); // Remove key space
6856
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6857
1
            if (decode_key(&k1, &out) != 0) {
6858
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6859
0
                return -1;
6860
0
            }
6861
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6862
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6863
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6864
1
        }
6865
1
        return 0;
6866
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6840
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6841
50.0k
        ++num_scanned;
6842
50.0k
        RecycleTxnPB recycle_txn_pb;
6843
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6844
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6845
0
            return -1;
6846
0
        }
6847
50.0k
        if ((config::force_immediate_recycle) ||
6848
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6849
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6850
50.0k
             current_time_ms)) {
6851
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6852
38.0k
            num_expired++;
6853
6854
38.0k
            std::string_view k1 = k;
6855
38.0k
            k1.remove_prefix(1); // Remove key space
6856
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6857
38.0k
            if (decode_key(&k1, &out) != 0) {
6858
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6859
0
                return -1;
6860
0
            }
6861
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6862
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6863
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6864
38.0k
        }
6865
50.0k
        return 0;
6866
50.0k
    };
6867
6868
    // int 0 for success, 1 for conflict, -1 for error
6869
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6870
38.0k
        std::string_view k1 = k;
6871
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6872
38.0k
        k1.remove_prefix(1); // Remove key space
6873
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6874
38.0k
        int ret = decode_key(&k1, &out);
6875
38.0k
        if (ret != 0) {
6876
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6877
0
            return -1;
6878
0
        }
6879
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6880
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6881
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6882
38.0k
        std::unique_ptr<Transaction> txn;
6883
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6884
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6885
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6886
0
            return -1;
6887
0
        }
6888
        // Remove txn index kv
6889
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6890
38.0k
        txn->remove(index_key);
6891
        // Remove txn info kv
6892
38.0k
        std::string info_key, info_val;
6893
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6894
38.0k
        err = txn->get(info_key, &info_val);
6895
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6896
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6897
0
            return -1;
6898
0
        }
6899
38.0k
        TxnInfoPB txn_info;
6900
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6901
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6902
0
            return -1;
6903
0
        }
6904
38.0k
        txn->remove(info_key);
6905
        // Remove sub txn index kvs
6906
38.0k
        std::vector<std::string> sub_txn_index_keys;
6907
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6908
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6909
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6910
38.0k
        }
6911
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6912
37.9k
            txn->remove(sub_txn_index_key);
6913
37.9k
        }
6914
        // Update txn label
6915
38.0k
        std::string label_key, label_val;
6916
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6917
38.0k
        err = txn->get(label_key, &label_val);
6918
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6920
0
                         << " err=" << err;
6921
0
            return -1;
6922
0
        }
6923
38.0k
        TxnLabelPB txn_label;
6924
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6925
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6926
0
            return -1;
6927
0
        }
6928
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6929
38.0k
        if (it != txn_label.txn_ids().end()) {
6930
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6931
38.0k
        }
6932
38.0k
        if (txn_label.txn_ids().empty()) {
6933
38.0k
            txn->remove(label_key);
6934
38.0k
            TEST_SYNC_POINT_CALLBACK(
6935
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6936
38.0k
        } else {
6937
11
            if (!txn_label.SerializeToString(&label_val)) {
6938
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6939
0
                return -1;
6940
0
            }
6941
11
            TEST_SYNC_POINT_CALLBACK(
6942
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6943
11
            txn->atomic_set_ver_value(label_key, label_val);
6944
11
            TEST_SYNC_POINT_CALLBACK(
6945
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6946
11
        }
6947
        // Remove recycle txn kv
6948
38.0k
        txn->remove(k);
6949
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6950
38.0k
        err = txn->commit();
6951
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6952
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6953
4
                TEST_SYNC_POINT_CALLBACK(
6954
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6955
                // log the txn_id and label
6956
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6957
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6958
4
                             << " txn_label=" << txn_info.label();
6959
4
                return 1;
6960
4
            }
6961
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6962
0
            return -1;
6963
4
        }
6964
38.0k
        ++num_recycled;
6965
6966
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6967
38.0k
        return 0;
6968
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6869
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6870
1
        std::string_view k1 = k;
6871
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6872
1
        k1.remove_prefix(1); // Remove key space
6873
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6874
1
        int ret = decode_key(&k1, &out);
6875
1
        if (ret != 0) {
6876
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6877
0
            return -1;
6878
0
        }
6879
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6880
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6881
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6882
1
        std::unique_ptr<Transaction> txn;
6883
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6884
1
        if (err != TxnErrorCode::TXN_OK) {
6885
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6886
0
            return -1;
6887
0
        }
6888
        // Remove txn index kv
6889
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6890
1
        txn->remove(index_key);
6891
        // Remove txn info kv
6892
1
        std::string info_key, info_val;
6893
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6894
1
        err = txn->get(info_key, &info_val);
6895
1
        if (err != TxnErrorCode::TXN_OK) {
6896
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6897
0
            return -1;
6898
0
        }
6899
1
        TxnInfoPB txn_info;
6900
1
        if (!txn_info.ParseFromString(info_val)) {
6901
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6902
0
            return -1;
6903
0
        }
6904
1
        txn->remove(info_key);
6905
        // Remove sub txn index kvs
6906
1
        std::vector<std::string> sub_txn_index_keys;
6907
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6908
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6909
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6910
0
        }
6911
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6912
0
            txn->remove(sub_txn_index_key);
6913
0
        }
6914
        // Update txn label
6915
1
        std::string label_key, label_val;
6916
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6917
1
        err = txn->get(label_key, &label_val);
6918
1
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6920
0
                         << " err=" << err;
6921
0
            return -1;
6922
0
        }
6923
1
        TxnLabelPB txn_label;
6924
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6925
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6926
0
            return -1;
6927
0
        }
6928
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6929
1
        if (it != txn_label.txn_ids().end()) {
6930
1
            txn_label.mutable_txn_ids()->erase(it);
6931
1
        }
6932
1
        if (txn_label.txn_ids().empty()) {
6933
1
            txn->remove(label_key);
6934
1
            TEST_SYNC_POINT_CALLBACK(
6935
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6936
1
        } else {
6937
0
            if (!txn_label.SerializeToString(&label_val)) {
6938
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6939
0
                return -1;
6940
0
            }
6941
0
            TEST_SYNC_POINT_CALLBACK(
6942
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6943
0
            txn->atomic_set_ver_value(label_key, label_val);
6944
0
            TEST_SYNC_POINT_CALLBACK(
6945
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6946
0
        }
6947
        // Remove recycle txn kv
6948
1
        txn->remove(k);
6949
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6950
1
        err = txn->commit();
6951
1
        if (err != TxnErrorCode::TXN_OK) {
6952
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6953
0
                TEST_SYNC_POINT_CALLBACK(
6954
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6955
                // log the txn_id and label
6956
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6957
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6958
0
                             << " txn_label=" << txn_info.label();
6959
0
                return 1;
6960
0
            }
6961
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6962
0
            return -1;
6963
0
        }
6964
1
        ++num_recycled;
6965
6966
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6967
1
        return 0;
6968
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6869
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6870
38.0k
        std::string_view k1 = k;
6871
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6872
38.0k
        k1.remove_prefix(1); // Remove key space
6873
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6874
38.0k
        int ret = decode_key(&k1, &out);
6875
38.0k
        if (ret != 0) {
6876
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6877
0
            return -1;
6878
0
        }
6879
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6880
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6881
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6882
38.0k
        std::unique_ptr<Transaction> txn;
6883
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6884
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6885
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6886
0
            return -1;
6887
0
        }
6888
        // Remove txn index kv
6889
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6890
38.0k
        txn->remove(index_key);
6891
        // Remove txn info kv
6892
38.0k
        std::string info_key, info_val;
6893
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6894
38.0k
        err = txn->get(info_key, &info_val);
6895
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6896
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6897
0
            return -1;
6898
0
        }
6899
38.0k
        TxnInfoPB txn_info;
6900
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6901
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6902
0
            return -1;
6903
0
        }
6904
38.0k
        txn->remove(info_key);
6905
        // Remove sub txn index kvs
6906
38.0k
        std::vector<std::string> sub_txn_index_keys;
6907
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6908
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6909
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6910
38.0k
        }
6911
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6912
37.9k
            txn->remove(sub_txn_index_key);
6913
37.9k
        }
6914
        // Update txn label
6915
38.0k
        std::string label_key, label_val;
6916
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6917
38.0k
        err = txn->get(label_key, &label_val);
6918
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6920
0
                         << " err=" << err;
6921
0
            return -1;
6922
0
        }
6923
38.0k
        TxnLabelPB txn_label;
6924
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6925
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6926
0
            return -1;
6927
0
        }
6928
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6929
38.0k
        if (it != txn_label.txn_ids().end()) {
6930
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6931
38.0k
        }
6932
38.0k
        if (txn_label.txn_ids().empty()) {
6933
38.0k
            txn->remove(label_key);
6934
38.0k
            TEST_SYNC_POINT_CALLBACK(
6935
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6936
38.0k
        } else {
6937
11
            if (!txn_label.SerializeToString(&label_val)) {
6938
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6939
0
                return -1;
6940
0
            }
6941
11
            TEST_SYNC_POINT_CALLBACK(
6942
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6943
11
            txn->atomic_set_ver_value(label_key, label_val);
6944
11
            TEST_SYNC_POINT_CALLBACK(
6945
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6946
11
        }
6947
        // Remove recycle txn kv
6948
38.0k
        txn->remove(k);
6949
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6950
38.0k
        err = txn->commit();
6951
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6952
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6953
4
                TEST_SYNC_POINT_CALLBACK(
6954
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6955
                // log the txn_id and label
6956
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6957
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6958
4
                             << " txn_label=" << txn_info.label();
6959
4
                return 1;
6960
4
            }
6961
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6962
0
            return -1;
6963
4
        }
6964
38.0k
        ++num_recycled;
6965
6966
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6967
38.0k
        return 0;
6968
38.0k
    };
6969
6970
22
    auto loop_done = [&]() -> int {
6971
15
        DORIS_CLOUD_DEFER {
6972
15
            recycle_txn_keys_by_label.clear();
6973
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6971
1
        DORIS_CLOUD_DEFER {
6972
1
            recycle_txn_keys_by_label.clear();
6973
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6971
14
        DORIS_CLOUD_DEFER {
6972
14
            recycle_txn_keys_by_label.clear();
6973
14
        };
6974
15
        TEST_SYNC_POINT_CALLBACK(
6975
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6976
15
                &recycle_txn_keys_by_label);
6977
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6978
38.0k
            int ret = delete_recycle_txn_kv(k);
6979
38.0k
            TEST_SYNC_POINT_CALLBACK(
6980
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6981
38.0k
                    &ret);
6982
38.0k
            if (ret == 1) {
6983
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6984
4
                for (int i = 1; i <= max_retry; ++i) {
6985
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6986
3
                    ret = delete_recycle_txn_kv(k);
6987
3
                    TEST_SYNC_POINT_CALLBACK(
6988
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6989
3
                            "error",
6990
3
                            &ret);
6991
3
                    if (ret != 1) {
6992
1
                        break;
6993
1
                    }
6994
                    // random sleep 0-100 ms to retry
6995
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6996
2
                }
6997
2
            }
6998
38.0k
            return ret;
6999
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6977
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6978
1
            int ret = delete_recycle_txn_kv(k);
6979
1
            TEST_SYNC_POINT_CALLBACK(
6980
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6981
1
                    &ret);
6982
1
            if (ret == 1) {
6983
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6984
0
                for (int i = 1; i <= max_retry; ++i) {
6985
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6986
0
                    ret = delete_recycle_txn_kv(k);
6987
0
                    TEST_SYNC_POINT_CALLBACK(
6988
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6989
0
                            "error",
6990
0
                            &ret);
6991
0
                    if (ret != 1) {
6992
0
                        break;
6993
0
                    }
6994
                    // random sleep 0-100 ms to retry
6995
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6996
0
                }
6997
0
            }
6998
1
            return ret;
6999
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6977
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6978
38.0k
            int ret = delete_recycle_txn_kv(k);
6979
38.0k
            TEST_SYNC_POINT_CALLBACK(
6980
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6981
38.0k
                    &ret);
6982
38.0k
            if (ret == 1) {
6983
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6984
4
                for (int i = 1; i <= max_retry; ++i) {
6985
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6986
3
                    ret = delete_recycle_txn_kv(k);
6987
3
                    TEST_SYNC_POINT_CALLBACK(
6988
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6989
3
                            "error",
6990
3
                            &ret);
6991
3
                    if (ret != 1) {
6992
1
                        break;
6993
1
                    }
6994
                    // random sleep 0-100 ms to retry
6995
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6996
2
                }
6997
2
            }
6998
38.0k
            return ret;
6999
38.0k
        };
7000
7001
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7002
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7003
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7004
0
                           << " txn_count=" << txn_keys.size();
7005
38.0k
                for (const auto& k : txn_keys) {
7006
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7007
38.0k
                    if (ret != 0) {
7008
2
                        LOG_WARNING("failed to delete recycle txn kv")
7009
2
                                .tag("instance id", instance_id_)
7010
2
                                .tag("key", hex(k))
7011
2
                                .tag("label_key", hex(label_key));
7012
2
                        return -1;
7013
2
                    }
7014
38.0k
                }
7015
38.0k
                return 0;
7016
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7002
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7003
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7004
0
                           << " txn_count=" << txn_keys.size();
7005
1
                for (const auto& k : txn_keys) {
7006
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7007
1
                    if (ret != 0) {
7008
0
                        LOG_WARNING("failed to delete recycle txn kv")
7009
0
                                .tag("instance id", instance_id_)
7010
0
                                .tag("key", hex(k))
7011
0
                                .tag("label_key", hex(label_key));
7012
0
                        return -1;
7013
0
                    }
7014
1
                }
7015
1
                return 0;
7016
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7002
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7003
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7004
0
                           << " txn_count=" << txn_keys.size();
7005
38.0k
                for (const auto& k : txn_keys) {
7006
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7007
38.0k
                    if (ret != 0) {
7008
2
                        LOG_WARNING("failed to delete recycle txn kv")
7009
2
                                .tag("instance id", instance_id_)
7010
2
                                .tag("key", hex(k))
7011
2
                                .tag("label_key", hex(label_key));
7012
2
                        return -1;
7013
2
                    }
7014
38.0k
                }
7015
38.0k
                return 0;
7016
38.0k
            });
7017
38.0k
        }
7018
15
        bool finished = true;
7019
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7020
38.0k
        for (int r : rets) {
7021
38.0k
            if (r != 0) {
7022
2
                ret = -1;
7023
2
            }
7024
38.0k
        }
7025
7026
15
        ret = finished ? ret : -1;
7027
7028
        // Update metrics after all concurrent tasks completed
7029
15
        metrics_context.total_recycled_num = num_recycled.load();
7030
15
        metrics_context.report();
7031
7032
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7033
7034
15
        if (ret != 0) {
7035
6
            LOG_WARNING("recycle txn kv ret!=0")
7036
6
                    .tag("finished", finished)
7037
6
                    .tag("ret", ret)
7038
6
                    .tag("instance_id", instance_id_);
7039
6
            return ret;
7040
6
        }
7041
9
        return ret;
7042
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6970
1
    auto loop_done = [&]() -> int {
6971
1
        DORIS_CLOUD_DEFER {
6972
1
            recycle_txn_keys_by_label.clear();
6973
1
        };
6974
1
        TEST_SYNC_POINT_CALLBACK(
6975
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6976
1
                &recycle_txn_keys_by_label);
6977
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6978
1
            int ret = delete_recycle_txn_kv(k);
6979
1
            TEST_SYNC_POINT_CALLBACK(
6980
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6981
1
                    &ret);
6982
1
            if (ret == 1) {
6983
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6984
1
                for (int i = 1; i <= max_retry; ++i) {
6985
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6986
1
                    ret = delete_recycle_txn_kv(k);
6987
1
                    TEST_SYNC_POINT_CALLBACK(
6988
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6989
1
                            "error",
6990
1
                            &ret);
6991
1
                    if (ret != 1) {
6992
1
                        break;
6993
1
                    }
6994
                    // random sleep 0-100 ms to retry
6995
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6996
1
                }
6997
1
            }
6998
1
            return ret;
6999
1
        };
7000
7001
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7002
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7003
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7004
1
                           << " txn_count=" << txn_keys.size();
7005
1
                for (const auto& k : txn_keys) {
7006
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7007
1
                    if (ret != 0) {
7008
1
                        LOG_WARNING("failed to delete recycle txn kv")
7009
1
                                .tag("instance id", instance_id_)
7010
1
                                .tag("key", hex(k))
7011
1
                                .tag("label_key", hex(label_key));
7012
1
                        return -1;
7013
1
                    }
7014
1
                }
7015
1
                return 0;
7016
1
            });
7017
1
        }
7018
1
        bool finished = true;
7019
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7020
1
        for (int r : rets) {
7021
1
            if (r != 0) {
7022
0
                ret = -1;
7023
0
            }
7024
1
        }
7025
7026
1
        ret = finished ? ret : -1;
7027
7028
        // Update metrics after all concurrent tasks completed
7029
1
        metrics_context.total_recycled_num = num_recycled.load();
7030
1
        metrics_context.report();
7031
7032
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7033
7034
1
        if (ret != 0) {
7035
0
            LOG_WARNING("recycle txn kv ret!=0")
7036
0
                    .tag("finished", finished)
7037
0
                    .tag("ret", ret)
7038
0
                    .tag("instance_id", instance_id_);
7039
0
            return ret;
7040
0
        }
7041
1
        return ret;
7042
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6970
14
    auto loop_done = [&]() -> int {
6971
14
        DORIS_CLOUD_DEFER {
6972
14
            recycle_txn_keys_by_label.clear();
6973
14
        };
6974
14
        TEST_SYNC_POINT_CALLBACK(
6975
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6976
14
                &recycle_txn_keys_by_label);
6977
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6978
14
            int ret = delete_recycle_txn_kv(k);
6979
14
            TEST_SYNC_POINT_CALLBACK(
6980
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6981
14
                    &ret);
6982
14
            if (ret == 1) {
6983
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6984
14
                for (int i = 1; i <= max_retry; ++i) {
6985
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6986
14
                    ret = delete_recycle_txn_kv(k);
6987
14
                    TEST_SYNC_POINT_CALLBACK(
6988
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6989
14
                            "error",
6990
14
                            &ret);
6991
14
                    if (ret != 1) {
6992
14
                        break;
6993
14
                    }
6994
                    // random sleep 0-100 ms to retry
6995
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6996
14
                }
6997
14
            }
6998
14
            return ret;
6999
14
        };
7000
7001
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7002
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7003
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7004
38.0k
                           << " txn_count=" << txn_keys.size();
7005
38.0k
                for (const auto& k : txn_keys) {
7006
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7007
38.0k
                    if (ret != 0) {
7008
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7009
38.0k
                                .tag("instance id", instance_id_)
7010
38.0k
                                .tag("key", hex(k))
7011
38.0k
                                .tag("label_key", hex(label_key));
7012
38.0k
                        return -1;
7013
38.0k
                    }
7014
38.0k
                }
7015
38.0k
                return 0;
7016
38.0k
            });
7017
38.0k
        }
7018
14
        bool finished = true;
7019
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7020
38.0k
        for (int r : rets) {
7021
38.0k
            if (r != 0) {
7022
2
                ret = -1;
7023
2
            }
7024
38.0k
        }
7025
7026
14
        ret = finished ? ret : -1;
7027
7028
        // Update metrics after all concurrent tasks completed
7029
14
        metrics_context.total_recycled_num = num_recycled.load();
7030
14
        metrics_context.report();
7031
7032
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7033
7034
14
        if (ret != 0) {
7035
6
            LOG_WARNING("recycle txn kv ret!=0")
7036
6
                    .tag("finished", finished)
7037
6
                    .tag("ret", ret)
7038
6
                    .tag("instance_id", instance_id_);
7039
6
            return ret;
7040
6
        }
7041
8
        return ret;
7042
14
    };
7043
7044
22
    if (config::enable_recycler_stats_metrics) {
7045
0
        scan_and_statistics_expired_txn_label();
7046
0
    }
7047
    // recycle_func and loop_done for scan and recycle
7048
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7049
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7050
22
}
7051
7052
struct CopyJobIdTuple {
7053
    std::string instance_id;
7054
    std::string stage_id;
7055
    long table_id;
7056
    std::string copy_id;
7057
    std::string stage_path;
7058
};
7059
struct BatchObjStoreAccessor {
7060
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7061
                          TxnKv* txn_kv)
7062
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7063
3
    ~BatchObjStoreAccessor() {
7064
3
        if (!paths_.empty()) {
7065
3
            consume();
7066
3
        }
7067
3
    }
7068
7069
    /**
7070
    * To implicitely do batch work and submit the batch delete task to s3
7071
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7072
    *
7073
    * @param copy_job The protubuf struct consists of the copy job files.
7074
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7075
    *            it would last until we finish the delete task, here we need pass one string value
7076
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7077
    */
7078
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7079
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7080
5
        auto& file_keys = copy_file_keys_[key];
7081
5
        file_keys.log_trace =
7082
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7083
5
                            instance_id, stage_id, table_id, copy_id, path);
7084
5
        std::string_view log_trace = file_keys.log_trace;
7085
2.03k
        for (const auto& file : copy_job.object_files()) {
7086
2.03k
            auto relative_path = file.relative_path();
7087
2.03k
            paths_.push_back(relative_path);
7088
2.03k
            file_keys.keys.push_back(copy_file_key(
7089
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7090
2.03k
            LOG_INFO(log_trace)
7091
2.03k
                    .tag("relative_path", relative_path)
7092
2.03k
                    .tag("batch_count", batch_count_);
7093
2.03k
        }
7094
5
        LOG_INFO(log_trace)
7095
5
                .tag("objects_num", copy_job.object_files().size())
7096
5
                .tag("batch_count", batch_count_);
7097
        // 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
7098
        // recommend using delete objects when objects num is less than 10)
7099
5
        if (paths_.size() < 1000) {
7100
3
            return;
7101
3
        }
7102
2
        consume();
7103
2
    }
7104
7105
private:
7106
5
    void consume() {
7107
5
        DORIS_CLOUD_DEFER {
7108
5
            paths_.clear();
7109
5
            copy_file_keys_.clear();
7110
5
            batch_count_++;
7111
7112
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7113
5
                        batch_count_);
7114
5
        };
7115
7116
5
        StopWatch sw;
7117
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7118
5
        if (0 != accessor_->delete_files(paths_)) {
7119
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7120
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7121
2
            return;
7122
2
        }
7123
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7124
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7125
        // delete fdb's keys
7126
3
        for (auto& file_keys : copy_file_keys_) {
7127
3
            auto& [log_trace, keys] = file_keys.second;
7128
3
            std::unique_ptr<Transaction> txn;
7129
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7130
0
                LOG(WARNING) << "failed to create txn";
7131
0
                continue;
7132
0
            }
7133
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7134
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7135
            // limited, should not cause the txn commit failed.
7136
1.02k
            for (const auto& key : keys) {
7137
1.02k
                txn->remove(key);
7138
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7139
1.02k
            }
7140
3
            txn->remove(file_keys.first);
7141
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7142
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7143
0
                continue;
7144
0
            }
7145
3
        }
7146
3
    }
7147
    std::shared_ptr<StorageVaultAccessor> accessor_;
7148
    // the path of the s3 files to be deleted
7149
    std::vector<std::string> paths_;
7150
    struct CopyFiles {
7151
        std::string log_trace;
7152
        std::vector<std::string> keys;
7153
    };
7154
    // pair<std::string, std::vector<std::string>>
7155
    // first: instance_id_ stage_id table_id query_id
7156
    // second: keys to be deleted
7157
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7158
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7159
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7160
    // which can together uniquely identifies different tasks for tracing log
7161
    uint64_t& batch_count_;
7162
    TxnKv* txn_kv_;
7163
};
7164
7165
13
int InstanceRecycler::recycle_copy_jobs() {
7166
13
    int64_t num_scanned = 0;
7167
13
    int64_t num_finished = 0;
7168
13
    int64_t num_expired = 0;
7169
13
    int64_t num_recycled = 0;
7170
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7171
13
    uint64_t batch_count = 0;
7172
13
    const std::string task_name = "recycle_copy_jobs";
7173
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7174
7175
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7176
7177
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7178
13
    register_recycle_task(task_name, start_time);
7179
7180
13
    DORIS_CLOUD_DEFER {
7181
13
        unregister_recycle_task(task_name);
7182
13
        int64_t cost =
7183
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7184
13
        metrics_context.finish_report();
7185
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7186
13
                .tag("instance_id", instance_id_)
7187
13
                .tag("num_scanned", num_scanned)
7188
13
                .tag("num_finished", num_finished)
7189
13
                .tag("num_expired", num_expired)
7190
13
                .tag("num_recycled", num_recycled);
7191
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7180
13
    DORIS_CLOUD_DEFER {
7181
13
        unregister_recycle_task(task_name);
7182
13
        int64_t cost =
7183
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7184
13
        metrics_context.finish_report();
7185
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7186
13
                .tag("instance_id", instance_id_)
7187
13
                .tag("num_scanned", num_scanned)
7188
13
                .tag("num_finished", num_finished)
7189
13
                .tag("num_expired", num_expired)
7190
13
                .tag("num_recycled", num_recycled);
7191
13
    };
7192
7193
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7194
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7195
13
    std::string key0;
7196
13
    std::string key1;
7197
13
    copy_job_key(key_info0, &key0);
7198
13
    copy_job_key(key_info1, &key1);
7199
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7200
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7201
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7202
16
                         this](std::string_view k, std::string_view v) -> int {
7203
16
        ++num_scanned;
7204
16
        CopyJobPB copy_job;
7205
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7206
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7207
0
            return -1;
7208
0
        }
7209
7210
        // decode copy job key
7211
16
        auto k1 = k;
7212
16
        k1.remove_prefix(1);
7213
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7214
16
        decode_key(&k1, &out);
7215
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7216
        // -> CopyJobPB
7217
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7218
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7219
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7220
7221
16
        bool check_storage = true;
7222
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7223
12
            ++num_finished;
7224
7225
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7226
7
                auto it = stage_accessor_map.find(stage_id);
7227
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7228
7
                std::string_view path;
7229
7
                if (it != stage_accessor_map.end()) {
7230
2
                    accessor = it->second;
7231
5
                } else {
7232
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7233
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7234
5
                                                      &inner_accessor);
7235
5
                    if (ret < 0) { // error
7236
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7237
0
                        return -1;
7238
5
                    } else if (ret == 0) {
7239
3
                        path = inner_accessor->uri();
7240
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7241
3
                                inner_accessor, batch_count, txn_kv_.get());
7242
3
                        stage_accessor_map.emplace(stage_id, accessor);
7243
3
                    } else { // stage not found, skip check storage
7244
2
                        check_storage = false;
7245
2
                    }
7246
5
                }
7247
7
                if (check_storage) {
7248
                    // TODO delete objects with key and etag is not supported
7249
5
                    accessor->add(std::move(copy_job), std::string(k),
7250
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7251
5
                    return 0;
7252
5
                }
7253
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7254
5
                int64_t current_time =
7255
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7256
5
                if (copy_job.finish_time_ms() > 0) {
7257
2
                    if (!config::force_immediate_recycle &&
7258
2
                        current_time < copy_job.finish_time_ms() +
7259
2
                                               config::copy_job_max_retention_second * 1000) {
7260
1
                        return 0;
7261
1
                    }
7262
3
                } else {
7263
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7264
3
                    if (!config::force_immediate_recycle &&
7265
3
                        current_time < copy_job.start_time_ms() +
7266
3
                                               config::copy_job_max_retention_second * 1000) {
7267
1
                        return 0;
7268
1
                    }
7269
3
                }
7270
5
            }
7271
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7272
4
            int64_t current_time =
7273
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7274
            // if copy job is timeout: delete all copy file kvs and copy job kv
7275
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7276
2
                return 0;
7277
2
            }
7278
2
            ++num_expired;
7279
2
        }
7280
7281
        // delete all copy files
7282
7
        std::vector<std::string> copy_file_keys;
7283
70
        for (auto& file : copy_job.object_files()) {
7284
70
            copy_file_keys.push_back(copy_file_key(
7285
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7286
70
        }
7287
7
        std::unique_ptr<Transaction> txn;
7288
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7289
0
            LOG(WARNING) << "failed to create txn";
7290
0
            return -1;
7291
0
        }
7292
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7293
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7294
        // limited, should not cause the txn commit failed.
7295
70
        for (const auto& key : copy_file_keys) {
7296
70
            txn->remove(key);
7297
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7298
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7299
70
                      << ", query_id=" << copy_id;
7300
70
        }
7301
7
        txn->remove(k);
7302
7
        TxnErrorCode err = txn->commit();
7303
7
        if (err != TxnErrorCode::TXN_OK) {
7304
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7305
0
            return -1;
7306
0
        }
7307
7308
7
        metrics_context.total_recycled_num = ++num_recycled;
7309
7
        metrics_context.report();
7310
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7311
7
        return 0;
7312
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
7202
16
                         this](std::string_view k, std::string_view v) -> int {
7203
16
        ++num_scanned;
7204
16
        CopyJobPB copy_job;
7205
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7206
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7207
0
            return -1;
7208
0
        }
7209
7210
        // decode copy job key
7211
16
        auto k1 = k;
7212
16
        k1.remove_prefix(1);
7213
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7214
16
        decode_key(&k1, &out);
7215
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7216
        // -> CopyJobPB
7217
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7218
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7219
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7220
7221
16
        bool check_storage = true;
7222
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7223
12
            ++num_finished;
7224
7225
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7226
7
                auto it = stage_accessor_map.find(stage_id);
7227
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7228
7
                std::string_view path;
7229
7
                if (it != stage_accessor_map.end()) {
7230
2
                    accessor = it->second;
7231
5
                } else {
7232
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7233
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7234
5
                                                      &inner_accessor);
7235
5
                    if (ret < 0) { // error
7236
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7237
0
                        return -1;
7238
5
                    } else if (ret == 0) {
7239
3
                        path = inner_accessor->uri();
7240
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7241
3
                                inner_accessor, batch_count, txn_kv_.get());
7242
3
                        stage_accessor_map.emplace(stage_id, accessor);
7243
3
                    } else { // stage not found, skip check storage
7244
2
                        check_storage = false;
7245
2
                    }
7246
5
                }
7247
7
                if (check_storage) {
7248
                    // TODO delete objects with key and etag is not supported
7249
5
                    accessor->add(std::move(copy_job), std::string(k),
7250
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7251
5
                    return 0;
7252
5
                }
7253
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7254
5
                int64_t current_time =
7255
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7256
5
                if (copy_job.finish_time_ms() > 0) {
7257
2
                    if (!config::force_immediate_recycle &&
7258
2
                        current_time < copy_job.finish_time_ms() +
7259
2
                                               config::copy_job_max_retention_second * 1000) {
7260
1
                        return 0;
7261
1
                    }
7262
3
                } else {
7263
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7264
3
                    if (!config::force_immediate_recycle &&
7265
3
                        current_time < copy_job.start_time_ms() +
7266
3
                                               config::copy_job_max_retention_second * 1000) {
7267
1
                        return 0;
7268
1
                    }
7269
3
                }
7270
5
            }
7271
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7272
4
            int64_t current_time =
7273
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7274
            // if copy job is timeout: delete all copy file kvs and copy job kv
7275
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7276
2
                return 0;
7277
2
            }
7278
2
            ++num_expired;
7279
2
        }
7280
7281
        // delete all copy files
7282
7
        std::vector<std::string> copy_file_keys;
7283
70
        for (auto& file : copy_job.object_files()) {
7284
70
            copy_file_keys.push_back(copy_file_key(
7285
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7286
70
        }
7287
7
        std::unique_ptr<Transaction> txn;
7288
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7289
0
            LOG(WARNING) << "failed to create txn";
7290
0
            return -1;
7291
0
        }
7292
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7293
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7294
        // limited, should not cause the txn commit failed.
7295
70
        for (const auto& key : copy_file_keys) {
7296
70
            txn->remove(key);
7297
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7298
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7299
70
                      << ", query_id=" << copy_id;
7300
70
        }
7301
7
        txn->remove(k);
7302
7
        TxnErrorCode err = txn->commit();
7303
7
        if (err != TxnErrorCode::TXN_OK) {
7304
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7305
0
            return -1;
7306
0
        }
7307
7308
7
        metrics_context.total_recycled_num = ++num_recycled;
7309
7
        metrics_context.report();
7310
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7311
7
        return 0;
7312
7
    };
7313
7314
13
    if (config::enable_recycler_stats_metrics) {
7315
0
        scan_and_statistics_copy_jobs();
7316
0
    }
7317
    // recycle_func and loop_done for scan and recycle
7318
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7319
13
}
7320
7321
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7322
                                             const StagePB::StageType& stage_type,
7323
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7324
5
#ifdef UNIT_TEST
7325
    // In unit test, external use the same accessor as the internal stage
7326
5
    auto it = accessor_map_.find(stage_id);
7327
5
    if (it != accessor_map_.end()) {
7328
3
        *accessor = it->second;
7329
3
    } else {
7330
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7331
2
        return 1;
7332
2
    }
7333
#else
7334
    // init s3 accessor and add to accessor map
7335
    auto stage_it =
7336
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7337
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7338
7339
    if (stage_it == instance_info_.stages().end()) {
7340
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7341
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7342
        return 1;
7343
    }
7344
7345
    const auto& object_store_info = stage_it->obj_info();
7346
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7347
7348
    S3Conf s3_conf;
7349
    if (stage_type == StagePB::EXTERNAL) {
7350
        if (stage_access_type == StagePB::AKSK) {
7351
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7352
            if (!conf) {
7353
                return -1;
7354
            }
7355
7356
            s3_conf = std::move(*conf);
7357
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7358
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7359
            if (!conf) {
7360
                return -1;
7361
            }
7362
7363
            s3_conf = std::move(*conf);
7364
            if (instance_info_.ram_user().has_encryption_info()) {
7365
                AkSkPair plain_ak_sk_pair;
7366
                int ret = decrypt_ak_sk_helper(
7367
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7368
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7369
                if (ret != 0) {
7370
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7371
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7372
                    return -1;
7373
                }
7374
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7375
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7376
            } else {
7377
                s3_conf.ak = instance_info_.ram_user().ak();
7378
                s3_conf.sk = instance_info_.ram_user().sk();
7379
            }
7380
        } else {
7381
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7382
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7383
            return -1;
7384
        }
7385
    } else if (stage_type == StagePB::INTERNAL) {
7386
        int idx = stoi(object_store_info.id());
7387
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7388
            LOG(WARNING) << "invalid idx: " << idx;
7389
            return -1;
7390
        }
7391
7392
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7393
        auto conf = S3Conf::from_obj_store_info(old_obj);
7394
        if (!conf) {
7395
            return -1;
7396
        }
7397
7398
        s3_conf = std::move(*conf);
7399
        s3_conf.prefix = object_store_info.prefix();
7400
    } else {
7401
        LOG(WARNING) << "unknown stage type " << stage_type;
7402
        return -1;
7403
    }
7404
7405
    std::shared_ptr<S3Accessor> s3_accessor;
7406
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7407
    if (ret != 0) {
7408
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7409
        return -1;
7410
    }
7411
7412
    *accessor = std::move(s3_accessor);
7413
#endif
7414
3
    return 0;
7415
5
}
7416
7417
11
int InstanceRecycler::recycle_stage() {
7418
11
    int64_t num_scanned = 0;
7419
11
    int64_t num_recycled = 0;
7420
11
    const std::string task_name = "recycle_stage";
7421
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7422
7423
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7424
7425
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7426
11
    register_recycle_task(task_name, start_time);
7427
7428
11
    DORIS_CLOUD_DEFER {
7429
11
        unregister_recycle_task(task_name);
7430
11
        int64_t cost =
7431
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7432
11
        metrics_context.finish_report();
7433
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7434
11
                .tag("instance_id", instance_id_)
7435
11
                .tag("num_scanned", num_scanned)
7436
11
                .tag("num_recycled", num_recycled);
7437
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7428
11
    DORIS_CLOUD_DEFER {
7429
11
        unregister_recycle_task(task_name);
7430
11
        int64_t cost =
7431
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7432
11
        metrics_context.finish_report();
7433
        LOG_WARNING("recycle stage, cost={}s", cost)
7434
11
                .tag("instance_id", instance_id_)
7435
11
                .tag("num_scanned", num_scanned)
7436
11
                .tag("num_recycled", num_recycled);
7437
11
    };
7438
7439
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7440
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7441
11
    std::string key0 = recycle_stage_key(key_info0);
7442
11
    std::string key1 = recycle_stage_key(key_info1);
7443
7444
11
    std::vector<std::string_view> stage_keys;
7445
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7446
11
                         this](std::string_view k, std::string_view v) -> int {
7447
1
        ++num_scanned;
7448
1
        RecycleStagePB recycle_stage;
7449
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7450
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7451
0
            return -1;
7452
0
        }
7453
7454
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7455
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7456
0
            LOG(WARNING) << "invalid idx: " << idx;
7457
0
            return -1;
7458
0
        }
7459
7460
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7461
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7462
1
                [&] {
7463
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7464
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7465
1
                    if (!s3_conf) {
7466
1
                        return -1;
7467
1
                    }
7468
7469
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7470
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7471
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7472
1
                    if (ret != 0) {
7473
1
                        return -1;
7474
1
                    }
7475
7476
1
                    accessor = std::move(s3_accessor);
7477
1
                    return 0;
7478
1
                }(),
7479
1
                "recycle_stage:get_accessor", &accessor);
7480
7481
1
        if (ret != 0) {
7482
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7483
0
            return ret;
7484
0
        }
7485
7486
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7487
1
                .tag("instance_id", instance_id_)
7488
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7489
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7490
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7491
1
                .tag("obj_info_id", idx)
7492
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7493
1
        ret = accessor->delete_all();
7494
1
        if (ret != 0) {
7495
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7496
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7497
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7498
0
                         << ", ret=" << ret;
7499
0
            return -1;
7500
0
        }
7501
1
        metrics_context.total_recycled_num = ++num_recycled;
7502
1
        metrics_context.report();
7503
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7504
1
        stage_keys.push_back(k);
7505
1
        return 0;
7506
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7446
1
                         this](std::string_view k, std::string_view v) -> int {
7447
1
        ++num_scanned;
7448
1
        RecycleStagePB recycle_stage;
7449
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7450
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7451
0
            return -1;
7452
0
        }
7453
7454
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7455
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7456
0
            LOG(WARNING) << "invalid idx: " << idx;
7457
0
            return -1;
7458
0
        }
7459
7460
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7461
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7462
1
                [&] {
7463
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7464
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7465
1
                    if (!s3_conf) {
7466
1
                        return -1;
7467
1
                    }
7468
7469
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7470
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7471
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7472
1
                    if (ret != 0) {
7473
1
                        return -1;
7474
1
                    }
7475
7476
1
                    accessor = std::move(s3_accessor);
7477
1
                    return 0;
7478
1
                }(),
7479
1
                "recycle_stage:get_accessor", &accessor);
7480
7481
1
        if (ret != 0) {
7482
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7483
0
            return ret;
7484
0
        }
7485
7486
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7487
1
                .tag("instance_id", instance_id_)
7488
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7489
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7490
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7491
1
                .tag("obj_info_id", idx)
7492
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7493
1
        ret = accessor->delete_all();
7494
1
        if (ret != 0) {
7495
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7496
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7497
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7498
0
                         << ", ret=" << ret;
7499
0
            return -1;
7500
0
        }
7501
1
        metrics_context.total_recycled_num = ++num_recycled;
7502
1
        metrics_context.report();
7503
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7504
1
        stage_keys.push_back(k);
7505
1
        return 0;
7506
1
    };
7507
7508
11
    auto loop_done = [&stage_keys, this]() -> int {
7509
1
        if (stage_keys.empty()) return 0;
7510
1
        DORIS_CLOUD_DEFER {
7511
1
            stage_keys.clear();
7512
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7510
1
        DORIS_CLOUD_DEFER {
7511
1
            stage_keys.clear();
7512
1
        };
7513
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7514
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7515
0
            return -1;
7516
0
        }
7517
1
        return 0;
7518
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7508
1
    auto loop_done = [&stage_keys, this]() -> int {
7509
1
        if (stage_keys.empty()) return 0;
7510
1
        DORIS_CLOUD_DEFER {
7511
1
            stage_keys.clear();
7512
1
        };
7513
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7514
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7515
0
            return -1;
7516
0
        }
7517
1
        return 0;
7518
1
    };
7519
11
    if (config::enable_recycler_stats_metrics) {
7520
0
        scan_and_statistics_stage();
7521
0
    }
7522
    // recycle_func and loop_done for scan and recycle
7523
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7524
11
}
7525
7526
10
int InstanceRecycler::recycle_expired_stage_objects() {
7527
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7528
7529
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7530
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7531
7532
10
    DORIS_CLOUD_DEFER {
7533
10
        int64_t cost =
7534
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7535
10
        metrics_context.finish_report();
7536
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7537
10
                .tag("instance_id", instance_id_);
7538
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7532
10
    DORIS_CLOUD_DEFER {
7533
10
        int64_t cost =
7534
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7535
10
        metrics_context.finish_report();
7536
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7537
10
                .tag("instance_id", instance_id_);
7538
10
    };
7539
7540
10
    int ret = 0;
7541
7542
10
    if (config::enable_recycler_stats_metrics) {
7543
0
        scan_and_statistics_expired_stage_objects();
7544
0
    }
7545
7546
10
    for (const auto& stage : instance_info_.stages()) {
7547
0
        std::stringstream ss;
7548
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7549
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7550
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7551
0
           << ", prefix=" << stage.obj_info().prefix();
7552
7553
0
        if (stopped()) {
7554
0
            break;
7555
0
        }
7556
0
        if (stage.type() == StagePB::EXTERNAL) {
7557
0
            continue;
7558
0
        }
7559
0
        int idx = stoi(stage.obj_info().id());
7560
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7561
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7562
0
            continue;
7563
0
        }
7564
7565
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7566
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7567
0
        if (!s3_conf) {
7568
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7569
0
            continue;
7570
0
        }
7571
7572
0
        s3_conf->prefix = stage.obj_info().prefix();
7573
0
        std::shared_ptr<S3Accessor> accessor;
7574
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7575
0
        if (ret1 != 0) {
7576
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7577
0
            ret = -1;
7578
0
            continue;
7579
0
        }
7580
7581
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7582
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7583
0
            ret = -1;
7584
0
            continue;
7585
0
        }
7586
7587
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7588
0
        int64_t expiration_time =
7589
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7590
0
                config::internal_stage_objects_expire_time_second;
7591
0
        if (config::force_immediate_recycle) {
7592
0
            expiration_time = INT64_MAX;
7593
0
        }
7594
0
        ret1 = accessor->delete_all(expiration_time);
7595
0
        if (ret1 != 0) {
7596
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7597
0
                         << ss.str();
7598
0
            ret = -1;
7599
0
            continue;
7600
0
        }
7601
0
        metrics_context.total_recycled_num++;
7602
0
        metrics_context.report();
7603
0
    }
7604
10
    return ret;
7605
10
}
7606
7607
234
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7608
234
    std::lock_guard lock(recycle_tasks_mutex);
7609
234
    running_recycle_tasks[task_name] = start_time;
7610
234
}
7611
7612
234
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7613
234
    std::lock_guard lock(recycle_tasks_mutex);
7614
234
    DCHECK(running_recycle_tasks[task_name] > 0);
7615
234
    running_recycle_tasks.erase(task_name);
7616
234
}
7617
7618
21
bool InstanceRecycler::check_recycle_tasks() {
7619
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7620
21
    {
7621
21
        std::lock_guard lock(recycle_tasks_mutex);
7622
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7623
21
    }
7624
7625
21
    bool found = false;
7626
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7627
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7628
20
        int64_t cost = now - start_time;
7629
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7630
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7631
20
                    .tag("instance_id", instance_id_)
7632
20
                    .tag("task", task_name);
7633
20
            found = true;
7634
20
        }
7635
20
    }
7636
7637
21
    return found;
7638
21
}
7639
7640
// Scan and statistics indexes that need to be recycled
7641
0
int InstanceRecycler::scan_and_statistics_indexes() {
7642
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7643
7644
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7645
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7646
0
    std::string index_key0;
7647
0
    std::string index_key1;
7648
0
    recycle_index_key(index_key_info0, &index_key0);
7649
0
    recycle_index_key(index_key_info1, &index_key1);
7650
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7651
7652
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7653
0
        RecycleIndexPB index_pb;
7654
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7655
0
            return 0;
7656
0
        }
7657
0
        int64_t current_time = ::time(nullptr);
7658
0
        if (current_time <
7659
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7660
0
            return 0;
7661
0
        }
7662
        // decode index_id
7663
0
        auto k1 = k;
7664
0
        k1.remove_prefix(1);
7665
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7666
0
        decode_key(&k1, &out);
7667
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7668
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7669
0
        std::unique_ptr<Transaction> txn;
7670
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7671
0
        if (err != TxnErrorCode::TXN_OK) {
7672
0
            return 0;
7673
0
        }
7674
0
        std::string val;
7675
0
        err = txn->get(k, &val);
7676
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7677
0
            return 0;
7678
0
        }
7679
0
        if (err != TxnErrorCode::TXN_OK) {
7680
0
            return 0;
7681
0
        }
7682
0
        index_pb.Clear();
7683
0
        if (!index_pb.ParseFromString(val)) {
7684
0
            return 0;
7685
0
        }
7686
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7687
0
            return 0;
7688
0
        }
7689
0
        metrics_context.total_need_recycle_num++;
7690
0
        return 0;
7691
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
7692
7693
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7694
0
    metrics_context.report(true);
7695
0
    segment_metrics_context_.report(true);
7696
0
    tablet_metrics_context_.report(true);
7697
0
    return ret;
7698
0
}
7699
7700
// Scan and statistics partitions that need to be recycled
7701
0
int InstanceRecycler::scan_and_statistics_partitions() {
7702
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7703
7704
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7705
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7706
0
    std::string part_key0;
7707
0
    std::string part_key1;
7708
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7709
7710
0
    recycle_partition_key(part_key_info0, &part_key0);
7711
0
    recycle_partition_key(part_key_info1, &part_key1);
7712
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7713
0
        RecyclePartitionPB part_pb;
7714
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7715
0
            return 0;
7716
0
        }
7717
0
        int64_t current_time = ::time(nullptr);
7718
0
        if (current_time <
7719
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7720
0
            return 0;
7721
0
        }
7722
        // decode partition_id
7723
0
        auto k1 = k;
7724
0
        k1.remove_prefix(1);
7725
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7726
0
        decode_key(&k1, &out);
7727
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7728
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7729
        // Change state to RECYCLING
7730
0
        std::unique_ptr<Transaction> txn;
7731
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7732
0
        if (err != TxnErrorCode::TXN_OK) {
7733
0
            return 0;
7734
0
        }
7735
0
        std::string val;
7736
0
        err = txn->get(k, &val);
7737
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7738
0
            return 0;
7739
0
        }
7740
0
        if (err != TxnErrorCode::TXN_OK) {
7741
0
            return 0;
7742
0
        }
7743
0
        part_pb.Clear();
7744
0
        if (!part_pb.ParseFromString(val)) {
7745
0
            return 0;
7746
0
        }
7747
        // Partitions with PREPARED state MUST have no data
7748
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7749
0
        int ret = 0;
7750
0
        for (int64_t index_id : part_pb.index_id()) {
7751
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7752
0
                                            partition_id, is_empty_tablet) != 0) {
7753
0
                ret = 0;
7754
0
            }
7755
0
        }
7756
0
        metrics_context.total_need_recycle_num++;
7757
0
        return ret;
7758
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_
7759
7760
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7761
0
    metrics_context.report(true);
7762
0
    segment_metrics_context_.report(true);
7763
0
    tablet_metrics_context_.report(true);
7764
0
    return ret;
7765
0
}
7766
7767
// Scan and statistics rowsets that need to be recycled
7768
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7769
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7770
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7771
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7772
0
    std::string recyc_rs_key0;
7773
0
    std::string recyc_rs_key1;
7774
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7775
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7776
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7777
7778
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7779
0
        RecycleRowsetPB rowset;
7780
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7781
0
            return 0;
7782
0
        }
7783
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7784
0
        int64_t current_time = ::time(nullptr);
7785
0
        if (current_time <
7786
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7787
0
            return 0;
7788
0
        }
7789
7790
0
        if (!rowset.has_type()) {
7791
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7792
0
                return 0;
7793
0
            }
7794
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7795
0
                return 0;
7796
0
            }
7797
0
            metrics_context.total_need_recycle_num++;
7798
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7799
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7800
0
            segment_metrics_context_.total_need_recycle_data_size +=
7801
0
                    rowset.rowset_meta().total_disk_size();
7802
0
            return 0;
7803
0
        }
7804
7805
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7806
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7807
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7808
0
            return 0;
7809
0
        }
7810
7811
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7812
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7813
0
                return 0;
7814
0
            }
7815
0
        }
7816
0
        metrics_context.total_need_recycle_num++;
7817
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7818
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7819
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7820
0
        return 0;
7821
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_
7822
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7823
0
    metrics_context.report(true);
7824
0
    segment_metrics_context_.report(true);
7825
0
    return ret;
7826
0
}
7827
7828
// Scan and statistics tmp_rowsets that need to be recycled
7829
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7830
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7831
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7832
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7833
0
    std::string tmp_rs_key0;
7834
0
    std::string tmp_rs_key1;
7835
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7836
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7837
7838
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7839
7840
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7841
0
        doris::RowsetMetaCloudPB rowset;
7842
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7843
0
            return 0;
7844
0
        }
7845
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7846
0
        int64_t current_time = ::time(nullptr);
7847
0
        if (current_time < expiration) {
7848
0
            return 0;
7849
0
        }
7850
7851
0
        DCHECK_GT(rowset.txn_id(), 0)
7852
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7853
7854
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
7855
0
            return 0;
7856
0
        }
7857
7858
0
        if (!rowset.has_resource_id()) {
7859
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7860
0
                return 0;
7861
0
            }
7862
0
            return 0;
7863
0
        }
7864
7865
0
        metrics_context.total_need_recycle_num++;
7866
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7867
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7868
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7869
0
        return 0;
7870
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_
7871
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7872
0
    metrics_context.report(true);
7873
0
    segment_metrics_context_.report(true);
7874
0
    return ret;
7875
0
}
7876
7877
// Scan and statistics abort_timeout_txn that need to be recycled
7878
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7879
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7880
7881
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7882
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7883
0
    std::string begin_txn_running_key;
7884
0
    std::string end_txn_running_key;
7885
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7886
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7887
7888
0
    int64_t current_time =
7889
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7890
7891
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7892
0
                                               std::string_view k, std::string_view v) -> int {
7893
0
        std::unique_ptr<Transaction> txn;
7894
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7895
0
        if (err != TxnErrorCode::TXN_OK) {
7896
0
            return 0;
7897
0
        }
7898
0
        std::string_view k1 = k;
7899
0
        k1.remove_prefix(1);
7900
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7901
0
        if (decode_key(&k1, &out) != 0) {
7902
0
            return 0;
7903
0
        }
7904
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7905
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7906
        // Update txn_info
7907
0
        std::string txn_inf_key, txn_inf_val;
7908
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7909
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7910
0
        if (err != TxnErrorCode::TXN_OK) {
7911
0
            return 0;
7912
0
        }
7913
0
        TxnInfoPB txn_info;
7914
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7915
0
            return 0;
7916
0
        }
7917
7918
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7919
0
            TxnRunningPB txn_running_pb;
7920
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7921
0
                return 0;
7922
0
            }
7923
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7924
0
                return 0;
7925
0
            }
7926
0
            metrics_context.total_need_recycle_num++;
7927
0
        }
7928
0
        return 0;
7929
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_
7930
7931
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7932
0
                               std::move(handle_abort_timeout_txn_kv));
7933
0
    metrics_context.report(true);
7934
0
    return ret;
7935
0
}
7936
7937
// Scan and statistics expired_txn_label that need to be recycled
7938
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7939
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7940
7941
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7942
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7943
0
    std::string begin_recycle_txn_key;
7944
0
    std::string end_recycle_txn_key;
7945
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7946
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7947
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7948
0
    int64_t current_time_ms =
7949
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7950
7951
    // for calculate the total num or bytes of recyled objects
7952
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7953
0
        RecycleTxnPB recycle_txn_pb;
7954
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7955
0
            return 0;
7956
0
        }
7957
0
        if ((config::force_immediate_recycle) ||
7958
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7959
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7960
0
             current_time_ms)) {
7961
0
            metrics_context.total_need_recycle_num++;
7962
0
        }
7963
0
        return 0;
7964
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_
7965
7966
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7967
0
                               std::move(handle_expired_txn_label_kv));
7968
0
    metrics_context.report(true);
7969
0
    return ret;
7970
0
}
7971
7972
// Scan and statistics copy_jobs that need to be recycled
7973
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7974
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7975
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7976
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7977
0
    std::string key0;
7978
0
    std::string key1;
7979
0
    copy_job_key(key_info0, &key0);
7980
0
    copy_job_key(key_info1, &key1);
7981
7982
    // for calculate the total num or bytes of recyled objects
7983
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7984
0
        CopyJobPB copy_job;
7985
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7986
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7987
0
            return 0;
7988
0
        }
7989
7990
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7991
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7992
0
                int64_t current_time =
7993
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7994
0
                if (copy_job.finish_time_ms() > 0) {
7995
0
                    if (!config::force_immediate_recycle &&
7996
0
                        current_time < copy_job.finish_time_ms() +
7997
0
                                               config::copy_job_max_retention_second * 1000) {
7998
0
                        return 0;
7999
0
                    }
8000
0
                } else {
8001
0
                    if (!config::force_immediate_recycle &&
8002
0
                        current_time < copy_job.start_time_ms() +
8003
0
                                               config::copy_job_max_retention_second * 1000) {
8004
0
                        return 0;
8005
0
                    }
8006
0
                }
8007
0
            }
8008
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8009
0
            int64_t current_time =
8010
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8011
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8012
0
                return 0;
8013
0
            }
8014
0
        }
8015
0
        metrics_context.total_need_recycle_num++;
8016
0
        return 0;
8017
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_
8018
8019
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8020
0
    metrics_context.report(true);
8021
0
    return ret;
8022
0
}
8023
8024
// Scan and statistics stage that need to be recycled
8025
0
int InstanceRecycler::scan_and_statistics_stage() {
8026
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8027
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8028
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8029
0
    std::string key0 = recycle_stage_key(key_info0);
8030
0
    std::string key1 = recycle_stage_key(key_info1);
8031
8032
    // for calculate the total num or bytes of recyled objects
8033
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8034
0
                                                        std::string_view v) -> int {
8035
0
        RecycleStagePB recycle_stage;
8036
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8037
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8038
0
            return 0;
8039
0
        }
8040
8041
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8042
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8043
0
            LOG(WARNING) << "invalid idx: " << idx;
8044
0
            return 0;
8045
0
        }
8046
8047
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8048
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8049
0
                [&] {
8050
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8051
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8052
0
                    if (!s3_conf) {
8053
0
                        return 0;
8054
0
                    }
8055
8056
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8057
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8058
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8059
0
                    if (ret != 0) {
8060
0
                        return 0;
8061
0
                    }
8062
8063
0
                    accessor = std::move(s3_accessor);
8064
0
                    return 0;
8065
0
                }(),
8066
0
                "recycle_stage:get_accessor", &accessor);
8067
8068
0
        if (ret != 0) {
8069
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8070
0
            return 0;
8071
0
        }
8072
8073
0
        metrics_context.total_need_recycle_num++;
8074
0
        return 0;
8075
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_
8076
8077
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8078
0
    metrics_context.report(true);
8079
0
    return ret;
8080
0
}
8081
8082
// Scan and statistics expired_stage_objects that need to be recycled
8083
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8084
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8085
8086
    // for calculate the total num or bytes of recyled objects
8087
0
    auto scan_and_statistics = [&metrics_context, this]() {
8088
0
        for (const auto& stage : instance_info_.stages()) {
8089
0
            if (stopped()) {
8090
0
                break;
8091
0
            }
8092
0
            if (stage.type() == StagePB::EXTERNAL) {
8093
0
                continue;
8094
0
            }
8095
0
            int idx = stoi(stage.obj_info().id());
8096
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8097
0
                continue;
8098
0
            }
8099
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8100
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8101
0
            if (!s3_conf) {
8102
0
                continue;
8103
0
            }
8104
0
            s3_conf->prefix = stage.obj_info().prefix();
8105
0
            std::shared_ptr<S3Accessor> accessor;
8106
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8107
0
            if (ret1 != 0) {
8108
0
                continue;
8109
0
            }
8110
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8111
0
                continue;
8112
0
            }
8113
0
            metrics_context.total_need_recycle_num++;
8114
0
        }
8115
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8116
8117
0
    scan_and_statistics();
8118
0
    metrics_context.report(true);
8119
0
    return 0;
8120
0
}
8121
8122
// Scan and statistics versions that need to be recycled
8123
0
int InstanceRecycler::scan_and_statistics_versions() {
8124
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8125
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8126
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8127
8128
0
    int64_t last_scanned_table_id = 0;
8129
0
    bool is_recycled = false; // Is last scanned kv recycled
8130
    // for calculate the total num or bytes of recyled objects
8131
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8132
0
                                       std::string_view k, std::string_view) {
8133
0
        auto k1 = k;
8134
0
        k1.remove_prefix(1);
8135
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8136
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8137
0
        decode_key(&k1, &out);
8138
0
        DCHECK_EQ(out.size(), 6) << k;
8139
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8140
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8141
0
            metrics_context.total_need_recycle_num +=
8142
0
                    is_recycled; // Version kv of this table has been recycled
8143
0
            return 0;
8144
0
        }
8145
0
        last_scanned_table_id = table_id;
8146
0
        is_recycled = false;
8147
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8148
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8149
0
        std::unique_ptr<Transaction> txn;
8150
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8151
0
        if (err != TxnErrorCode::TXN_OK) {
8152
0
            return 0;
8153
0
        }
8154
0
        std::unique_ptr<RangeGetIterator> iter;
8155
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8156
0
        if (err != TxnErrorCode::TXN_OK) {
8157
0
            return 0;
8158
0
        }
8159
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8160
0
            return 0;
8161
0
        }
8162
0
        metrics_context.total_need_recycle_num++;
8163
0
        is_recycled = true;
8164
0
        return 0;
8165
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_
8166
8167
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8168
0
    metrics_context.report(true);
8169
0
    return ret;
8170
0
}
8171
8172
// Scan and statistics restore jobs that need to be recycled
8173
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8174
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8175
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8176
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8177
0
    std::string restore_job_key0;
8178
0
    std::string restore_job_key1;
8179
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8180
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8181
8182
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8183
8184
    // for calculate the total num or bytes of recyled objects
8185
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8186
0
        RestoreJobCloudPB restore_job_pb;
8187
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8188
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8189
0
            return 0;
8190
0
        }
8191
0
        int64_t expiration =
8192
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8193
0
        int64_t current_time = ::time(nullptr);
8194
0
        if (current_time < expiration) { // not expired
8195
0
            return 0;
8196
0
        }
8197
0
        metrics_context.total_need_recycle_num++;
8198
0
        if (restore_job_pb.need_recycle_data()) {
8199
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8200
0
        }
8201
0
        return 0;
8202
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_
8203
8204
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8205
0
    metrics_context.report(true);
8206
0
    return ret;
8207
0
}
8208
8209
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8210
3
    if (!should_recycle_versioned_keys()) {
8211
0
        return;
8212
0
    }
8213
8214
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8215
8216
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8217
3
    if (recycle_checker.init() != 0) {
8218
0
        return;
8219
0
    }
8220
8221
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8222
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8223
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8224
8225
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8226
8
    for (; iter->valid(); iter->next()) {
8227
5
        OperationLogPB operation_log;
8228
5
        if (!iter->parse_value(&operation_log)) {
8229
0
            continue;
8230
0
        }
8231
8232
5
        std::string_view key = iter->key();
8233
5
        Versionstamp log_versionstamp;
8234
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8235
0
            continue;
8236
0
        }
8237
8238
5
        OperationLogReferenceInfo ref_info;
8239
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8240
5
                                        &ref_info)) {
8241
4
            metrics_context.total_need_recycle_num++;
8242
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8243
4
        }
8244
5
    }
8245
8246
3
    metrics_context.report(true);
8247
3
}
8248
8249
int InstanceRecycler::classify_rowset_task_by_ref_count(
8250
61
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8251
61
    constexpr int MAX_RETRY = 10;
8252
61
    const auto& rowset_meta = task.rowset_meta;
8253
61
    int64_t tablet_id = rowset_meta.tablet_id();
8254
61
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8255
61
    std::string_view reference_instance_id = instance_id_;
8256
61
    if (rowset_meta.has_reference_instance_id()) {
8257
5
        reference_instance_id = rowset_meta.reference_instance_id();
8258
5
    }
8259
8260
62
    for (int i = 0; i < MAX_RETRY; ++i) {
8261
62
        std::unique_ptr<Transaction> txn;
8262
62
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8263
62
        if (err != TxnErrorCode::TXN_OK) {
8264
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8265
0
                    .tag("instance_id", instance_id_)
8266
0
                    .tag("tablet_id", tablet_id)
8267
0
                    .tag("rowset_id", rowset_id)
8268
0
                    .tag("err", err);
8269
0
            return -1;
8270
0
        }
8271
8272
62
        std::string rowset_ref_count_key =
8273
62
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8274
62
        task.rowset_ref_count_key = rowset_ref_count_key;
8275
8276
62
        int64_t ref_count = 0;
8277
62
        {
8278
62
            std::string value;
8279
62
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8280
62
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8281
0
                ref_count = 1;
8282
62
            } else if (err != TxnErrorCode::TXN_OK) {
8283
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8284
0
                        .tag("instance_id", instance_id_)
8285
0
                        .tag("tablet_id", tablet_id)
8286
0
                        .tag("rowset_id", rowset_id)
8287
0
                        .tag("err", err);
8288
0
                return -1;
8289
62
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8290
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8291
0
                        .tag("instance_id", instance_id_)
8292
0
                        .tag("tablet_id", tablet_id)
8293
0
                        .tag("rowset_id", rowset_id)
8294
0
                        .tag("value", hex(value));
8295
0
                return -1;
8296
0
            }
8297
62
        }
8298
8299
62
        if (ref_count > 1) {
8300
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8301
12
            txn->atomic_add(rowset_ref_count_key, -1);
8302
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8303
12
                    .tag("instance_id", instance_id_)
8304
12
                    .tag("tablet_id", tablet_id)
8305
12
                    .tag("rowset_id", rowset_id)
8306
12
                    .tag("ref_count", ref_count - 1)
8307
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8308
8309
12
            if (!task.recycle_rowset_key.empty()) {
8310
0
                txn->remove(task.recycle_rowset_key);
8311
0
                LOG_INFO("remove recycle rowset key in classification phase")
8312
0
                        .tag("key", hex(task.recycle_rowset_key));
8313
0
            }
8314
12
            if (!task.non_versioned_rowset_key.empty()) {
8315
12
                txn->remove(task.non_versioned_rowset_key);
8316
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8317
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8318
12
            }
8319
8320
12
            err = txn->commit();
8321
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8322
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8323
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8324
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8325
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8326
1
                continue;
8327
11
            } else if (err != TxnErrorCode::TXN_OK) {
8328
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8329
0
                        .tag("instance_id", instance_id_)
8330
0
                        .tag("tablet_id", tablet_id)
8331
0
                        .tag("rowset_id", rowset_id)
8332
0
                        .tag("err", err);
8333
0
                return -1;
8334
0
            }
8335
11
            return 1; // handled, not added to batch delete
8336
50
        } else {
8337
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8338
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8339
50
            LOG_INFO("add rowset to batch delete plan")
8340
50
                    .tag("instance_id", instance_id_)
8341
50
                    .tag("tablet_id", tablet_id)
8342
50
                    .tag("rowset_id", rowset_id)
8343
50
                    .tag("resource_id", rowset_meta.resource_id())
8344
50
                    .tag("ref_count", ref_count);
8345
8346
50
            batch_delete_tasks.push_back(std::move(task));
8347
50
            return 0; // added to batch delete
8348
50
        }
8349
62
    }
8350
8351
0
    LOG_WARNING("failed to classify rowset task after retry")
8352
0
            .tag("instance_id", instance_id_)
8353
0
            .tag("tablet_id", tablet_id)
8354
0
            .tag("rowset_id", rowset_id)
8355
0
            .tag("retry", MAX_RETRY);
8356
0
    return -1;
8357
61
}
8358
8359
11
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8360
11
    int ret = 0;
8361
50
    for (const auto& task : tasks) {
8362
50
        int64_t tablet_id = task.rowset_meta.tablet_id();
8363
50
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8364
8365
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8366
        // so we don't need to call it again here.
8367
8368
        // Remove all metadata keys in one transaction
8369
50
        std::unique_ptr<Transaction> txn;
8370
50
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8371
50
        if (err != TxnErrorCode::TXN_OK) {
8372
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8373
0
                    .tag("instance_id", instance_id_)
8374
0
                    .tag("tablet_id", tablet_id)
8375
0
                    .tag("rowset_id", rowset_id)
8376
0
                    .tag("err", err);
8377
0
            ret = -1;
8378
0
            continue;
8379
0
        }
8380
8381
50
        std::string_view reference_instance_id = instance_id_;
8382
50
        if (task.rowset_meta.has_reference_instance_id()) {
8383
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8384
0
        }
8385
8386
50
        txn->remove(task.rowset_ref_count_key);
8387
50
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8388
50
                .tag("instance_id", instance_id_)
8389
50
                .tag("tablet_id", tablet_id)
8390
50
                .tag("rowset_id", rowset_id)
8391
50
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8392
8393
50
        std::string dbm_start_key =
8394
50
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8395
50
        std::string dbm_end_key = meta_delete_bitmap_key(
8396
50
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8397
50
                 std::numeric_limits<int64_t>::max()});
8398
50
        txn->remove(dbm_start_key, dbm_end_key);
8399
50
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8400
50
                .tag("instance_id", instance_id_)
8401
50
                .tag("tablet_id", tablet_id)
8402
50
                .tag("rowset_id", rowset_id)
8403
50
                .tag("begin", hex(dbm_start_key))
8404
50
                .tag("end", hex(dbm_end_key));
8405
8406
50
        std::string versioned_dbm_start_key =
8407
50
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8408
50
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8409
50
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8410
50
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8411
50
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8412
50
                .tag("instance_id", instance_id_)
8413
50
                .tag("tablet_id", tablet_id)
8414
50
                .tag("rowset_id", rowset_id)
8415
50
                .tag("begin", hex(versioned_dbm_start_key))
8416
50
                .tag("end", hex(versioned_dbm_end_key));
8417
8418
        // Remove versioned meta rowset key
8419
50
        if (!task.versioned_rowset_key.empty()) {
8420
50
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8421
50
                                                          task.versionstamp);
8422
50
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8423
50
                    .tag("instance_id", instance_id_)
8424
50
                    .tag("tablet_id", tablet_id)
8425
50
                    .tag("rowset_id", rowset_id)
8426
50
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8427
50
        }
8428
8429
50
        if (!task.non_versioned_rowset_key.empty()) {
8430
50
            txn->remove(task.non_versioned_rowset_key);
8431
50
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8432
50
                    .tag("instance_id", instance_id_)
8433
50
                    .tag("tablet_id", tablet_id)
8434
50
                    .tag("rowset_id", rowset_id)
8435
50
                    .tag("key", hex(task.non_versioned_rowset_key));
8436
50
        }
8437
8438
        // Remove recycle_rowset_key last to ensure retry safety:
8439
        // if cleanup fails, this key remains and triggers next round retry.
8440
50
        if (!task.recycle_rowset_key.empty()) {
8441
0
            txn->remove(task.recycle_rowset_key);
8442
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8443
0
                    .tag("instance_id", instance_id_)
8444
0
                    .tag("tablet_id", tablet_id)
8445
0
                    .tag("rowset_id", rowset_id)
8446
0
                    .tag("key", hex(task.recycle_rowset_key));
8447
0
        }
8448
8449
50
        err = txn->commit();
8450
50
        if (err != TxnErrorCode::TXN_OK) {
8451
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8452
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8453
0
                    .tag("instance_id", instance_id_)
8454
0
                    .tag("tablet_id", tablet_id)
8455
0
                    .tag("rowset_id", rowset_id)
8456
0
                    .tag("err", err);
8457
0
            ret = -1;
8458
0
            continue;
8459
0
        }
8460
8461
50
        LOG_INFO("cleanup rowset metadata success")
8462
50
                .tag("instance_id", instance_id_)
8463
50
                .tag("tablet_id", tablet_id)
8464
50
                .tag("rowset_id", rowset_id);
8465
50
    }
8466
11
    return ret;
8467
11
}
8468
8469
} // namespace doris::cloud