Coverage Report

Created: 2026-10-25 18:19

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
948k
                                      std::vector<std::string>* file_paths) {
121
948k
    if (!is_packed_slice_path(rowset, path)) {
122
919k
        file_paths->push_back(path);
123
919k
    }
124
948k
}
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
948k
                                      std::vector<std::string>* file_paths) {
121
948k
    if (!is_packed_slice_path(rowset, path)) {
122
919k
        file_paths->push_back(path);
123
919k
    }
124
948k
}
125
126
} // namespace
127
128
// return 0 for success get a key, 1 for key not found, negative for error
129
16
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
16
    std::unique_ptr<Transaction> txn;
131
16
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
16
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
16
    switch (txn->get(key, &val, true)) {
136
6
    case TxnErrorCode::TXN_OK:
137
6
        return 0;
138
10
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
10
        return 1;
140
0
    default:
141
0
        return -1;
142
16
    };
143
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
10
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
10
    std::unique_ptr<Transaction> txn;
131
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
10
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
10
    switch (txn->get(key, &val, true)) {
136
3
    case TxnErrorCode::TXN_OK:
137
3
        return 0;
138
7
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
7
        return 1;
140
0
    default:
141
0
        return -1;
142
10
    };
143
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
129
6
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
130
6
    std::unique_ptr<Transaction> txn;
131
6
    TxnErrorCode err = txn_kv->create_txn(&txn);
132
6
    if (err != TxnErrorCode::TXN_OK) {
133
0
        return -1;
134
0
    }
135
6
    switch (txn->get(key, &val, true)) {
136
3
    case TxnErrorCode::TXN_OK:
137
3
        return 0;
138
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
139
3
        return 1;
140
0
    default:
141
0
        return -1;
142
6
    };
143
0
}
144
145
// 0 for success, negative for error
146
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
147
688
                   std::unique_ptr<RangeGetIterator>& it) {
148
688
    std::unique_ptr<Transaction> txn;
149
688
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
688
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
688
    switch (txn->get(begin, end, &it, true)) {
154
688
    case TxnErrorCode::TXN_OK:
155
688
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
688
    };
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
657
                   std::unique_ptr<RangeGetIterator>& it) {
148
657
    std::unique_ptr<Transaction> txn;
149
657
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
657
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
657
    switch (txn->get(begin, end, &it, true)) {
154
657
    case TxnErrorCode::TXN_OK:
155
657
        return 0;
156
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
157
0
        return 1;
158
0
    default:
159
0
        return -1;
160
657
    };
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
53
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
53
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
52
    size_t idx = 0;
237
105
    while (idx < rowset_dbm_key_groups.size()) {
238
53
        std::unique_ptr<Transaction> txn;
239
53
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
53
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
53
        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(); });
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.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
53
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
53
        err = txn->commit();
265
53
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
53
    }
270
52
    return 0;
271
52
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
recycler_test.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
Line
Count
Source
232
53
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
233
53
    if (rowset_dbm_key_groups.empty()) {
234
1
        return 0;
235
1
    }
236
52
    size_t idx = 0;
237
105
    while (idx < rowset_dbm_key_groups.size()) {
238
53
        std::unique_ptr<Transaction> txn;
239
53
        TxnErrorCode err = txn_kv->create_txn(&txn);
240
53
        if (err != TxnErrorCode::TXN_OK) {
241
0
            return -1;
242
0
        }
243
244
53
        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
53
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
264
53
        err = txn->commit();
265
53
        if (err != TxnErrorCode::TXN_OK) {
266
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
267
0
            return -1;
268
0
        }
269
53
    }
270
52
    return 0;
271
52
}
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
667
    while (!stopped()) {
329
662
        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
658
        } else {
352
658
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
353
658
        }
354
662
        {
355
662
            std::unique_lock lock(mtx_);
356
662
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
357
1.32k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
357
1.32k
                               [&]() { return stopped(); });
358
662
        }
359
662
    }
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
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
368
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
369
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
54
    while (!stopped()) {
448
50
        std::vector<std::string> instances;
449
50
        instances.reserve(recycling_instance_map_.size());
450
50
        {
451
50
            std::lock_guard lock(mtx_);
452
50
            for (auto& [id, _] : recycling_instance_map_) {
453
30
                instances.push_back(id);
454
30
            }
455
50
        }
456
50
        for (auto& i : instances) {
457
30
            std::string recycle_job_key;
458
30
            job_recycle_key({i}, &recycle_job_key);
459
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
460
30
            if (ret == 1) {
461
0
                std::lock_guard lock(mtx_);
462
0
                if (auto it = recycling_instance_map_.find(i);
463
0
                    it != recycling_instance_map_.end()) {
464
0
                    it->second->stop();
465
0
                }
466
0
            }
467
30
        }
468
50
        {
469
50
            std::unique_lock lock(mtx_);
470
50
            notifier_.wait_for(lock,
471
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
472
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
472
100
                               [&]() { return stopped(); });
473
50
        }
474
50
    }
475
4
}
476
477
4
void Recycler::check_recycle_tasks() {
478
7
    while (!stopped()) {
479
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
480
3
        {
481
3
            std::lock_guard lock(mtx_);
482
3
            recycling_instance_map = recycling_instance_map_;
483
3
        }
484
3
        for (auto& entry : recycling_instance_map) {
485
0
            entry.second->check_recycle_tasks();
486
0
        }
487
488
3
        std::unique_lock lock(mtx_);
489
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
490
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
490
6
                           [&]() { return stopped(); });
491
3
    }
492
4
}
493
494
4
int Recycler::start(brpc::Server* server) {
495
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
496
4
    S3Environment::getInstance();
497
498
4
    if (config::enable_checker) {
499
0
        checker_ = std::make_unique<Checker>(txn_kv_);
500
0
        int ret = checker_->start();
501
0
        std::string msg;
502
0
        if (ret != 0) {
503
0
            msg = "failed to start checker";
504
0
            LOG(ERROR) << msg;
505
0
            std::cerr << msg << std::endl;
506
0
            return ret;
507
0
        }
508
0
        msg = "checker started";
509
0
        LOG(INFO) << msg;
510
0
        std::cout << msg << std::endl;
511
0
    }
512
513
4
    if (server) {
514
        // Add service
515
1
        auto recycler_service =
516
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
517
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
518
1
    }
519
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
521
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
522
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
522
8
        workers_.emplace_back([this] { recycle_callback(); });
523
8
    }
524
525
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
526
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
527
528
4
    if (config::enable_snapshot_data_migrator) {
529
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
530
0
        int ret = snapshot_data_migrator_->start();
531
0
        if (ret != 0) {
532
0
            LOG(ERROR) << "failed to start snapshot data migrator";
533
0
            return ret;
534
0
        }
535
0
        LOG(INFO) << "snapshot data migrator started";
536
0
    }
537
538
4
    if (config::enable_snapshot_chain_compactor) {
539
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
540
0
        int ret = snapshot_chain_compactor_->start();
541
0
        if (ret != 0) {
542
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
543
0
            return ret;
544
0
        }
545
0
        LOG(INFO) << "snapshot chain compactor started";
546
0
    }
547
548
4
    return 0;
549
4
}
550
551
4
void Recycler::stop() {
552
4
    stopped_ = true;
553
4
    notifier_.notify_all();
554
4
    pending_instance_cond_.notify_all();
555
4
    {
556
4
        std::lock_guard lock(mtx_);
557
4
        for (auto& [_, recycler] : recycling_instance_map_) {
558
0
            recycler->stop();
559
0
        }
560
4
    }
561
20
    for (auto& w : workers_) {
562
20
        if (w.joinable()) w.join();
563
20
    }
564
4
    if (checker_) {
565
0
        checker_->stop();
566
0
    }
567
4
    if (snapshot_data_migrator_) {
568
0
        snapshot_data_migrator_->stop();
569
0
    }
570
4
    if (snapshot_chain_compactor_) {
571
0
        snapshot_chain_compactor_->stop();
572
0
    }
573
4
}
574
575
class InstanceRecycler::InvertedIndexIdCache {
576
public:
577
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
578
172
            : 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.50k
            LOG(WARNING) << "failed to get schema, err=" << err;
611
5.50k
            return static_cast<int>(err);
612
5.50k
        }
613
4.93k
        doris::TabletSchemaCloudPB schema;
614
4.93k
        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.93k
        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.93k
        insert(index_id, schema_version, res);
632
4.93k
        return 0;
633
4.93k
    }
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
172
        : txn_kv_(std::move(txn_kv)),
672
172
          instance_id_(instance.instance_id()),
673
172
          instance_info_(instance),
674
172
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
675
172
          _thread_pool_group(std::move(thread_pool_group)),
676
172
          txn_lazy_committer_(std::move(txn_lazy_committer)),
677
172
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
678
172
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
679
172
    delete_bitmap_lock_white_list_->init();
680
172
    resource_mgr_->init();
681
682
172
    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
172
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
687
172
};
688
689
172
InstanceRecycler::~InstanceRecycler() = default;
690
691
148
int InstanceRecycler::init_obj_store_accessors() {
692
148
    for (const auto& obj_info : instance_info_.obj_info()) {
693
104
#ifdef UNIT_TEST
694
104
        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
104
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
711
104
    }
712
713
148
    return 0;
714
148
}
715
716
148
int InstanceRecycler::init_storage_vault_accessors() {
717
148
    if (instance_info_.resource_ids().empty()) {
718
141
        return 0;
719
141
    }
720
721
7
    FullRangeGetOptions opts(txn_kv_);
722
7
    opts.prefetch = true;
723
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
724
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
725
726
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
727
18
        auto [k, v] = *kv;
728
18
        StorageVaultPB vault;
729
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
730
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
731
0
            return -1;
732
0
        }
733
18
        std::string recycler_storage_vault_white_list = accumulate(
734
18
                config::recycler_storage_vault_white_list.begin(),
735
18
                config::recycler_storage_vault_white_list.end(), std::string(),
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
737
18
        LOG_INFO("config::recycler_storage_vault_white_list")
738
18
                .tag("", recycler_storage_vault_white_list);
739
18
        if (!config::recycler_storage_vault_white_list.empty()) {
740
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
741
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
742
8
                it == config::recycler_storage_vault_white_list.end()) {
743
2
                LOG_WARNING(
744
2
                        "failed to init accessor for vault because this vault is not in "
745
2
                        "config::recycler_storage_vault_white_list. ")
746
2
                        .tag(" vault name:", vault.name())
747
2
                        .tag(" config::recycler_storage_vault_white_list:",
748
2
                             recycler_storage_vault_white_list);
749
2
                continue;
750
2
            }
751
8
        }
752
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
753
16
                                 &accessor_map_, &vault);
754
16
        if (vault.has_hdfs_info()) {
755
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
756
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
757
9
            int ret = accessor->init();
758
9
            if (ret != 0) {
759
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
760
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
761
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
762
4
                continue;
763
4
            }
764
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
765
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
766
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
767
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
768
#else
769
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
770
                       << "but HDFS storage vaults were detected";
771
#endif
772
7
        } else if (vault.has_obj_info()) {
773
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
774
7
            if (!s3_conf) {
775
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
776
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
777
1
                continue;
778
1
            }
779
780
6
            std::shared_ptr<S3Accessor> accessor;
781
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
782
6
            if (ret != 0) {
783
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
784
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
785
0
                             << " ret=" << ret
786
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
787
0
                continue;
788
0
            }
789
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
790
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
791
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
792
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
793
6
        }
794
16
    }
795
796
7
    if (!it->is_valid()) {
797
0
        LOG_WARNING("failed to get storage vault kv");
798
0
        return -1;
799
0
    }
800
801
7
    if (accessor_map_.empty()) {
802
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
803
1
        return -2;
804
1
    }
805
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
806
6
             instance_id_);
807
808
6
    return 0;
809
7
}
810
811
149
int InstanceRecycler::init() {
812
149
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
813
149
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
814
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
815
1
        return 0;
816
1
    }
817
818
148
    int ret = init_obj_store_accessors();
819
148
    if (ret != 0) {
820
0
        return ret;
821
0
    }
822
823
148
    return init_storage_vault_accessors();
824
148
}
825
826
template <typename... Func>
827
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
120
    return [funcs...]() {
829
120
        return [](std::initializer_list<int> ret_vals) {
830
120
            int i = 0;
831
140
            for (int ret : ret_vals) {
832
140
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
140
            }
836
120
            return i;
837
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
20
            for (int ret : ret_vals) {
832
20
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
20
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
20
            for (int ret : ret_vals) {
832
20
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
20
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
0
                    i = ret;
834
0
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
827
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
828
10
    return [funcs...]() {
829
10
        return [](std::initializer_list<int> ret_vals) {
830
10
            int i = 0;
831
10
            for (int ret : ret_vals) {
832
10
                if (ret != 0) {
833
10
                    i = ret;
834
10
                }
835
10
            }
836
10
            return i;
837
10
        }({funcs()...});
838
10
    };
839
10
}
840
841
11
int InstanceRecycler::do_recycle() {
842
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
843
11
    tablet_metrics_context_.reset();
844
11
    segment_metrics_context_.reset();
845
11
    DORIS_CLOUD_DEFER {
846
11
        tablet_metrics_context_.finish_report();
847
11
        segment_metrics_context_.finish_report();
848
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
845
11
    DORIS_CLOUD_DEFER {
846
11
        tablet_metrics_context_.finish_report();
847
11
        segment_metrics_context_.finish_report();
848
11
    };
849
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
850
1
        int res = recycle_cluster_snapshots();
851
1
        if (res != 0) {
852
0
            return -1;
853
0
        }
854
1
        return recycle_deleted_instance();
855
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
856
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
857
10
                                        fmt::format("instance id {}", instance_id_),
858
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
858
120
                                        [](int r) { return r != 0; });
859
10
        sync_executor
860
10
                .add(task_wrapper(
861
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
861
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
862
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
862
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
863
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
864
                                   // becase they may both recycle the same set of tablets
865
                        // recycle dropped table or idexes(mv, rollup)
866
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
866
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
867
                        // recycle dropped partitions
868
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
868
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
869
10
                .add(task_wrapper(
870
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
870
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
871
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
871
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
872
10
                .add(task_wrapper(
873
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
873
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
874
10
                .add(task_wrapper(
875
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
875
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
876
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
876
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
877
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
877
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
879
10
                .add(task_wrapper(
880
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
880
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
883
10
        bool finished = true;
884
10
        std::vector<int> rets = sync_executor.when_all(&finished);
885
120
        for (int ret : rets) {
886
120
            if (ret != 0) {
887
0
                return ret;
888
0
            }
889
120
        }
890
10
        return finished ? 0 : -1;
891
10
    } else {
892
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
893
0
                     << " instance_id=" << instance_id_;
894
0
        return -1;
895
0
    }
896
11
}
897
898
/**
899
* 1. delete all remote data
900
* 2. delete all kv
901
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
902
*/
903
13
int InstanceRecycler::recycle_deleted_instance() {
904
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
905
906
13
    int ret = 0;
907
13
    auto start_time = steady_clock::now();
908
13
    const auto recycle_state = instance_info_.recycle_state();
909
910
13
    if (config::retain_deleted_instance_tombstone &&
911
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
912
4
        return 0;
913
4
    }
914
915
9
    DORIS_CLOUD_DEFER {
916
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
917
9
        if (ret != 0) {
918
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
919
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
920
0
                         << "s, instance_id=" << instance_id_;
921
9
        } else if (recycle_state ==
922
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
923
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
924
0
                      << "s, instance_id=" << instance_id_;
925
9
        } else {
926
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
927
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
928
9
                      << "s, instance_id=" << instance_id_;
929
9
        }
930
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
915
9
    DORIS_CLOUD_DEFER {
916
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
917
9
        if (ret != 0) {
918
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
919
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
920
0
                         << "s, instance_id=" << instance_id_;
921
9
        } else if (recycle_state ==
922
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
923
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
924
0
                      << "s, instance_id=" << instance_id_;
925
9
        } else {
926
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
927
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
928
9
                      << "s, instance_id=" << instance_id_;
929
9
        }
930
9
    };
931
932
9
    switch (recycle_state) {
933
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
934
6
        ret = recycle_deleted_instance_data();
935
6
        break;
936
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
937
3
        ret = recycle_deleted_instance_metadata();
938
3
        break;
939
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
940
0
        ret = remove_instance_key();
941
0
        break;
942
0
    default:
943
0
        LOG_WARNING("invalid instance recycle state")
944
0
                .tag("instance_id", instance_id_)
945
0
                .tag("recycle_state", instance_info_.recycle_state());
946
0
        ret = -1;
947
0
        break;
948
9
    }
949
950
9
    return ret;
951
9
}
952
953
6
int InstanceRecycler::recycle_deleted_instance_data() {
954
6
    int ret = 0;
955
956
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
957
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
958
6
        int res = recycle_tmp_rowsets();
959
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
960
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
961
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
962
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
963
            // and cannot be recycled.
964
0
            res = recycle_tmp_rowsets();
965
0
        }
966
6
        return res;
967
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
957
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
958
6
        int res = recycle_tmp_rowsets();
959
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
960
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
961
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
962
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
963
            // and cannot be recycled.
964
0
            res = recycle_tmp_rowsets();
965
0
        }
966
6
        return res;
967
6
    };
968
969
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
970
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
971
0
        return -1;
972
0
    }
973
974
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
975
6
    if (recycle_versioned_rowsets() != 0) {
976
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
977
0
        return -1;
978
0
    }
979
980
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
981
6
    if (recycle_operation_logs() != 0) {
982
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
983
0
        return -1;
984
0
    }
985
986
    // Step 4: Check if there are still cluster snapshots
987
6
    bool has_snapshots = false;
988
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
989
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
990
0
        return -1;
991
6
    } else if (has_snapshots) {
992
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
993
1
        return 0;
994
1
    }
995
996
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
997
5
                            instance_info().snapshot_switch_status() !=
998
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
999
5
    if (snapshot_enabled) {
1000
1
        bool has_unrecycled_rowsets = false;
1001
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1002
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1003
0
            return -1;
1004
1
        } else if (has_unrecycled_rowsets) {
1005
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1006
0
                    .tag("instance_id", instance_id_);
1007
0
            return ret;
1008
0
        }
1009
4
    } else { // delete all remote data if snapshot is disabled
1010
4
        for (auto& [_, accessor] : accessor_map_) {
1011
4
            if (stopped()) {
1012
0
                return ret;
1013
0
            }
1014
1015
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1016
4
            int del_ret = accessor->delete_all();
1017
4
            if (del_ret == 0) {
1018
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1019
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1020
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1021
                // so the recycling has been successful.
1022
0
                ret = -1;
1023
0
            }
1024
4
        }
1025
1026
4
        if (ret != 0) {
1027
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1028
0
            return ret;
1029
0
        }
1030
4
    }
1031
1032
5
    if (update_instance_recycle_state(
1033
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1034
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1035
0
        return -1;
1036
0
    }
1037
1038
5
    return 0;
1039
5
}
1040
1041
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1042
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1043
7
    if (instance_info_.has_successor_instance_id() &&
1044
7
        !instance_info_.successor_instance_id().empty()) {
1045
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1046
4
        std::unique_ptr<Transaction> txn;
1047
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1048
4
        if (err != TxnErrorCode::TXN_OK) {
1049
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1050
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1051
0
                         << " err=" << err;
1052
0
            return -1;
1053
0
        }
1054
1055
4
        InstanceInfoPB successor_instance;
1056
4
        std::string value;
1057
4
        err = txn->get(key, &value);
1058
4
        if (err == TxnErrorCode::TXN_OK) {
1059
3
            InstanceInfoPB successor_instance;
1060
3
            if (!successor_instance.ParseFromString(value)) {
1061
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1062
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1063
0
                return -1;
1064
0
            }
1065
3
            if (!successor_instance.has_recycle_state() ||
1066
3
                successor_instance.recycle_state() !=
1067
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1068
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1069
2
                          << " instance_id=" << instance_id_
1070
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1071
2
                          << " successor_status=" << successor_instance.status()
1072
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1073
2
                return 0;
1074
2
            }
1075
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1076
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1077
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1078
0
                         << " err=" << err;
1079
0
            return -1;
1080
0
        }
1081
4
    }
1082
1083
    // delete all kv
1084
5
    std::unique_ptr<Transaction> txn;
1085
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1086
5
    if (err != TxnErrorCode::TXN_OK) {
1087
0
        LOG(WARNING) << "failed to create txn";
1088
0
        return -1;
1089
0
    }
1090
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1091
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1092
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1093
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1094
5
    txn->remove(start_txn_key, end_txn_key);
1095
5
    std::string start_version_key = version_key_prefix(instance_id_);
1096
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1097
5
    txn->remove(start_version_key, end_version_key);
1098
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1099
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_meta_key, end_meta_key);
1101
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1102
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_recycle_key, end_recycle_key);
1104
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1105
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1106
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1107
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1108
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1109
5
    txn->remove(start_copy_key, end_copy_key);
1110
    // should not remove job key range, because we need to reserve job recycle kv
1111
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1112
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1113
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1114
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1115
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1116
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1117
5
    std::string start_vault_key = storage_vault_key(key_info0);
1118
5
    std::string end_vault_key = storage_vault_key(key_info1);
1119
5
    txn->remove(start_vault_key, end_vault_key);
1120
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1121
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1122
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1123
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1124
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1125
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1126
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1127
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1129
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1130
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1132
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1133
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1135
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1136
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1138
1139
    // Updating the recycle state also commits this transaction, making the metadata deletions
1140
    // and state transition atomic.
1141
5
    if (update_instance_recycle_state(
1142
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1143
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1144
0
        return -1;
1145
0
    }
1146
1147
5
    return 0;
1148
5
}
1149
1150
0
int InstanceRecycler::remove_instance_key() {
1151
0
    std::unique_ptr<Transaction> txn;
1152
0
    std::string key = instance_key(instance_info_.instance_id());
1153
0
    std::string value;
1154
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1155
0
    if (err != TxnErrorCode::TXN_OK) {
1156
0
        LOG(WARNING) << "failed to create txn";
1157
0
        return -1;
1158
0
    }
1159
1160
0
    err = txn->get(key, &value);
1161
0
    if (err != TxnErrorCode::TXN_OK) {
1162
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1163
0
                     << ", err=" << err;
1164
0
        return -1;
1165
0
    }
1166
1167
0
    InstanceInfoPB instance;
1168
0
    if (!instance.ParseFromString(value)) {
1169
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1170
0
        return -1;
1171
0
    }
1172
1173
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1174
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1175
0
                     << instance_id_ << ", status=" << instance.status();
1176
0
        return -1;
1177
0
    }
1178
1179
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1180
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1181
0
                     << instance_id_
1182
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1183
0
                     << ", expected_state="
1184
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1185
0
        return -1;
1186
0
    }
1187
1188
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1189
0
    txn->remove(key);
1190
0
    err = txn->commit();
1191
0
    if (err != TxnErrorCode::TXN_OK) {
1192
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1193
0
                     << " err=" << err;
1194
0
        return -1;
1195
0
    }
1196
0
    return 0;
1197
0
}
1198
1199
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1200
7
                                                    InstanceRecycleState target_state) {
1201
7
    std::unique_ptr<Transaction> txn;
1202
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1203
7
    if (err != TxnErrorCode::TXN_OK) {
1204
0
        LOG(WARNING) << "failed to create txn";
1205
0
        return -1;
1206
0
    }
1207
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1208
7
}
1209
1210
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1211
                                                    InstanceRecycleState target_state,
1212
12
                                                    Transaction* txn) {
1213
12
    const bool valid_transition =
1214
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1215
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1216
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1217
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1218
1219
12
    if (!valid_transition) {
1220
1
        LOG_WARNING("invalid instance recycled state transition")
1221
1
                .tag("instance_id", instance_id_)
1222
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1223
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1224
1
        return -1;
1225
1
    }
1226
1227
11
    std::string key = instance_key({instance_id_});
1228
11
    std::string value;
1229
11
    TxnErrorCode err = txn->get(key, &value);
1230
11
    if (err != TxnErrorCode::TXN_OK) {
1231
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1232
0
                .tag("instance_id", instance_id_)
1233
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1234
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1235
0
                .tag("err", err);
1236
0
        return -1;
1237
0
    }
1238
1239
11
    InstanceInfoPB instance;
1240
11
    if (!instance.ParseFromString(value)) {
1241
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1242
0
                .tag("instance_id", instance_id_)
1243
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1244
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1245
0
        return -1;
1246
0
    }
1247
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1248
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1249
0
                .tag("instance_id", instance_id_)
1250
0
                .tag("status", instance.status())
1251
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1252
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1253
0
        return -1;
1254
0
    }
1255
11
    if (instance.recycle_state() != current_state) {
1256
1
        LOG_WARNING("instance recycled state changed before update")
1257
1
                .tag("instance_id", instance_id_)
1258
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1259
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1260
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1261
1
        return -1;
1262
1
    }
1263
1264
10
    instance.set_recycle_state(target_state);
1265
10
    instance.set_recycle_state_update_time_ms(
1266
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1267
10
    if (!instance.SerializeToString(&value)) {
1268
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1269
0
                .tag("instance_id", instance_id_)
1270
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1271
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1272
0
        return -1;
1273
0
    }
1274
1275
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1276
10
    txn->put(key, value);
1277
10
    err = txn->commit();
1278
10
    if (err != TxnErrorCode::TXN_OK) {
1279
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1280
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1281
0
        return -1;
1282
0
    }
1283
1284
10
    instance_info_.Swap(&instance);
1285
10
    LOG_INFO("updated instance recycled state")
1286
10
            .tag("instance_id", instance_id_)
1287
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1288
10
    return 0;
1289
10
}
1290
1291
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1292
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1293
9
    if (exists == nullptr) {
1294
0
        return -1;
1295
0
    }
1296
9
    *exists = false;
1297
1298
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1299
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1300
9
    std::string scan_begin = begin;
1301
1302
9
    while (true) {
1303
9
        std::unique_ptr<RangeGetIterator> it_range;
1304
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1305
9
        if (get_ret < 0) {
1306
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1307
0
                    .tag("instance_id", instance_id_)
1308
0
                    .tag("tablet_id", tablet_id)
1309
0
                    .tag("ret", get_ret);
1310
0
            return -1;
1311
0
        }
1312
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1313
6
            return 0;
1314
6
        }
1315
1316
3
        std::string last_key;
1317
3
        while (it_range->has_next()) {
1318
3
            auto [k, v] = it_range->next();
1319
3
            last_key.assign(k.data(), k.size());
1320
3
            doris::RowsetMetaCloudPB rowset_meta;
1321
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1322
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1323
0
                        .tag("instance_id", instance_id_)
1324
0
                        .tag("tablet_id", tablet_id)
1325
0
                        .tag("key", hex(k));
1326
0
                continue;
1327
0
            }
1328
3
            if (stats) {
1329
3
                ++stats->rowset_scan_count;
1330
3
            }
1331
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1332
3
                *exists = true;
1333
3
                return 0;
1334
3
            }
1335
3
        }
1336
1337
0
        if (!it_range->more()) {
1338
0
            return 0;
1339
0
        }
1340
1341
        // Continue scanning from the next key to keep each transaction short.
1342
0
        scan_begin = std::move(last_key);
1343
0
        scan_begin.push_back('\x00');
1344
0
    }
1345
9
}
1346
1347
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1348
                                                          const std::string& rowset_id,
1349
                                                          int64_t txn_id, bool* recycle_exists,
1350
11
                                                          bool* tmp_exists) {
1351
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1352
0
        return -1;
1353
0
    }
1354
11
    *recycle_exists = false;
1355
11
    *tmp_exists = false;
1356
1357
11
    if (txn_id <= 0) {
1358
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1359
0
                .tag("instance_id", instance_id_)
1360
0
                .tag("tablet_id", tablet_id)
1361
0
                .tag("rowset_id", rowset_id)
1362
0
                .tag("txn_id", txn_id);
1363
0
        return -1;
1364
0
    }
1365
1366
11
    std::unique_ptr<Transaction> txn;
1367
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1368
11
    if (err != TxnErrorCode::TXN_OK) {
1369
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1370
0
                .tag("instance_id", instance_id_)
1371
0
                .tag("tablet_id", tablet_id)
1372
0
                .tag("rowset_id", rowset_id)
1373
0
                .tag("txn_id", txn_id)
1374
0
                .tag("err", err);
1375
0
        return -1;
1376
0
    }
1377
1378
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1379
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1380
11
    if (ret == TxnErrorCode::TXN_OK) {
1381
1
        *recycle_exists = true;
1382
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1383
0
        LOG_WARNING("failed to check recycle rowset existence")
1384
0
                .tag("instance_id", instance_id_)
1385
0
                .tag("tablet_id", tablet_id)
1386
0
                .tag("rowset_id", rowset_id)
1387
0
                .tag("key", hex(recycle_key))
1388
0
                .tag("err", ret);
1389
0
        return -1;
1390
0
    }
1391
1392
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1393
11
    ret = key_exists(txn.get(), tmp_key, true);
1394
11
    if (ret == TxnErrorCode::TXN_OK) {
1395
1
        *tmp_exists = true;
1396
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1397
0
        LOG_WARNING("failed to check tmp rowset existence")
1398
0
                .tag("instance_id", instance_id_)
1399
0
                .tag("tablet_id", tablet_id)
1400
0
                .tag("txn_id", txn_id)
1401
0
                .tag("key", hex(tmp_key))
1402
0
                .tag("err", ret);
1403
0
        return -1;
1404
0
    }
1405
1406
11
    return 0;
1407
11
}
1408
1409
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1410
7.49k
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1411
7.49k
    if (!hint.empty()) {
1412
7.48k
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1413
7.45k
            return {hint, it->second};
1414
7.45k
        }
1415
7.48k
    }
1416
1417
39
    return {"", nullptr};
1418
7.49k
}
1419
1420
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1421
                                               const std::string& packed_file_path,
1422
3
                                               PackedFileRecycleStats* stats) {
1423
3
    bool local_changed = false;
1424
3
    int64_t left_num = 0;
1425
3
    int64_t left_bytes = 0;
1426
3
    bool all_small_files_confirmed = true;
1427
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1428
1429
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1430
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1431
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1432
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1433
14
        LOG_INFO("packed slice correction status")
1434
14
                .tag("instance_id", instance_id_)
1435
14
                .tag("packed_file_path", packed_file_path)
1436
14
                .tag("small_file_path", file.path())
1437
14
                .tag("tablet_id", tablet_id)
1438
14
                .tag("rowset_id", rowset_id)
1439
14
                .tag("txn_id", txn_id)
1440
14
                .tag("size", file.size())
1441
14
                .tag("deleted", file.deleted())
1442
14
                .tag("corrected", file.corrected())
1443
14
                .tag("confirmed_this_round", confirmed_this_round);
1444
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1429
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1430
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1431
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1432
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1433
        LOG_INFO("packed slice correction status")
1434
14
                .tag("instance_id", instance_id_)
1435
14
                .tag("packed_file_path", packed_file_path)
1436
14
                .tag("small_file_path", file.path())
1437
14
                .tag("tablet_id", tablet_id)
1438
14
                .tag("rowset_id", rowset_id)
1439
14
                .tag("txn_id", txn_id)
1440
14
                .tag("size", file.size())
1441
14
                .tag("deleted", file.deleted())
1442
14
                .tag("corrected", file.corrected())
1443
14
                .tag("confirmed_this_round", confirmed_this_round);
1444
14
    };
1445
1446
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1447
14
        auto* small_file = packed_info->mutable_slices(i);
1448
14
        if (small_file->deleted()) {
1449
3
            log_small_file_status(*small_file, small_file->corrected());
1450
3
            continue;
1451
3
        }
1452
1453
11
        if (small_file->corrected()) {
1454
0
            left_num++;
1455
0
            left_bytes += small_file->size();
1456
0
            log_small_file_status(*small_file, true);
1457
0
            continue;
1458
0
        }
1459
1460
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1461
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1462
0
                    .tag("instance_id", instance_id_)
1463
0
                    .tag("small_file_path", small_file->path())
1464
0
                    .tag("index", i);
1465
0
            return -1;
1466
0
        }
1467
1468
11
        int64_t tablet_id = small_file->tablet_id();
1469
11
        const std::string& rowset_id = small_file->rowset_id();
1470
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1471
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1472
0
                    .tag("instance_id", instance_id_)
1473
0
                    .tag("small_file_path", small_file->path())
1474
0
                    .tag("index", i)
1475
0
                    .tag("tablet_id", tablet_id)
1476
0
                    .tag("rowset_id", rowset_id)
1477
0
                    .tag("has_txn_id", small_file->has_txn_id())
1478
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1479
0
            return -1;
1480
0
        }
1481
11
        int64_t txn_id = small_file->txn_id();
1482
11
        bool recycle_exists = false;
1483
11
        bool tmp_exists = false;
1484
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1485
11
                                                &tmp_exists) != 0) {
1486
0
            return -1;
1487
0
        }
1488
1489
11
        bool small_file_confirmed = false;
1490
11
        if (tmp_exists) {
1491
1
            left_num++;
1492
1
            left_bytes += small_file->size();
1493
1
            small_file_confirmed = true;
1494
10
        } else if (recycle_exists) {
1495
1
            left_num++;
1496
1
            left_bytes += small_file->size();
1497
            // keep small_file_confirmed=false so the packed file remains uncorrected
1498
9
        } else {
1499
9
            bool rowset_exists = false;
1500
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1501
0
                return -1;
1502
0
            }
1503
1504
9
            if (!rowset_exists) {
1505
6
                if (!small_file->deleted()) {
1506
6
                    small_file->set_deleted(true);
1507
6
                    local_changed = true;
1508
6
                }
1509
6
                if (!small_file->corrected()) {
1510
6
                    small_file->set_corrected(true);
1511
6
                    local_changed = true;
1512
6
                }
1513
6
                small_file_confirmed = true;
1514
6
            } else {
1515
3
                left_num++;
1516
3
                left_bytes += small_file->size();
1517
3
                small_file_confirmed = true;
1518
3
            }
1519
9
        }
1520
1521
11
        if (!small_file_confirmed) {
1522
1
            all_small_files_confirmed = false;
1523
1
        }
1524
1525
11
        if (small_file->corrected() != small_file_confirmed) {
1526
4
            small_file->set_corrected(small_file_confirmed);
1527
4
            local_changed = true;
1528
4
        }
1529
1530
11
        log_small_file_status(*small_file, small_file_confirmed);
1531
11
    }
1532
1533
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1534
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1535
3
        local_changed = true;
1536
3
    }
1537
3
    if (packed_info->ref_cnt() != left_num) {
1538
3
        auto old_ref_cnt = packed_info->ref_cnt();
1539
3
        packed_info->set_ref_cnt(left_num);
1540
3
        LOG_INFO("corrected packed file ref count")
1541
3
                .tag("instance_id", instance_id_)
1542
3
                .tag("resource_id", packed_info->resource_id())
1543
3
                .tag("packed_file_path", packed_file_path)
1544
3
                .tag("old_ref_cnt", old_ref_cnt)
1545
3
                .tag("new_ref_cnt", left_num);
1546
3
        local_changed = true;
1547
3
    }
1548
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1549
2
        packed_info->set_corrected(all_small_files_confirmed);
1550
2
        local_changed = true;
1551
2
    }
1552
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1553
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1554
1
        local_changed = true;
1555
1
    }
1556
1557
3
    if (changed != nullptr) {
1558
3
        *changed = local_changed;
1559
3
    }
1560
3
    return 0;
1561
3
}
1562
1563
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1564
                                                 const std::string& packed_file_path,
1565
4
                                                 PackedFileRecycleStats* stats) {
1566
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1567
4
    bool correction_ok = false;
1568
4
    cloud::PackedFileInfoPB packed_info;
1569
1570
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1571
4
        if (stopped()) {
1572
0
            LOG_WARNING("recycler stopped before processing packed file")
1573
0
                    .tag("instance_id", instance_id_)
1574
0
                    .tag("packed_file_path", packed_file_path)
1575
0
                    .tag("attempt", attempt);
1576
0
            return -1;
1577
0
        }
1578
1579
4
        std::unique_ptr<Transaction> txn;
1580
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1581
4
        if (err != TxnErrorCode::TXN_OK) {
1582
0
            LOG_WARNING("failed to create txn when processing packed file")
1583
0
                    .tag("instance_id", instance_id_)
1584
0
                    .tag("packed_file_path", packed_file_path)
1585
0
                    .tag("attempt", attempt)
1586
0
                    .tag("err", err);
1587
0
            return -1;
1588
0
        }
1589
1590
4
        std::string packed_val;
1591
4
        err = txn->get(packed_key, &packed_val);
1592
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1593
0
            return 0;
1594
0
        }
1595
4
        if (err != TxnErrorCode::TXN_OK) {
1596
0
            LOG_WARNING("failed to get packed file kv")
1597
0
                    .tag("instance_id", instance_id_)
1598
0
                    .tag("packed_file_path", packed_file_path)
1599
0
                    .tag("attempt", attempt)
1600
0
                    .tag("err", err);
1601
0
            return -1;
1602
0
        }
1603
1604
4
        if (!packed_info.ParseFromString(packed_val)) {
1605
0
            LOG_WARNING("failed to parse packed file info")
1606
0
                    .tag("instance_id", instance_id_)
1607
0
                    .tag("packed_file_path", packed_file_path)
1608
0
                    .tag("attempt", attempt);
1609
0
            return -1;
1610
0
        }
1611
1612
4
        int64_t now_sec = ::time(nullptr);
1613
4
        bool corrected = packed_info.corrected();
1614
4
        bool due = config::force_immediate_recycle ||
1615
4
                   now_sec - packed_info.created_at_sec() >=
1616
4
                           config::packed_file_correction_delay_seconds;
1617
1618
4
        if (!corrected && due) {
1619
3
            bool changed = false;
1620
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1621
0
                LOG_WARNING("correct_packed_file_info failed")
1622
0
                        .tag("instance_id", instance_id_)
1623
0
                        .tag("packed_file_path", packed_file_path)
1624
0
                        .tag("attempt", attempt);
1625
0
                return -1;
1626
0
            }
1627
3
            if (changed) {
1628
3
                std::string updated;
1629
3
                if (!packed_info.SerializeToString(&updated)) {
1630
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1631
0
                            .tag("instance_id", instance_id_)
1632
0
                            .tag("packed_file_path", packed_file_path)
1633
0
                            .tag("attempt", attempt);
1634
0
                    return -1;
1635
0
                }
1636
3
                txn->put(packed_key, updated);
1637
3
                err = txn->commit();
1638
3
                if (err == TxnErrorCode::TXN_OK) {
1639
3
                    if (stats) {
1640
3
                        ++stats->num_corrected;
1641
3
                    }
1642
3
                } else {
1643
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1644
0
                        LOG_WARNING(
1645
0
                                "failed to commit correction for packed file due to conflict, "
1646
0
                                "retrying")
1647
0
                                .tag("instance_id", instance_id_)
1648
0
                                .tag("packed_file_path", packed_file_path)
1649
0
                                .tag("attempt", attempt);
1650
0
                        sleep_for_packed_file_retry();
1651
0
                        packed_info.Clear();
1652
0
                        continue;
1653
0
                    }
1654
0
                    LOG_WARNING("failed to commit correction for packed file")
1655
0
                            .tag("instance_id", instance_id_)
1656
0
                            .tag("packed_file_path", packed_file_path)
1657
0
                            .tag("attempt", attempt)
1658
0
                            .tag("err", err);
1659
0
                    return -1;
1660
0
                }
1661
3
            }
1662
3
        }
1663
1664
4
        correction_ok = true;
1665
4
        break;
1666
4
    }
1667
1668
4
    if (!correction_ok) {
1669
0
        return -1;
1670
0
    }
1671
1672
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1673
4
          packed_info.ref_cnt() == 0)) {
1674
3
        return 0;
1675
3
    }
1676
1677
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1678
0
        LOG_WARNING("packed file missing resource id when recycling")
1679
0
                .tag("instance_id", instance_id_)
1680
0
                .tag("packed_file_path", packed_file_path);
1681
0
        return -1;
1682
0
    }
1683
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1684
1
    if (!accessor) {
1685
0
        LOG_WARNING("no accessor available to delete packed file")
1686
0
                .tag("instance_id", instance_id_)
1687
0
                .tag("packed_file_path", packed_file_path)
1688
0
                .tag("resource_id", packed_info.resource_id());
1689
0
        return -1;
1690
0
    }
1691
1
    int del_ret = accessor->delete_file(packed_file_path);
1692
1
    if (del_ret != 0 && del_ret != 1) {
1693
0
        LOG_WARNING("failed to delete packed file")
1694
0
                .tag("instance_id", instance_id_)
1695
0
                .tag("packed_file_path", packed_file_path)
1696
0
                .tag("resource_id", resource_id)
1697
0
                .tag("ret", del_ret);
1698
0
        return -1;
1699
0
    }
1700
1
    if (del_ret == 1) {
1701
0
        LOG_INFO("packed file already removed")
1702
0
                .tag("instance_id", instance_id_)
1703
0
                .tag("packed_file_path", packed_file_path)
1704
0
                .tag("resource_id", resource_id);
1705
1
    } else {
1706
1
        LOG_INFO("deleted packed file")
1707
1
                .tag("instance_id", instance_id_)
1708
1
                .tag("packed_file_path", packed_file_path)
1709
1
                .tag("resource_id", resource_id);
1710
1
    }
1711
1712
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1713
1
        std::unique_ptr<Transaction> del_txn;
1714
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1715
1
        if (err != TxnErrorCode::TXN_OK) {
1716
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1717
0
                    .tag("instance_id", instance_id_)
1718
0
                    .tag("packed_file_path", packed_file_path)
1719
0
                    .tag("del_attempt", del_attempt)
1720
0
                    .tag("err", err);
1721
0
            return -1;
1722
0
        }
1723
1724
1
        std::string latest_val;
1725
1
        err = del_txn->get(packed_key, &latest_val);
1726
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1727
0
            return 0;
1728
0
        }
1729
1
        if (err != TxnErrorCode::TXN_OK) {
1730
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1731
0
                    .tag("instance_id", instance_id_)
1732
0
                    .tag("packed_file_path", packed_file_path)
1733
0
                    .tag("del_attempt", del_attempt)
1734
0
                    .tag("err", err);
1735
0
            return -1;
1736
0
        }
1737
1738
1
        cloud::PackedFileInfoPB latest_info;
1739
1
        if (!latest_info.ParseFromString(latest_val)) {
1740
0
            LOG_WARNING("failed to parse packed file info before removal")
1741
0
                    .tag("instance_id", instance_id_)
1742
0
                    .tag("packed_file_path", packed_file_path)
1743
0
                    .tag("del_attempt", del_attempt);
1744
0
            return -1;
1745
0
        }
1746
1747
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1748
1
              latest_info.ref_cnt() == 0)) {
1749
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1750
0
                    .tag("instance_id", instance_id_)
1751
0
                    .tag("packed_file_path", packed_file_path)
1752
0
                    .tag("del_attempt", del_attempt);
1753
0
            return 0;
1754
0
        }
1755
1756
1
        del_txn->remove(packed_key);
1757
1
        err = del_txn->commit();
1758
1
        if (err == TxnErrorCode::TXN_OK) {
1759
1
            if (stats) {
1760
1
                ++stats->num_deleted;
1761
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1762
1
                                        static_cast<int64_t>(latest_val.size());
1763
1
                if (del_ret == 0 || del_ret == 1) {
1764
1
                    ++stats->num_object_deleted;
1765
1
                    int64_t object_size = latest_info.total_slice_bytes();
1766
1
                    if (object_size <= 0) {
1767
0
                        object_size = packed_info.total_slice_bytes();
1768
0
                    }
1769
1
                    stats->bytes_object_deleted += object_size;
1770
1
                }
1771
1
            }
1772
1
            LOG_INFO("removed packed file metadata")
1773
1
                    .tag("instance_id", instance_id_)
1774
1
                    .tag("packed_file_path", packed_file_path);
1775
1
            return 0;
1776
1
        }
1777
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1778
0
            if (del_attempt >= max_retry_times) {
1779
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1780
0
                        .tag("instance_id", instance_id_)
1781
0
                        .tag("packed_file_path", packed_file_path)
1782
0
                        .tag("del_attempt", del_attempt);
1783
0
                return -1;
1784
0
            }
1785
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1786
0
                    .tag("instance_id", instance_id_)
1787
0
                    .tag("packed_file_path", packed_file_path)
1788
0
                    .tag("del_attempt", del_attempt);
1789
0
            sleep_for_packed_file_retry();
1790
0
            continue;
1791
0
        }
1792
0
        LOG_WARNING("failed to remove packed file kv")
1793
0
                .tag("instance_id", instance_id_)
1794
0
                .tag("packed_file_path", packed_file_path)
1795
0
                .tag("del_attempt", del_attempt)
1796
0
                .tag("err", err);
1797
0
        return -1;
1798
0
    }
1799
1800
0
    return -1;
1801
1
}
1802
1803
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1804
4
                                            PackedFileRecycleStats* stats, int* ret) {
1805
4
    if (stats) {
1806
4
        ++stats->num_scanned;
1807
4
    }
1808
4
    std::string packed_file_path;
1809
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1810
0
        LOG_WARNING("failed to decode packed file key")
1811
0
                .tag("instance_id", instance_id_)
1812
0
                .tag("key", hex(key));
1813
0
        if (stats) {
1814
0
            ++stats->num_failed;
1815
0
        }
1816
0
        if (ret) {
1817
0
            *ret = -1;
1818
0
        }
1819
0
        return 0;
1820
0
    }
1821
1822
4
    std::string packed_key(key);
1823
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1824
4
    if (process_ret != 0) {
1825
0
        if (stats) {
1826
0
            ++stats->num_failed;
1827
0
        }
1828
0
        if (ret) {
1829
0
            *ret = -1;
1830
0
        }
1831
0
    }
1832
4
    return 0;
1833
4
}
1834
1835
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1836
126k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1837
126k
    if (config::force_immediate_recycle) {
1838
120k
        return 0L;
1839
120k
    }
1840
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1841
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1842
6.00k
    int64_t retention_seconds = config::retention_seconds;
1843
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1844
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1845
4.70k
    }
1846
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1847
6.00k
    if (*earlest_ts > final_expiration) {
1848
6
        *earlest_ts = final_expiration;
1849
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1850
6
    }
1851
6.00k
    return final_expiration;
1852
126k
}
1853
1854
int64_t calculate_partition_expired_time(
1855
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1856
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1857
9
    if (config::force_immediate_recycle) {
1858
3
        return 0L;
1859
3
    }
1860
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1861
6
                                                            : partition_meta_pb.creation_time();
1862
6
    int64_t retention_seconds = config::retention_seconds;
1863
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1864
6
        retention_seconds =
1865
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1866
6
    }
1867
6
    int64_t final_expiration = expiration + retention_seconds;
1868
6
    if (*earlest_ts > final_expiration) {
1869
2
        *earlest_ts = final_expiration;
1870
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1871
2
    }
1872
6
    return final_expiration;
1873
9
}
1874
1875
int64_t calculate_index_expired_time(const std::string& instance_id_,
1876
                                     const RecycleIndexPB& index_meta_pb,
1877
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1878
10
    if (config::force_immediate_recycle) {
1879
4
        return 0L;
1880
4
    }
1881
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1882
6
                                                        : index_meta_pb.creation_time();
1883
6
    int64_t retention_seconds = config::retention_seconds;
1884
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1885
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1886
6
    }
1887
6
    int64_t final_expiration = expiration + retention_seconds;
1888
6
    if (*earlest_ts > final_expiration) {
1889
2
        *earlest_ts = final_expiration;
1890
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1891
2
    }
1892
6
    return final_expiration;
1893
10
}
1894
1895
int64_t calculate_tmp_rowset_expired_time(
1896
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1897
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1898
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1899
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1900
    //  duration or timeout always < `retention_time` in practice.
1901
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1902
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1903
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1904
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1905
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1906
53.2k
    if (*earlest_ts > final_expiration) {
1907
20
        *earlest_ts = final_expiration;
1908
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1909
20
    }
1910
53.2k
    return final_expiration;
1911
53.2k
}
1912
1913
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1914
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1915
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1916
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1917
11
        *earlest_ts = final_expiration / 1000;
1918
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1919
11
    }
1920
50.0k
    return final_expiration;
1921
50.0k
}
1922
1923
int64_t calculate_restore_job_expired_time(
1924
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1925
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1926
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1927
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1928
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1929
        // final state, recycle immediately
1930
41
        return 0L;
1931
41
    }
1932
    // not final state, wait much longer than the FE's timeout(1 day)
1933
0
    int64_t last_modified_s =
1934
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1935
0
    int64_t expiration = restore_job.expired_at_s() > 0
1936
0
                                 ? last_modified_s + restore_job.expired_at_s()
1937
0
                                 : last_modified_s;
1938
0
    int64_t final_expiration = expiration + config::retention_seconds;
1939
0
    if (*earlest_ts > final_expiration) {
1940
0
        *earlest_ts = final_expiration;
1941
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1942
0
    }
1943
0
    return final_expiration;
1944
41
}
1945
1946
10.5k
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1947
10.5k
    AbortTxnRequest req;
1948
10.5k
    TxnInfoPB txn_info;
1949
10.5k
    MetaServiceCode code = MetaServiceCode::OK;
1950
10.5k
    std::string msg;
1951
10.5k
    std::stringstream ss;
1952
10.5k
    std::unique_ptr<Transaction> txn;
1953
10.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1954
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1955
0
        LOG_WARNING("failed to create txn").tag("err", err);
1956
0
        return -1;
1957
0
    }
1958
1959
    // get txn index
1960
10.5k
    TxnIndexPB txn_idx_pb;
1961
10.5k
    auto index_key = txn_index_key({instance_id_, txn_id});
1962
10.5k
    std::string index_val;
1963
10.5k
    err = txn->get(index_key, &index_val);
1964
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1965
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1966
            // maybe recycled
1967
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1968
2
                    .tag("key", hex(index_key))
1969
2
                    .tag("txn_id", txn_id);
1970
2
            return 0;
1971
2
        }
1972
0
        LOG_WARNING("failed to get txn index")
1973
0
                .tag("err", err)
1974
0
                .tag("key", hex(index_key))
1975
0
                .tag("txn_id", txn_id);
1976
0
        return -1;
1977
2
    }
1978
10.4k
    if (!txn_idx_pb.ParseFromString(index_val)) {
1979
1
        LOG_WARNING("failed to parse txn index")
1980
1
                .tag("err", err)
1981
1
                .tag("key", hex(index_key))
1982
1
                .tag("txn_id", txn_id);
1983
1
        return -1;
1984
1
    }
1985
10.4k
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1986
10.5k
        txn_idx_pb.tablet_index().db_id() <= 0) {
1987
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1988
3
                .tag("key", hex(index_key))
1989
3
                .tag("txn_id", txn_id)
1990
3
                .tag("db_id",
1991
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1992
3
        return -1;
1993
3
    }
1994
1995
10.4k
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1996
10.4k
    const int64_t owner_txn_id =
1997
10.4k
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1998
10.4k
    if (owner_txn_id <= 0) {
1999
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2000
1
                .tag("key", hex(index_key))
2001
1
                .tag("txn_id", txn_id)
2002
1
                .tag("owner_txn_id", owner_txn_id);
2003
1
        return -1;
2004
1
    }
2005
2006
10.4k
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2007
10.4k
    std::string info_val;
2008
10.4k
    err = txn->get(info_key, &info_val);
2009
10.4k
    if (err != TxnErrorCode::TXN_OK) {
2010
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2011
            // maybe recycled
2012
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2013
1
                        owner_txn_id, instance_id_)
2014
1
                    .tag("key", hex(info_key))
2015
1
                    .tag("txn_id", txn_id)
2016
1
                    .tag("owner_txn_id", owner_txn_id);
2017
1
            return 0;
2018
1
        }
2019
0
        LOG_WARNING("failed to get txn info")
2020
0
                .tag("err", err)
2021
0
                .tag("key", hex(info_key))
2022
0
                .tag("txn_id", txn_id)
2023
0
                .tag("owner_txn_id", owner_txn_id);
2024
0
        return -1;
2025
1
    }
2026
10.4k
    if (!txn_info.ParseFromString(info_val)) {
2027
1
        LOG_WARNING("failed to parse txn info")
2028
1
                .tag("err", err)
2029
1
                .tag("key", hex(info_key))
2030
1
                .tag("txn_id", txn_id)
2031
1
                .tag("owner_txn_id", owner_txn_id);
2032
1
        return -1;
2033
1
    }
2034
10.4k
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2035
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2036
1
                .tag("key", hex(info_key))
2037
1
                .tag("txn_id", txn_id)
2038
1
                .tag("owner_txn_id", owner_txn_id)
2039
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2040
1
        return -1;
2041
1
    }
2042
2043
10.4k
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2044
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2045
514
                .tag("key", hex(info_key))
2046
514
                .tag("txn_id", txn_id)
2047
514
                .tag("owner_txn_id", owner_txn_id);
2048
514
        return 0;
2049
514
    }
2050
9.97k
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2051
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2052
4
                    owner_txn_id, txn_info.status())
2053
4
                .tag("key", hex(info_key))
2054
4
                .tag("txn_id", txn_id)
2055
4
                .tag("owner_txn_id", owner_txn_id);
2056
4
        return -1;
2057
4
    }
2058
2059
9.97k
    req.set_txn_id(owner_txn_id);
2060
9.97k
    req.set_db_id(db_id);
2061
2062
9.97k
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2063
9.97k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2064
9.97k
                 << " txn_info=" << txn_info.ShortDebugString();
2065
2066
9.97k
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2067
9.97k
    if (code != MetaServiceCode::OK) {
2068
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2069
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2070
0
                     << " code=" << code << " msg=" << msg;
2071
0
        return -1;
2072
0
    }
2073
2074
9.97k
    err = txn->commit();
2075
9.97k
    if (err != TxnErrorCode::TXN_OK) {
2076
0
        code = cast_as<ErrCategory::COMMIT>(err);
2077
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2078
0
        msg = ss.str();
2079
0
        return -1;
2080
0
    }
2081
2082
9.97k
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2083
9.97k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2084
9.97k
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2085
9.97k
                 << " msg=" << msg;
2086
2087
9.97k
    return 0;
2088
9.97k
}
2089
2090
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2091
11
                                                   const std::string& job_id) {
2092
11
    FinishTabletJobRequest req;
2093
11
    FinishTabletJobResponse res;
2094
11
    req.set_action(FinishTabletJobRequest::ABORT);
2095
11
    MetaServiceCode code = MetaServiceCode::OK;
2096
11
    std::string msg;
2097
11
    std::stringstream ss;
2098
2099
11
    TabletIndexPB tablet_idx;
2100
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2101
11
    if (ret == 1) {
2102
        // tablet maybe recycled, directly return 0
2103
1
        return 0;
2104
10
    } else if (ret != 0) {
2105
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2106
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2107
0
        return ret;
2108
0
    }
2109
2110
10
    std::unique_ptr<Transaction> txn;
2111
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2112
10
    if (err != TxnErrorCode::TXN_OK) {
2113
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2114
0
        return -1;
2115
0
    }
2116
2117
10
    std::string job_key =
2118
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2119
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2120
10
    std::string job_val;
2121
10
    err = txn->get(job_key, &job_val);
2122
10
    if (err != TxnErrorCode::TXN_OK) {
2123
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2124
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2125
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2126
            // A previous recycler round may have aborted the job. The caller must recheck the
2127
            // recycle key before deleting object data.
2128
1
            return 0;
2129
1
        }
2130
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2131
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2132
0
                     << " key=" << hex(job_key);
2133
0
        return -1;
2134
1
    }
2135
2136
9
    TabletJobInfoPB job_pb;
2137
9
    if (!job_pb.ParseFromString(job_val)) {
2138
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2139
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2140
0
        return -1;
2141
0
    }
2142
2143
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2144
9
    for (const auto& compaction : job_pb.compaction()) {
2145
9
        if (compaction.id() == job_id) {
2146
5
            matched_compaction = &compaction;
2147
5
            break;
2148
5
        }
2149
9
    }
2150
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2151
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2152
9
        job_pb.schema_change().id() == job_id) {
2153
3
        matched_schema_change = &job_pb.schema_change();
2154
3
    }
2155
2156
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2157
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2158
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2159
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2160
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2161
        // both the base and mirrored schema-change records.
2162
8
        if (matched_compaction != nullptr) {
2163
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2164
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2165
5
        } else {
2166
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2167
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2168
3
        }
2169
8
        req.set_action(FinishTabletJobRequest::ABORT);
2170
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2171
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2172
8
                           ss);
2173
8
        if (code != MetaServiceCode::OK) {
2174
            // These two codes mean that the job cannot be aborted anymore.
2175
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2176
            // There is no running job that still owns the PREPARE rowset, so the caller may
2177
            // recheck the recycle key.
2178
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2179
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2180
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2181
            // job again and continue recycling only when the target job id no longer exists.
2182
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2183
0
                std::unique_ptr<Transaction> check_txn;
2184
0
                err = txn_kv_->create_txn(&check_txn);
2185
0
                if (err != TxnErrorCode::TXN_OK) {
2186
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2187
0
                                 << instance_id_ << " err=" << err;
2188
0
                    return -1;
2189
0
                }
2190
2191
0
                const auto& idx = req.job().idx();
2192
0
                std::string current_job_key =
2193
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2194
0
                                        idx.partition_id(), idx.tablet_id()});
2195
0
                std::string current_job_val;
2196
0
                err = check_txn->get(current_job_key, &current_job_val);
2197
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2198
0
                    no_job_to_abort = true;
2199
0
                } else if (err != TxnErrorCode::TXN_OK) {
2200
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2201
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2202
0
                                 << " key=" << hex(current_job_key);
2203
0
                    return -1;
2204
0
                } else {
2205
0
                    TabletJobInfoPB current_job;
2206
0
                    if (!current_job.ParseFromString(current_job_val)) {
2207
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2208
0
                                     << " tablet_id=" << idx.tablet_id()
2209
0
                                     << " key=" << hex(current_job_key);
2210
0
                        return -1;
2211
0
                    }
2212
0
                    if (matched_compaction != nullptr) {
2213
0
                        no_job_to_abort = true;
2214
0
                        for (const auto& compaction : current_job.compaction()) {
2215
0
                            if (compaction.id() == job_id) {
2216
0
                                no_job_to_abort = false;
2217
0
                                break;
2218
0
                            }
2219
0
                        }
2220
0
                    } else {
2221
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2222
0
                                          current_job.schema_change().id() != job_id;
2223
0
                    }
2224
0
                }
2225
0
            }
2226
0
            if (no_job_to_abort) {
2227
0
                return 0;
2228
0
            }
2229
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2230
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2231
0
                         << " msg=" << msg;
2232
0
            return -1;
2233
0
        }
2234
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2235
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2236
8
                     << " code=" << code << " msg=" << msg;
2237
8
    } else {
2238
        // clang-format off
2239
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2240
1
                  << ", instance_id=" << instance_id_ 
2241
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2242
1
                  << ", job_id=" << job_id
2243
1
                  << ", rowset_id=" << rowset_id;
2244
        // clang-format on
2245
1
    }
2246
2247
9
    return 0;
2248
9
}
2249
2250
template <typename T>
2251
19.6k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
19.6k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
19.6k
        return rowset_meta_pb.mutable_rowset_meta();
2254
19.6k
    } else {
2255
9
        return &rowset_meta_pb;
2256
9
    }
2257
19.6k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2251
19.6k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
19.6k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
19.6k
        return rowset_meta_pb.mutable_rowset_meta();
2254
    } else {
2255
        return &rowset_meta_pb;
2256
    }
2257
19.6k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2251
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2252
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2253
        return rowset_meta_pb.mutable_rowset_meta();
2254
9
    } else {
2255
9
        return &rowset_meta_pb;
2256
9
    }
2257
9
}
2258
2259
template <typename T>
2260
81.2k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
81.2k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
80.4k
        return rowset_meta_pb.rowset_meta();
2263
80.4k
    } else {
2264
799
        return rowset_meta_pb;
2265
799
    }
2266
81.2k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2260
80.4k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
80.4k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
80.4k
        return rowset_meta_pb.rowset_meta();
2263
    } else {
2264
        return rowset_meta_pb;
2265
    }
2266
80.4k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2260
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2261
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2262
        return rowset_meta_pb.rowset_meta();
2263
799
    } else {
2264
799
        return rowset_meta_pb;
2265
799
    }
2266
799
}
2267
2268
template <typename T>
2269
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2270
41.0k
        const T& rowset_meta_pb) {
2271
41.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
0
            return std::nullopt;
2274
0
        }
2275
40.5k
    }
2276
2277
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
41.0k
    RelatedTxnOrJobAbortTask task;
2279
41.0k
    task.tablet_id = rs_meta.tablet_id();
2280
41.0k
    task.start_version = rs_meta.start_version();
2281
41.0k
    task.end_version = rs_meta.end_version();
2282
41.0k
    task.rowset_id = rs_meta.rowset_id_v2();
2283
41.0k
    if (rs_meta.has_load_id()) {
2284
21.0k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
21.0k
        task.txn_id = rs_meta.txn_id();
2286
21.0k
        return task;
2287
21.0k
    }
2288
20.0k
    if (rs_meta.has_job_id()) {
2289
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
14
        task.job_id = rs_meta.job_id();
2291
14
        return task;
2292
14
    }
2293
20.0k
    return std::nullopt;
2294
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2270
40.5k
        const T& rowset_meta_pb) {
2271
40.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
0
            return std::nullopt;
2274
0
        }
2275
40.5k
    }
2276
2277
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
40.5k
    RelatedTxnOrJobAbortTask task;
2279
40.5k
    task.tablet_id = rs_meta.tablet_id();
2280
40.5k
    task.start_version = rs_meta.start_version();
2281
40.5k
    task.end_version = rs_meta.end_version();
2282
40.5k
    task.rowset_id = rs_meta.rowset_id_v2();
2283
40.5k
    if (rs_meta.has_load_id()) {
2284
20.5k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
20.5k
        task.txn_id = rs_meta.txn_id();
2286
20.5k
        return task;
2287
20.5k
    }
2288
20.0k
    if (rs_meta.has_job_id()) {
2289
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
10
        task.job_id = rs_meta.job_id();
2291
10
        return task;
2292
10
    }
2293
20.0k
    return std::nullopt;
2294
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2270
526
        const T& rowset_meta_pb) {
2271
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2272
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2273
            return std::nullopt;
2274
        }
2275
    }
2276
2277
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2278
526
    RelatedTxnOrJobAbortTask task;
2279
526
    task.tablet_id = rs_meta.tablet_id();
2280
526
    task.start_version = rs_meta.start_version();
2281
526
    task.end_version = rs_meta.end_version();
2282
526
    task.rowset_id = rs_meta.rowset_id_v2();
2283
526
    if (rs_meta.has_load_id()) {
2284
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2285
518
        task.txn_id = rs_meta.txn_id();
2286
518
        return task;
2287
518
    }
2288
8
    if (rs_meta.has_job_id()) {
2289
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2290
4
        task.job_id = rs_meta.job_id();
2291
4
        return task;
2292
4
    }
2293
4
    return std::nullopt;
2294
8
}
2295
2296
template <typename T>
2297
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2298
10.5k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
10.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return false;
2302
0
        }
2303
10.2k
    }
2304
2305
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
10.5k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
10.5k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
10.5k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
10.5k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
10.5k
    }
2313
18.4E
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
10.5k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2298
10.2k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
10.2k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return false;
2302
0
        }
2303
10.2k
    }
2304
2305
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
10.2k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
10.2k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
10.2k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
10.2k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
10.2k
    }
2313
18.4E
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
10.2k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2298
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2299
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
            return false;
2302
        }
2303
    }
2304
2305
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2307
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2308
0
        return false;
2309
0
    }
2310
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2311
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2312
259
    }
2313
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2314
261
}
2315
2316
79.6k
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2317
79.6k
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2318
79.6k
}
2319
2320
template <typename T>
2321
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2322
76
                                   const std::vector<std::string>& keys) {
2323
204
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
129
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
129
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
129
        std::unique_ptr<Transaction> txn;
2327
129
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
129
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
129
        std::vector<std::optional<std::string>> values;
2333
129
        err = txn->batch_get(&values, batch_keys);
2334
129
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
129
        DCHECK_EQ(values.size(), batch_keys.size());
2340
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
19.9k
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
19.9k
            const auto& key = batch_keys[i];
2346
19.9k
            auto val = values[i].value();
2347
19.9k
            T rowset_meta_pb;
2348
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
19.9k
            }
2361
19.9k
            val.clear();
2362
19.9k
            rowset_meta_pb.SerializeToString(&val);
2363
19.9k
            txn->put(key, val);
2364
19.9k
        }
2365
129
        err = txn->commit();
2366
129
        if (err != TxnErrorCode::TXN_OK) {
2367
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
1
            return -1;
2369
1
        }
2370
129
    }
2371
2372
75
    return 0;
2373
76
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2322
69
                                   const std::vector<std::string>& keys) {
2323
190
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
122
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
122
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
122
        std::unique_ptr<Transaction> txn;
2327
122
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
122
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
122
        std::vector<std::optional<std::string>> values;
2333
122
        err = txn->batch_get(&values, batch_keys);
2334
122
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
122
        DCHECK_EQ(values.size(), batch_keys.size());
2340
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
19.9k
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
19.9k
            const auto& key = batch_keys[i];
2346
19.9k
            auto val = values[i].value();
2347
19.9k
            T rowset_meta_pb;
2348
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
19.9k
            }
2361
19.9k
            val.clear();
2362
19.9k
            rowset_meta_pb.SerializeToString(&val);
2363
19.9k
            txn->put(key, val);
2364
19.9k
        }
2365
122
        err = txn->commit();
2366
122
        if (err != TxnErrorCode::TXN_OK) {
2367
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
1
            return -1;
2369
1
        }
2370
122
    }
2371
2372
68
    return 0;
2373
69
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2322
7
                                   const std::vector<std::string>& keys) {
2323
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2324
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2325
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2326
7
        std::unique_ptr<Transaction> txn;
2327
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2328
7
        if (err != TxnErrorCode::TXN_OK) {
2329
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2330
0
            return -1;
2331
0
        }
2332
7
        std::vector<std::optional<std::string>> values;
2333
7
        err = txn->batch_get(&values, batch_keys);
2334
7
        if (err != TxnErrorCode::TXN_OK) {
2335
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2336
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2337
0
            return -1;
2338
0
        }
2339
7
        DCHECK_EQ(values.size(), batch_keys.size());
2340
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2341
9
            if (!values[i].has_value()) {
2342
                // has already been removed by commit_rowset
2343
0
                continue;
2344
0
            }
2345
9
            const auto& key = batch_keys[i];
2346
9
            auto val = values[i].value();
2347
9
            T rowset_meta_pb;
2348
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2349
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2350
0
                             << " key=" << hex(key);
2351
0
                return -1;
2352
0
            }
2353
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2354
0
                continue;
2355
0
            }
2356
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2357
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2358
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2359
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2360
            }
2361
9
            val.clear();
2362
9
            rowset_meta_pb.SerializeToString(&val);
2363
9
            txn->put(key, val);
2364
9
        }
2365
7
        err = txn->commit();
2366
7
        if (err != TxnErrorCode::TXN_OK) {
2367
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2368
0
            return -1;
2369
0
        }
2370
7
    }
2371
2372
7
    return 0;
2373
7
}
2374
2375
template <typename T>
2376
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2377
76
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
76
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
76
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
1
        }
2383
76
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2378
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
1
        }
2383
69
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2378
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
0
        }
2383
7
    });
2384
76
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2377
69
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
69
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
69
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
69
        }
2383
69
    });
2384
69
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2377
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2378
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2379
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2380
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2381
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2382
7
        }
2383
7
    });
2384
7
}
2385
2386
template <typename T>
2387
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2388
                                 const std::vector<std::string>& keys,
2389
51
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
132
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
81
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
81
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
81
        std::unique_ptr<Transaction> txn;
2394
81
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
81
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
81
        std::vector<std::optional<std::string>> values;
2400
81
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
81
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
81
        DCHECK_EQ(values.size(), batch_keys.size());
2407
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
10.5k
            const std::string& key = batch_keys[idx];
2409
10.5k
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
10.5k
            T rowset_meta_pb;
2414
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
10.5k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
10.5k
                abort_task.has_value()) {
2421
10.5k
                abort_task->key = key;
2422
10.5k
                abort_tasks->emplace_back(std::move(*abort_task));
2423
10.5k
            }
2424
10.5k
        }
2425
81
    }
2426
51
    return 0;
2427
51
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2389
46
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
121
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
75
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
75
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
75
        std::unique_ptr<Transaction> txn;
2394
75
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
75
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
75
        std::vector<std::optional<std::string>> values;
2400
75
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
75
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
75
        DCHECK_EQ(values.size(), batch_keys.size());
2407
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
10.2k
            const std::string& key = batch_keys[idx];
2409
10.2k
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
10.2k
            T rowset_meta_pb;
2414
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
10.2k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
10.2k
                abort_task.has_value()) {
2421
10.2k
                abort_task->key = key;
2422
10.2k
                abort_tasks->emplace_back(std::move(*abort_task));
2423
10.2k
            }
2424
10.2k
        }
2425
75
    }
2426
46
    return 0;
2427
46
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2389
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2390
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2391
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2392
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2393
6
        std::unique_ptr<Transaction> txn;
2394
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2395
6
        if (err != TxnErrorCode::TXN_OK) {
2396
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2397
0
            return -1;
2398
0
        }
2399
6
        std::vector<std::optional<std::string>> values;
2400
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2401
6
        if (err != TxnErrorCode::TXN_OK) {
2402
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2403
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2404
0
            return -1;
2405
0
        }
2406
6
        DCHECK_EQ(values.size(), batch_keys.size());
2407
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2408
261
            const std::string& key = batch_keys[idx];
2409
261
            if (!values[idx].has_value()) {
2410
                // has already been removed
2411
0
                continue;
2412
0
            }
2413
261
            T rowset_meta_pb;
2414
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2415
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2416
0
                             << " key=" << hex(key);
2417
0
                return -1;
2418
0
            }
2419
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2420
261
                abort_task.has_value()) {
2421
261
                abort_task->key = key;
2422
261
                abort_tasks->emplace_back(std::move(*abort_task));
2423
261
            }
2424
261
        }
2425
6
    }
2426
5
    return 0;
2427
5
}
2428
2429
template <typename T>
2430
int batch_recheck_rowsets_after_abort(
2431
        TxnKv* txn_kv, const std::string& instance_id,
2432
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2433
49
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
49
    int ret = 0;
2435
128
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
79
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
79
        std::vector<std::string> batch_keys;
2438
79
        batch_keys.reserve(limit - offset);
2439
10.5k
        for (size_t idx = offset; idx < limit; ++idx) {
2440
10.5k
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
10.5k
        }
2442
2443
79
        std::unique_ptr<Transaction> txn;
2444
79
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
79
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
79
        std::vector<std::optional<std::string>> values;
2453
79
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
79
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
79
        DCHECK_EQ(values.size(), batch_keys.size());
2461
79
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
79
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
79
                                 &batch_size);
2464
2465
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
10.5k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
10.5k
            if (!values[idx].has_value()) {
2468
1
                continue;
2469
1
            }
2470
2471
10.5k
            T rowset_meta_pb;
2472
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
10.5k
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
10.5k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
10.5k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
1
                             << instance_id << " key=" << hex(key);
2487
1
                continue;
2488
1
            }
2489
10.5k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
10.5k
        }
2491
79
    }
2492
49
    return ret;
2493
49
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2433
44
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
44
    int ret = 0;
2435
117
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
73
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
73
        std::vector<std::string> batch_keys;
2438
73
        batch_keys.reserve(limit - offset);
2439
10.3k
        for (size_t idx = offset; idx < limit; ++idx) {
2440
10.2k
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
10.2k
        }
2442
2443
73
        std::unique_ptr<Transaction> txn;
2444
73
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
73
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
73
        std::vector<std::optional<std::string>> values;
2453
73
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
73
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
73
        DCHECK_EQ(values.size(), batch_keys.size());
2461
73
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
73
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
73
                                 &batch_size);
2464
2465
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
10.2k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
10.2k
            if (!values[idx].has_value()) {
2468
1
                continue;
2469
1
            }
2470
2471
10.2k
            T rowset_meta_pb;
2472
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
10.2k
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
10.2k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
10.2k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
1
                             << instance_id << " key=" << hex(key);
2487
1
                continue;
2488
1
            }
2489
10.2k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
10.2k
        }
2491
73
    }
2492
44
    return ret;
2493
44
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2433
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2434
5
    int ret = 0;
2435
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2436
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2437
6
        std::vector<std::string> batch_keys;
2438
6
        batch_keys.reserve(limit - offset);
2439
267
        for (size_t idx = offset; idx < limit; ++idx) {
2440
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2441
261
        }
2442
2443
6
        std::unique_ptr<Transaction> txn;
2444
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2445
6
        if (err != TxnErrorCode::TXN_OK) {
2446
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2447
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2448
0
            ret = -1;
2449
0
            continue;
2450
0
        }
2451
2452
6
        std::vector<std::optional<std::string>> values;
2453
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2454
6
        if (err != TxnErrorCode::TXN_OK) {
2455
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2456
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2457
0
            ret = -1;
2458
0
            continue;
2459
0
        }
2460
6
        DCHECK_EQ(values.size(), batch_keys.size());
2461
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2462
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2463
6
                                 &batch_size);
2464
2465
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2466
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2467
261
            if (!values[idx].has_value()) {
2468
0
                continue;
2469
0
            }
2470
2471
261
            T rowset_meta_pb;
2472
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2473
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2474
0
                             << instance_id << " key=" << hex(key);
2475
0
                ret = -1;
2476
0
                continue;
2477
0
            }
2478
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2479
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2480
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2481
0
                             << instance_id << " key=" << hex(key);
2482
0
                continue;
2483
0
            }
2484
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2485
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2486
0
                             << instance_id << " key=" << hex(key);
2487
0
                continue;
2488
0
            }
2489
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2490
261
        }
2491
6
    }
2492
5
    return ret;
2493
5
}
2494
2495
template <typename T>
2496
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2497
        const std::vector<std::string>& keys,
2498
51
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
51
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
51
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
51
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
51
    int ret = 0;
2506
10.5k
    for (const auto& abort_task : abort_tasks) {
2507
10.5k
        int abort_ret = 0;
2508
10.5k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
10.5k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
10.5k
        } else {
2511
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
2
                                                     abort_task.job_id);
2513
2
        }
2514
10.5k
        if (abort_ret != 0) {
2515
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
3
            ret = abort_ret;
2519
3
            continue;
2520
3
        }
2521
10.5k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
10.5k
    }
2523
51
    return ret;
2524
51
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2498
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
46
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
46
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
46
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
46
    int ret = 0;
2506
10.2k
    for (const auto& abort_task : abort_tasks) {
2507
10.2k
        int abort_ret = 0;
2508
10.2k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
10.2k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
10.2k
        } else {
2511
0
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
0
                                                     abort_task.job_id);
2513
0
        }
2514
10.2k
        if (abort_ret != 0) {
2515
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
3
            ret = abort_ret;
2519
3
            continue;
2520
3
        }
2521
10.2k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
10.2k
    }
2523
46
    return ret;
2524
46
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2498
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2499
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2500
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2501
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2502
0
        return -1;
2503
0
    }
2504
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2505
5
    int ret = 0;
2506
261
    for (const auto& abort_task : abort_tasks) {
2507
261
        int abort_ret = 0;
2508
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2509
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2510
259
        } else {
2511
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2512
2
                                                     abort_task.job_id);
2513
2
        }
2514
261
        if (abort_ret != 0) {
2515
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2516
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2517
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2518
0
            ret = abort_ret;
2519
0
            continue;
2520
0
        }
2521
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2522
261
    }
2523
5
    return ret;
2524
5
}
2525
2526
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2527
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2528
46
        std::atomic_long* num_recycled) {
2529
46
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2530
46
                                  num_recycled]() mutable {
2531
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
46
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
46
                                                                            keys_to_recheck);
2534
46
        if (abort_ret != 0) {
2535
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
2
                            "instance_id="
2537
2
                         << instance_id_;
2538
2
        }
2539
46
        if (keys_to_recheck.empty()) {
2540
2
            return;
2541
2
        }
2542
2543
44
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
44
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
44
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
44
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2552
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2554
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
1
                continue;
2556
1
            }
2557
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
10.2k
                                                   current_meta.tablet_id(),
2559
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
10.2k
            std::vector<std::string> keys {key};
2563
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
10.2k
        }
2569
44
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2530
2
                                  num_recycled]() mutable {
2531
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
2
                                                                            keys_to_recheck);
2534
2
        if (abort_ret != 0) {
2535
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
0
                            "instance_id="
2537
0
                         << instance_id_;
2538
0
        }
2539
2
        if (keys_to_recheck.empty()) {
2540
0
            return;
2541
0
        }
2542
2543
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
2
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
2
            const auto& current_meta = current_rowset.rowset_meta();
2552
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
2
                                   current_meta.rowset_id_v2()) != 0) {
2554
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
0
                continue;
2556
0
            }
2557
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
2
                                                   current_meta.tablet_id(),
2559
2
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
2
            std::vector<std::string> keys {key};
2563
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
2
        }
2569
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2530
44
                                  num_recycled]() mutable {
2531
44
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2532
44
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2533
44
                                                                            keys_to_recheck);
2534
44
        if (abort_ret != 0) {
2535
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2536
2
                            "instance_id="
2537
2
                         << instance_id_;
2538
2
        }
2539
44
        if (keys_to_recheck.empty()) {
2540
2
            return;
2541
2
        }
2542
2543
42
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2544
42
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2545
42
                                                            keys_to_recheck, &rowsets_to_recycle);
2546
42
        if (recheck_ret != 0) {
2547
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2548
0
                         << instance_id_;
2549
0
        }
2550
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2551
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2552
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2553
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2554
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2555
1
                continue;
2556
1
            }
2557
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2558
10.2k
                                                   current_meta.tablet_id(),
2559
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2560
0
                continue;
2561
0
            }
2562
10.2k
            std::vector<std::string> keys {key};
2563
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2564
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2565
0
                continue;
2566
0
            }
2567
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2568
10.2k
        }
2569
42
    });
2570
46
    if (ret != 0) {
2571
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2572
0
    }
2573
46
}
2574
2575
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2576
                                                      std::vector<std::string> rowset_keys_to_abort,
2577
                                                      std::atomic_long* num_recycled,
2578
5
                                                      RecyclerMetricsContext* metrics_context) {
2579
5
    if (rowset_keys_to_abort.empty()) {
2580
0
        return;
2581
0
    }
2582
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2583
5
                        metrics_context]() mutable {
2584
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
5
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
5
        std::vector<std::string> keys_to_delete;
2595
5
        std::vector<std::string> ref_count_keys_to_delete;
2596
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
5
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
261
            keys_to_delete.push_back(key);
2605
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
261
        }
2609
2610
5
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
5
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
261
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
261
        }
2627
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2583
3
                        metrics_context]() mutable {
2584
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
3
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
3
        std::vector<std::string> keys_to_delete;
2595
3
        std::vector<std::string> ref_count_keys_to_delete;
2596
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
3
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
3
            keys_to_delete.push_back(key);
2605
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
3
        }
2609
2610
3
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
3
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
3
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
3
        }
2627
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2583
2
                        metrics_context]() mutable {
2584
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2585
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2586
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2587
2
        if (abort_ret != 0) {
2588
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2589
0
                            "instance_id="
2590
0
                         << instance_id_;
2591
0
        }
2592
2593
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2594
2
        std::vector<std::string> keys_to_delete;
2595
2
        std::vector<std::string> ref_count_keys_to_delete;
2596
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2597
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2598
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2599
2
        if (recheck_ret != 0) {
2600
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2601
0
                         << instance_id_;
2602
0
        }
2603
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2604
258
            keys_to_delete.push_back(key);
2605
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2606
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2607
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2608
258
        }
2609
2610
2
        if (keys_to_delete.empty()) {
2611
0
            return;
2612
0
        }
2613
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2614
2
                               *metrics_context) != 0) {
2615
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2616
0
            return;
2617
0
        }
2618
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2619
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2620
258
                                                   rowset.rowset_id_v2()) != 0) {
2621
0
                return;
2622
0
            }
2623
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2624
0
                return;
2625
0
            }
2626
258
        }
2627
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2628
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2629
0
            return;
2630
0
        }
2631
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2632
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2633
0
                         << instance_id_;
2634
0
            return;
2635
0
        }
2636
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2637
2
    });
2638
5
}
2639
2640
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2641
1
    const std::string task_name = "recycle_ref_rowsets";
2642
1
    *has_unrecycled_rowsets = false;
2643
2644
1
    std::string data_rowset_ref_count_key_start =
2645
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2646
1
    std::string data_rowset_ref_count_key_end =
2647
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2648
2649
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2650
2651
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2652
1
    register_recycle_task(task_name, start_time);
2653
2654
1
    DORIS_CLOUD_DEFER {
2655
1
        unregister_recycle_task(task_name);
2656
1
        int64_t cost =
2657
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2658
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2659
1
                .tag("instance_id", instance_id_);
2660
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2654
1
    DORIS_CLOUD_DEFER {
2655
1
        unregister_recycle_task(task_name);
2656
1
        int64_t cost =
2657
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2658
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2659
1
                .tag("instance_id", instance_id_);
2660
1
    };
2661
2662
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2663
1
    std::set<int64_t> tablets_with_refs;
2664
1
    int64_t num_scanned = 0;
2665
2666
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2667
0
        ++num_scanned;
2668
0
        int64_t tablet_id;
2669
0
        std::string rowset_id;
2670
0
        std::string_view key(k);
2671
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2672
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2673
0
            return 0; // Continue scanning
2674
0
        }
2675
2676
0
        tablets_with_refs.insert(tablet_id);
2677
0
        return 0;
2678
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2679
2680
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2681
1
                         std::move(scan_func)) != 0) {
2682
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2683
0
        return -1;
2684
0
    }
2685
2686
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2687
1
             tablets_with_refs.size(), num_scanned)
2688
1
            .tag("instance_id", instance_id_);
2689
2690
    // Phase 2: Recycle each tablet
2691
1
    int64_t num_recycled_tablets = 0;
2692
1
    for (int64_t tablet_id : tablets_with_refs) {
2693
0
        if (stopped()) {
2694
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2695
0
                    .tag("instance_id", instance_id_)
2696
0
                    .tag("tablets_processed", num_recycled_tablets)
2697
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2698
0
            break;
2699
0
        }
2700
2701
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2702
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2703
0
            LOG_WARNING("failed to recycle tablet")
2704
0
                    .tag("instance_id", instance_id_)
2705
0
                    .tag("tablet_id", tablet_id);
2706
0
            return -1;
2707
0
        }
2708
0
        ++num_recycled_tablets;
2709
0
    }
2710
2711
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2712
1
            .tag("instance_id", instance_id_)
2713
1
            .tag("total_tablets", tablets_with_refs.size());
2714
2715
    // Phase 3: Scan again to check if any ref count keys still exist
2716
1
    std::unique_ptr<Transaction> txn;
2717
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2718
1
    if (err != TxnErrorCode::TXN_OK) {
2719
0
        LOG_WARNING("failed to create txn for final check")
2720
0
                .tag("instance_id", instance_id_)
2721
0
                .tag("err", err);
2722
0
        return -1;
2723
0
    }
2724
2725
1
    std::unique_ptr<RangeGetIterator> iter;
2726
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2727
1
    if (err != TxnErrorCode::TXN_OK) {
2728
0
        LOG_WARNING("failed to create range iterator for final check")
2729
0
                .tag("instance_id", instance_id_)
2730
0
                .tag("err", err);
2731
0
        return -1;
2732
0
    }
2733
2734
1
    *has_unrecycled_rowsets = iter->has_next();
2735
1
    if (*has_unrecycled_rowsets) {
2736
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2737
0
                .tag("instance_id", instance_id_);
2738
0
    }
2739
2740
1
    return 0;
2741
1
}
2742
2743
17
int InstanceRecycler::recycle_indexes() {
2744
17
    const std::string task_name = "recycle_indexes";
2745
17
    int64_t num_scanned = 0;
2746
17
    int64_t num_expired = 0;
2747
17
    int64_t num_recycled = 0;
2748
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2749
2750
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2751
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2752
17
    std::string index_key0;
2753
17
    std::string index_key1;
2754
17
    recycle_index_key(index_key_info0, &index_key0);
2755
17
    recycle_index_key(index_key_info1, &index_key1);
2756
2757
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2758
2759
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2760
17
    register_recycle_task(task_name, start_time);
2761
2762
17
    DORIS_CLOUD_DEFER {
2763
17
        unregister_recycle_task(task_name);
2764
17
        int64_t cost =
2765
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2766
17
        metrics_context.finish_report();
2767
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2768
17
                .tag("instance_id", instance_id_)
2769
17
                .tag("num_scanned", num_scanned)
2770
17
                .tag("num_expired", num_expired)
2771
17
                .tag("num_recycled", num_recycled);
2772
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2762
2
    DORIS_CLOUD_DEFER {
2763
2
        unregister_recycle_task(task_name);
2764
2
        int64_t cost =
2765
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2766
2
        metrics_context.finish_report();
2767
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2768
2
                .tag("instance_id", instance_id_)
2769
2
                .tag("num_scanned", num_scanned)
2770
2
                .tag("num_expired", num_expired)
2771
2
                .tag("num_recycled", num_recycled);
2772
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2762
15
    DORIS_CLOUD_DEFER {
2763
15
        unregister_recycle_task(task_name);
2764
15
        int64_t cost =
2765
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2766
15
        metrics_context.finish_report();
2767
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2768
15
                .tag("instance_id", instance_id_)
2769
15
                .tag("num_scanned", num_scanned)
2770
15
                .tag("num_expired", num_expired)
2771
15
                .tag("num_recycled", num_recycled);
2772
15
    };
2773
2774
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2775
2776
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2777
17
    std::vector<std::string_view> index_keys;
2778
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2779
10
        ++num_scanned;
2780
10
        RecycleIndexPB index_pb;
2781
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2782
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2783
0
            return -1;
2784
0
        }
2785
10
        int64_t current_time = ::time(nullptr);
2786
10
        if (current_time <
2787
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2788
0
            return 0;
2789
0
        }
2790
10
        ++num_expired;
2791
        // decode index_id
2792
10
        auto k1 = k;
2793
10
        k1.remove_prefix(1);
2794
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2795
10
        decode_key(&k1, &out);
2796
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2797
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2798
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2799
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2800
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2801
        // Change state to RECYCLING
2802
10
        std::unique_ptr<Transaction> txn;
2803
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2804
10
        if (err != TxnErrorCode::TXN_OK) {
2805
0
            LOG_WARNING("failed to create txn").tag("err", err);
2806
0
            return -1;
2807
0
        }
2808
10
        std::string val;
2809
10
        err = txn->get(k, &val);
2810
10
        if (err ==
2811
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2812
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2813
0
            return 0;
2814
0
        }
2815
10
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2817
0
            return -1;
2818
0
        }
2819
10
        index_pb.Clear();
2820
10
        if (!index_pb.ParseFromString(val)) {
2821
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2822
0
            return -1;
2823
0
        }
2824
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2825
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2826
9
            txn->put(k, index_pb.SerializeAsString());
2827
9
            err = txn->commit();
2828
9
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2830
0
                return -1;
2831
0
            }
2832
9
        }
2833
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2834
1
            LOG_WARNING("failed to recycle tablets under index")
2835
1
                    .tag("table_id", index_pb.table_id())
2836
1
                    .tag("instance_id", instance_id_)
2837
1
                    .tag("index_id", index_id);
2838
1
            return -1;
2839
1
        }
2840
2841
9
        if (index_pb.has_db_id()) {
2842
            // Recycle the versioned keys
2843
3
            std::unique_ptr<Transaction> txn;
2844
3
            err = txn_kv_->create_txn(&txn);
2845
3
            if (err != TxnErrorCode::TXN_OK) {
2846
0
                LOG_WARNING("failed to create txn").tag("err", err);
2847
0
                return -1;
2848
0
            }
2849
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2850
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2851
3
            std::string index_inverted_key = versioned::index_inverted_key(
2852
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2853
3
            versioned_remove_all(txn.get(), meta_key);
2854
3
            txn->remove(index_key);
2855
3
            txn->remove(index_inverted_key);
2856
3
            err = txn->commit();
2857
3
            if (err != TxnErrorCode::TXN_OK) {
2858
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2859
0
                return -1;
2860
0
            }
2861
3
        }
2862
2863
9
        metrics_context.total_recycled_num = ++num_recycled;
2864
9
        metrics_context.report();
2865
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2866
9
        index_keys.push_back(k);
2867
9
        return 0;
2868
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2778
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2779
2
        ++num_scanned;
2780
2
        RecycleIndexPB index_pb;
2781
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2782
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2783
0
            return -1;
2784
0
        }
2785
2
        int64_t current_time = ::time(nullptr);
2786
2
        if (current_time <
2787
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2788
0
            return 0;
2789
0
        }
2790
2
        ++num_expired;
2791
        // decode index_id
2792
2
        auto k1 = k;
2793
2
        k1.remove_prefix(1);
2794
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2795
2
        decode_key(&k1, &out);
2796
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2797
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2798
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2799
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2800
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2801
        // Change state to RECYCLING
2802
2
        std::unique_ptr<Transaction> txn;
2803
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2804
2
        if (err != TxnErrorCode::TXN_OK) {
2805
0
            LOG_WARNING("failed to create txn").tag("err", err);
2806
0
            return -1;
2807
0
        }
2808
2
        std::string val;
2809
2
        err = txn->get(k, &val);
2810
2
        if (err ==
2811
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2812
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2813
0
            return 0;
2814
0
        }
2815
2
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2817
0
            return -1;
2818
0
        }
2819
2
        index_pb.Clear();
2820
2
        if (!index_pb.ParseFromString(val)) {
2821
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2822
0
            return -1;
2823
0
        }
2824
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2825
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2826
1
            txn->put(k, index_pb.SerializeAsString());
2827
1
            err = txn->commit();
2828
1
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2830
0
                return -1;
2831
0
            }
2832
1
        }
2833
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2834
1
            LOG_WARNING("failed to recycle tablets under index")
2835
1
                    .tag("table_id", index_pb.table_id())
2836
1
                    .tag("instance_id", instance_id_)
2837
1
                    .tag("index_id", index_id);
2838
1
            return -1;
2839
1
        }
2840
2841
1
        if (index_pb.has_db_id()) {
2842
            // Recycle the versioned keys
2843
1
            std::unique_ptr<Transaction> txn;
2844
1
            err = txn_kv_->create_txn(&txn);
2845
1
            if (err != TxnErrorCode::TXN_OK) {
2846
0
                LOG_WARNING("failed to create txn").tag("err", err);
2847
0
                return -1;
2848
0
            }
2849
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2850
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2851
1
            std::string index_inverted_key = versioned::index_inverted_key(
2852
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2853
1
            versioned_remove_all(txn.get(), meta_key);
2854
1
            txn->remove(index_key);
2855
1
            txn->remove(index_inverted_key);
2856
1
            err = txn->commit();
2857
1
            if (err != TxnErrorCode::TXN_OK) {
2858
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2859
0
                return -1;
2860
0
            }
2861
1
        }
2862
2863
1
        metrics_context.total_recycled_num = ++num_recycled;
2864
1
        metrics_context.report();
2865
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2866
1
        index_keys.push_back(k);
2867
1
        return 0;
2868
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2778
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2779
8
        ++num_scanned;
2780
8
        RecycleIndexPB index_pb;
2781
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2782
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2783
0
            return -1;
2784
0
        }
2785
8
        int64_t current_time = ::time(nullptr);
2786
8
        if (current_time <
2787
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2788
0
            return 0;
2789
0
        }
2790
8
        ++num_expired;
2791
        // decode index_id
2792
8
        auto k1 = k;
2793
8
        k1.remove_prefix(1);
2794
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2795
8
        decode_key(&k1, &out);
2796
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2797
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2798
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2799
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2800
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2801
        // Change state to RECYCLING
2802
8
        std::unique_ptr<Transaction> txn;
2803
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2804
8
        if (err != TxnErrorCode::TXN_OK) {
2805
0
            LOG_WARNING("failed to create txn").tag("err", err);
2806
0
            return -1;
2807
0
        }
2808
8
        std::string val;
2809
8
        err = txn->get(k, &val);
2810
8
        if (err ==
2811
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2812
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2813
0
            return 0;
2814
0
        }
2815
8
        if (err != TxnErrorCode::TXN_OK) {
2816
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2817
0
            return -1;
2818
0
        }
2819
8
        index_pb.Clear();
2820
8
        if (!index_pb.ParseFromString(val)) {
2821
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2822
0
            return -1;
2823
0
        }
2824
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2825
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2826
8
            txn->put(k, index_pb.SerializeAsString());
2827
8
            err = txn->commit();
2828
8
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2830
0
                return -1;
2831
0
            }
2832
8
        }
2833
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2834
0
            LOG_WARNING("failed to recycle tablets under index")
2835
0
                    .tag("table_id", index_pb.table_id())
2836
0
                    .tag("instance_id", instance_id_)
2837
0
                    .tag("index_id", index_id);
2838
0
            return -1;
2839
0
        }
2840
2841
8
        if (index_pb.has_db_id()) {
2842
            // Recycle the versioned keys
2843
2
            std::unique_ptr<Transaction> txn;
2844
2
            err = txn_kv_->create_txn(&txn);
2845
2
            if (err != TxnErrorCode::TXN_OK) {
2846
0
                LOG_WARNING("failed to create txn").tag("err", err);
2847
0
                return -1;
2848
0
            }
2849
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2850
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2851
2
            std::string index_inverted_key = versioned::index_inverted_key(
2852
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2853
2
            versioned_remove_all(txn.get(), meta_key);
2854
2
            txn->remove(index_key);
2855
2
            txn->remove(index_inverted_key);
2856
2
            err = txn->commit();
2857
2
            if (err != TxnErrorCode::TXN_OK) {
2858
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2859
0
                return -1;
2860
0
            }
2861
2
        }
2862
2863
8
        metrics_context.total_recycled_num = ++num_recycled;
2864
8
        metrics_context.report();
2865
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2866
8
        index_keys.push_back(k);
2867
8
        return 0;
2868
8
    };
2869
2870
17
    auto loop_done = [&index_keys, this]() -> int {
2871
6
        if (index_keys.empty()) return 0;
2872
5
        DORIS_CLOUD_DEFER {
2873
5
            index_keys.clear();
2874
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2872
1
        DORIS_CLOUD_DEFER {
2873
1
            index_keys.clear();
2874
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2872
4
        DORIS_CLOUD_DEFER {
2873
4
            index_keys.clear();
2874
4
        };
2875
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2876
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2877
0
            return -1;
2878
0
        }
2879
5
        return 0;
2880
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2870
2
    auto loop_done = [&index_keys, this]() -> int {
2871
2
        if (index_keys.empty()) return 0;
2872
1
        DORIS_CLOUD_DEFER {
2873
1
            index_keys.clear();
2874
1
        };
2875
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2876
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2877
0
            return -1;
2878
0
        }
2879
1
        return 0;
2880
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2870
4
    auto loop_done = [&index_keys, this]() -> int {
2871
4
        if (index_keys.empty()) return 0;
2872
4
        DORIS_CLOUD_DEFER {
2873
4
            index_keys.clear();
2874
4
        };
2875
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2876
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2877
0
            return -1;
2878
0
        }
2879
4
        return 0;
2880
4
    };
2881
2882
17
    if (config::enable_recycler_stats_metrics) {
2883
0
        scan_and_statistics_indexes();
2884
0
    }
2885
    // recycle_func and loop_done for scan and recycle
2886
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2887
17
}
2888
2889
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2890
8.25k
                             int64_t tablet_id) {
2891
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2892
2893
8.25k
    std::unique_ptr<Transaction> txn;
2894
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2895
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2896
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2897
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2898
0
        return false;
2899
0
    }
2900
2901
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2902
8.25k
    std::string tablet_idx_val;
2903
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2904
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2905
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2906
0
                     << " tablet_id=" << tablet_id << " err=" << err
2907
0
                     << " key=" << hex(tablet_idx_key);
2908
0
        return false;
2909
0
    }
2910
2911
8.25k
    TabletIndexPB tablet_idx_pb;
2912
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2913
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2914
0
                     << " tablet_id=" << tablet_id;
2915
0
        return false;
2916
0
    }
2917
2918
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2919
        // In the previous version, the db_id was not set in the index_pb.
2920
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2921
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2922
0
                  << " instance_id=" << instance_id
2923
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2924
0
        return true;
2925
0
    }
2926
2927
8.25k
    std::string ver_val;
2928
8.25k
    std::string ver_key =
2929
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2930
8.25k
                                   tablet_idx_pb.partition_id()});
2931
8.25k
    err = txn->get(ver_key, &ver_val);
2932
2933
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2934
216
        LOG(INFO) << ""
2935
216
                     "partition version not found, instance_id="
2936
216
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2937
216
                  << " table_id=" << tablet_idx_pb.table_id()
2938
216
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2939
216
                  << " key=" << hex(ver_key);
2940
216
        return true;
2941
216
    }
2942
2943
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2944
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2945
0
                     << " db_id=" << tablet_idx_pb.db_id()
2946
0
                     << " table_id=" << tablet_idx_pb.table_id()
2947
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2948
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2949
0
        return false;
2950
0
    }
2951
2952
8.03k
    VersionPB version_pb;
2953
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2954
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2955
0
                     << " db_id=" << tablet_idx_pb.db_id()
2956
0
                     << " table_id=" << tablet_idx_pb.table_id()
2957
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2958
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2959
0
        return false;
2960
0
    }
2961
2962
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2963
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2964
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2965
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2966
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2967
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2968
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2969
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2970
4.00k
                     << " key=" << hex(ver_key);
2971
4.00k
        return false;
2972
4.00k
    }
2973
4.03k
    return true;
2974
8.03k
}
2975
2976
15
int InstanceRecycler::recycle_partitions() {
2977
15
    const std::string task_name = "recycle_partitions";
2978
15
    int64_t num_scanned = 0;
2979
15
    int64_t num_expired = 0;
2980
15
    int64_t num_recycled = 0;
2981
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2982
2983
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2984
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2985
15
    std::string part_key0;
2986
15
    std::string part_key1;
2987
15
    recycle_partition_key(part_key_info0, &part_key0);
2988
15
    recycle_partition_key(part_key_info1, &part_key1);
2989
2990
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2991
2992
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2993
15
    register_recycle_task(task_name, start_time);
2994
2995
15
    DORIS_CLOUD_DEFER {
2996
15
        unregister_recycle_task(task_name);
2997
15
        int64_t cost =
2998
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2999
15
        metrics_context.finish_report();
3000
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3001
15
                .tag("instance_id", instance_id_)
3002
15
                .tag("num_scanned", num_scanned)
3003
15
                .tag("num_expired", num_expired)
3004
15
                .tag("num_recycled", num_recycled);
3005
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2995
2
    DORIS_CLOUD_DEFER {
2996
2
        unregister_recycle_task(task_name);
2997
2
        int64_t cost =
2998
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2999
2
        metrics_context.finish_report();
3000
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3001
2
                .tag("instance_id", instance_id_)
3002
2
                .tag("num_scanned", num_scanned)
3003
2
                .tag("num_expired", num_expired)
3004
2
                .tag("num_recycled", num_recycled);
3005
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2995
13
    DORIS_CLOUD_DEFER {
2996
13
        unregister_recycle_task(task_name);
2997
13
        int64_t cost =
2998
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2999
13
        metrics_context.finish_report();
3000
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3001
13
                .tag("instance_id", instance_id_)
3002
13
                .tag("num_scanned", num_scanned)
3003
13
                .tag("num_expired", num_expired)
3004
13
                .tag("num_recycled", num_recycled);
3005
13
    };
3006
3007
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3008
3009
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3010
15
    std::vector<std::string_view> partition_keys;
3011
15
    std::vector<std::string> partition_version_keys;
3012
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3013
9
        ++num_scanned;
3014
9
        RecyclePartitionPB part_pb;
3015
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3016
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3017
0
            return -1;
3018
0
        }
3019
9
        int64_t current_time = ::time(nullptr);
3020
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3021
9
                                                            &earlest_ts)) { // not expired
3022
0
            return 0;
3023
0
        }
3024
9
        ++num_expired;
3025
        // decode partition_id
3026
9
        auto k1 = k;
3027
9
        k1.remove_prefix(1);
3028
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3029
9
        decode_key(&k1, &out);
3030
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3031
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3032
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3033
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3034
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3035
        // Change state to RECYCLING
3036
9
        std::unique_ptr<Transaction> txn;
3037
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3038
9
        if (err != TxnErrorCode::TXN_OK) {
3039
0
            LOG_WARNING("failed to create txn").tag("err", err);
3040
0
            return -1;
3041
0
        }
3042
9
        std::string val;
3043
9
        err = txn->get(k, &val);
3044
9
        if (err ==
3045
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3046
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3047
0
            return 0;
3048
0
        }
3049
9
        if (err != TxnErrorCode::TXN_OK) {
3050
0
            LOG_WARNING("failed to get kv");
3051
0
            return -1;
3052
0
        }
3053
9
        part_pb.Clear();
3054
9
        if (!part_pb.ParseFromString(val)) {
3055
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3056
0
            return -1;
3057
0
        }
3058
        // Partitions with PREPARED state MUST have no data
3059
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3060
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3061
8
            txn->put(k, part_pb.SerializeAsString());
3062
8
            err = txn->commit();
3063
8
            if (err != TxnErrorCode::TXN_OK) {
3064
0
                LOG_WARNING("failed to commit txn: {}", err);
3065
0
                return -1;
3066
0
            }
3067
8
        }
3068
3069
9
        int ret = 0;
3070
33
        for (int64_t index_id : part_pb.index_id()) {
3071
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3072
1
                LOG_WARNING("failed to recycle tablets under partition")
3073
1
                        .tag("table_id", part_pb.table_id())
3074
1
                        .tag("instance_id", instance_id_)
3075
1
                        .tag("index_id", index_id)
3076
1
                        .tag("partition_id", partition_id);
3077
1
                ret = -1;
3078
1
            }
3079
33
        }
3080
9
        if (ret == 0 && part_pb.has_db_id()) {
3081
            // Recycle the versioned keys
3082
8
            std::unique_ptr<Transaction> txn;
3083
8
            err = txn_kv_->create_txn(&txn);
3084
8
            if (err != TxnErrorCode::TXN_OK) {
3085
0
                LOG_WARNING("failed to create txn").tag("err", err);
3086
0
                return -1;
3087
0
            }
3088
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3089
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3090
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3091
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3092
8
            std::string partition_version_key =
3093
8
                    versioned::partition_version_key({instance_id_, partition_id});
3094
8
            versioned_remove_all(txn.get(), meta_key);
3095
8
            txn->remove(index_key);
3096
8
            txn->remove(inverted_index_key);
3097
8
            versioned_remove_all(txn.get(), partition_version_key);
3098
8
            err = txn->commit();
3099
8
            if (err != TxnErrorCode::TXN_OK) {
3100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3101
0
                return -1;
3102
0
            }
3103
8
        }
3104
3105
9
        if (ret == 0) {
3106
8
            ++num_recycled;
3107
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3108
8
            partition_keys.push_back(k);
3109
8
            if (part_pb.db_id() > 0) {
3110
8
                partition_version_keys.push_back(partition_version_key(
3111
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3112
8
            }
3113
8
            metrics_context.total_recycled_num = num_recycled;
3114
8
            metrics_context.report();
3115
8
        }
3116
9
        return ret;
3117
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3012
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3013
2
        ++num_scanned;
3014
2
        RecyclePartitionPB part_pb;
3015
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3016
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3017
0
            return -1;
3018
0
        }
3019
2
        int64_t current_time = ::time(nullptr);
3020
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3021
2
                                                            &earlest_ts)) { // not expired
3022
0
            return 0;
3023
0
        }
3024
2
        ++num_expired;
3025
        // decode partition_id
3026
2
        auto k1 = k;
3027
2
        k1.remove_prefix(1);
3028
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3029
2
        decode_key(&k1, &out);
3030
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3031
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3032
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3033
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3034
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3035
        // Change state to RECYCLING
3036
2
        std::unique_ptr<Transaction> txn;
3037
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3038
2
        if (err != TxnErrorCode::TXN_OK) {
3039
0
            LOG_WARNING("failed to create txn").tag("err", err);
3040
0
            return -1;
3041
0
        }
3042
2
        std::string val;
3043
2
        err = txn->get(k, &val);
3044
2
        if (err ==
3045
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3046
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3047
0
            return 0;
3048
0
        }
3049
2
        if (err != TxnErrorCode::TXN_OK) {
3050
0
            LOG_WARNING("failed to get kv");
3051
0
            return -1;
3052
0
        }
3053
2
        part_pb.Clear();
3054
2
        if (!part_pb.ParseFromString(val)) {
3055
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3056
0
            return -1;
3057
0
        }
3058
        // Partitions with PREPARED state MUST have no data
3059
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3060
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3061
1
            txn->put(k, part_pb.SerializeAsString());
3062
1
            err = txn->commit();
3063
1
            if (err != TxnErrorCode::TXN_OK) {
3064
0
                LOG_WARNING("failed to commit txn: {}", err);
3065
0
                return -1;
3066
0
            }
3067
1
        }
3068
3069
2
        int ret = 0;
3070
2
        for (int64_t index_id : part_pb.index_id()) {
3071
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3072
1
                LOG_WARNING("failed to recycle tablets under partition")
3073
1
                        .tag("table_id", part_pb.table_id())
3074
1
                        .tag("instance_id", instance_id_)
3075
1
                        .tag("index_id", index_id)
3076
1
                        .tag("partition_id", partition_id);
3077
1
                ret = -1;
3078
1
            }
3079
2
        }
3080
2
        if (ret == 0 && part_pb.has_db_id()) {
3081
            // Recycle the versioned keys
3082
1
            std::unique_ptr<Transaction> txn;
3083
1
            err = txn_kv_->create_txn(&txn);
3084
1
            if (err != TxnErrorCode::TXN_OK) {
3085
0
                LOG_WARNING("failed to create txn").tag("err", err);
3086
0
                return -1;
3087
0
            }
3088
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3089
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3090
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3091
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3092
1
            std::string partition_version_key =
3093
1
                    versioned::partition_version_key({instance_id_, partition_id});
3094
1
            versioned_remove_all(txn.get(), meta_key);
3095
1
            txn->remove(index_key);
3096
1
            txn->remove(inverted_index_key);
3097
1
            versioned_remove_all(txn.get(), partition_version_key);
3098
1
            err = txn->commit();
3099
1
            if (err != TxnErrorCode::TXN_OK) {
3100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3101
0
                return -1;
3102
0
            }
3103
1
        }
3104
3105
2
        if (ret == 0) {
3106
1
            ++num_recycled;
3107
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3108
1
            partition_keys.push_back(k);
3109
1
            if (part_pb.db_id() > 0) {
3110
1
                partition_version_keys.push_back(partition_version_key(
3111
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3112
1
            }
3113
1
            metrics_context.total_recycled_num = num_recycled;
3114
1
            metrics_context.report();
3115
1
        }
3116
2
        return ret;
3117
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3012
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3013
7
        ++num_scanned;
3014
7
        RecyclePartitionPB part_pb;
3015
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3016
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3017
0
            return -1;
3018
0
        }
3019
7
        int64_t current_time = ::time(nullptr);
3020
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3021
7
                                                            &earlest_ts)) { // not expired
3022
0
            return 0;
3023
0
        }
3024
7
        ++num_expired;
3025
        // decode partition_id
3026
7
        auto k1 = k;
3027
7
        k1.remove_prefix(1);
3028
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3029
7
        decode_key(&k1, &out);
3030
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3031
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3032
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3033
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3034
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3035
        // Change state to RECYCLING
3036
7
        std::unique_ptr<Transaction> txn;
3037
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3038
7
        if (err != TxnErrorCode::TXN_OK) {
3039
0
            LOG_WARNING("failed to create txn").tag("err", err);
3040
0
            return -1;
3041
0
        }
3042
7
        std::string val;
3043
7
        err = txn->get(k, &val);
3044
7
        if (err ==
3045
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3046
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3047
0
            return 0;
3048
0
        }
3049
7
        if (err != TxnErrorCode::TXN_OK) {
3050
0
            LOG_WARNING("failed to get kv");
3051
0
            return -1;
3052
0
        }
3053
7
        part_pb.Clear();
3054
7
        if (!part_pb.ParseFromString(val)) {
3055
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3056
0
            return -1;
3057
0
        }
3058
        // Partitions with PREPARED state MUST have no data
3059
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3060
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3061
7
            txn->put(k, part_pb.SerializeAsString());
3062
7
            err = txn->commit();
3063
7
            if (err != TxnErrorCode::TXN_OK) {
3064
0
                LOG_WARNING("failed to commit txn: {}", err);
3065
0
                return -1;
3066
0
            }
3067
7
        }
3068
3069
7
        int ret = 0;
3070
31
        for (int64_t index_id : part_pb.index_id()) {
3071
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3072
0
                LOG_WARNING("failed to recycle tablets under partition")
3073
0
                        .tag("table_id", part_pb.table_id())
3074
0
                        .tag("instance_id", instance_id_)
3075
0
                        .tag("index_id", index_id)
3076
0
                        .tag("partition_id", partition_id);
3077
0
                ret = -1;
3078
0
            }
3079
31
        }
3080
7
        if (ret == 0 && part_pb.has_db_id()) {
3081
            // Recycle the versioned keys
3082
7
            std::unique_ptr<Transaction> txn;
3083
7
            err = txn_kv_->create_txn(&txn);
3084
7
            if (err != TxnErrorCode::TXN_OK) {
3085
0
                LOG_WARNING("failed to create txn").tag("err", err);
3086
0
                return -1;
3087
0
            }
3088
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3089
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3090
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3091
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3092
7
            std::string partition_version_key =
3093
7
                    versioned::partition_version_key({instance_id_, partition_id});
3094
7
            versioned_remove_all(txn.get(), meta_key);
3095
7
            txn->remove(index_key);
3096
7
            txn->remove(inverted_index_key);
3097
7
            versioned_remove_all(txn.get(), partition_version_key);
3098
7
            err = txn->commit();
3099
7
            if (err != TxnErrorCode::TXN_OK) {
3100
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3101
0
                return -1;
3102
0
            }
3103
7
        }
3104
3105
7
        if (ret == 0) {
3106
7
            ++num_recycled;
3107
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3108
7
            partition_keys.push_back(k);
3109
7
            if (part_pb.db_id() > 0) {
3110
7
                partition_version_keys.push_back(partition_version_key(
3111
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3112
7
            }
3113
7
            metrics_context.total_recycled_num = num_recycled;
3114
7
            metrics_context.report();
3115
7
        }
3116
7
        return ret;
3117
7
    };
3118
3119
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3120
5
        if (partition_keys.empty()) return 0;
3121
4
        DORIS_CLOUD_DEFER {
3122
4
            partition_keys.clear();
3123
4
            partition_version_keys.clear();
3124
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3121
1
        DORIS_CLOUD_DEFER {
3122
1
            partition_keys.clear();
3123
1
            partition_version_keys.clear();
3124
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3121
3
        DORIS_CLOUD_DEFER {
3122
3
            partition_keys.clear();
3123
3
            partition_version_keys.clear();
3124
3
        };
3125
4
        std::unique_ptr<Transaction> txn;
3126
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3127
4
        if (err != TxnErrorCode::TXN_OK) {
3128
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3129
0
            return -1;
3130
0
        }
3131
8
        for (auto& k : partition_keys) {
3132
8
            txn->remove(k);
3133
8
        }
3134
8
        for (auto& k : partition_version_keys) {
3135
8
            txn->remove(k);
3136
8
        }
3137
4
        err = txn->commit();
3138
4
        if (err != TxnErrorCode::TXN_OK) {
3139
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3140
0
                         << " err=" << err;
3141
0
            return -1;
3142
0
        }
3143
4
        return 0;
3144
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3119
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3120
2
        if (partition_keys.empty()) return 0;
3121
1
        DORIS_CLOUD_DEFER {
3122
1
            partition_keys.clear();
3123
1
            partition_version_keys.clear();
3124
1
        };
3125
1
        std::unique_ptr<Transaction> txn;
3126
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3127
1
        if (err != TxnErrorCode::TXN_OK) {
3128
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3129
0
            return -1;
3130
0
        }
3131
1
        for (auto& k : partition_keys) {
3132
1
            txn->remove(k);
3133
1
        }
3134
1
        for (auto& k : partition_version_keys) {
3135
1
            txn->remove(k);
3136
1
        }
3137
1
        err = txn->commit();
3138
1
        if (err != TxnErrorCode::TXN_OK) {
3139
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3140
0
                         << " err=" << err;
3141
0
            return -1;
3142
0
        }
3143
1
        return 0;
3144
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3119
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3120
3
        if (partition_keys.empty()) return 0;
3121
3
        DORIS_CLOUD_DEFER {
3122
3
            partition_keys.clear();
3123
3
            partition_version_keys.clear();
3124
3
        };
3125
3
        std::unique_ptr<Transaction> txn;
3126
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3127
3
        if (err != TxnErrorCode::TXN_OK) {
3128
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3129
0
            return -1;
3130
0
        }
3131
7
        for (auto& k : partition_keys) {
3132
7
            txn->remove(k);
3133
7
        }
3134
7
        for (auto& k : partition_version_keys) {
3135
7
            txn->remove(k);
3136
7
        }
3137
3
        err = txn->commit();
3138
3
        if (err != TxnErrorCode::TXN_OK) {
3139
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3140
0
                         << " err=" << err;
3141
0
            return -1;
3142
0
        }
3143
3
        return 0;
3144
3
    };
3145
3146
15
    if (config::enable_recycler_stats_metrics) {
3147
0
        scan_and_statistics_partitions();
3148
0
    }
3149
    // recycle_func and loop_done for scan and recycle
3150
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3151
15
}
3152
3153
14
int InstanceRecycler::recycle_versions() {
3154
14
    if (should_recycle_versioned_keys()) {
3155
2
        return recycle_orphan_partitions();
3156
2
    }
3157
3158
12
    int64_t num_scanned = 0;
3159
12
    int64_t num_recycled = 0;
3160
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3161
3162
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3163
3164
12
    auto start_time = steady_clock::now();
3165
3166
12
    DORIS_CLOUD_DEFER {
3167
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3168
12
        metrics_context.finish_report();
3169
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3170
12
                .tag("instance_id", instance_id_)
3171
12
                .tag("num_scanned", num_scanned)
3172
12
                .tag("num_recycled", num_recycled);
3173
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3166
12
    DORIS_CLOUD_DEFER {
3167
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3168
12
        metrics_context.finish_report();
3169
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3170
12
                .tag("instance_id", instance_id_)
3171
12
                .tag("num_scanned", num_scanned)
3172
12
                .tag("num_recycled", num_recycled);
3173
12
    };
3174
3175
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3176
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3177
12
    int64_t last_scanned_table_id = 0;
3178
12
    bool is_recycled = false; // Is last scanned kv recycled
3179
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3180
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3181
2
        ++num_scanned;
3182
2
        auto k1 = k;
3183
2
        k1.remove_prefix(1);
3184
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3185
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3186
2
        decode_key(&k1, &out);
3187
2
        DCHECK_EQ(out.size(), 6) << k;
3188
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3189
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3190
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3191
0
            return 0;
3192
0
        }
3193
2
        last_scanned_table_id = table_id;
3194
2
        is_recycled = false;
3195
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3196
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3197
2
        std::unique_ptr<Transaction> txn;
3198
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3199
2
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            return -1;
3201
0
        }
3202
2
        std::unique_ptr<RangeGetIterator> iter;
3203
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3204
2
        if (err != TxnErrorCode::TXN_OK) {
3205
0
            return -1;
3206
0
        }
3207
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3208
1
            return 0;
3209
1
        }
3210
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3211
        // 1. Remove all partition version kvs of this table
3212
1
        auto partition_version_key_begin =
3213
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3214
1
        auto partition_version_key_end =
3215
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3216
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3217
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3218
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3219
1
                     << " table_id=" << table_id;
3220
        // 2. Remove the table version kv of this table
3221
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3222
1
        txn->remove(tbl_version_key);
3223
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3224
        // 3. Remove mow delete bitmap update lock and tablet job lock
3225
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3226
1
        txn->remove(lock_key);
3227
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3228
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3229
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3230
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3231
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3232
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3233
1
                     << " table_id=" << table_id;
3234
1
        err = txn->commit();
3235
1
        if (err != TxnErrorCode::TXN_OK) {
3236
0
            return -1;
3237
0
        }
3238
1
        metrics_context.total_recycled_num = ++num_recycled;
3239
1
        metrics_context.report();
3240
1
        is_recycled = true;
3241
1
        return 0;
3242
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3180
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3181
2
        ++num_scanned;
3182
2
        auto k1 = k;
3183
2
        k1.remove_prefix(1);
3184
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3185
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3186
2
        decode_key(&k1, &out);
3187
2
        DCHECK_EQ(out.size(), 6) << k;
3188
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3189
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3190
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3191
0
            return 0;
3192
0
        }
3193
2
        last_scanned_table_id = table_id;
3194
2
        is_recycled = false;
3195
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3196
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3197
2
        std::unique_ptr<Transaction> txn;
3198
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3199
2
        if (err != TxnErrorCode::TXN_OK) {
3200
0
            return -1;
3201
0
        }
3202
2
        std::unique_ptr<RangeGetIterator> iter;
3203
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3204
2
        if (err != TxnErrorCode::TXN_OK) {
3205
0
            return -1;
3206
0
        }
3207
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3208
1
            return 0;
3209
1
        }
3210
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3211
        // 1. Remove all partition version kvs of this table
3212
1
        auto partition_version_key_begin =
3213
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3214
1
        auto partition_version_key_end =
3215
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3216
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3217
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3218
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3219
1
                     << " table_id=" << table_id;
3220
        // 2. Remove the table version kv of this table
3221
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3222
1
        txn->remove(tbl_version_key);
3223
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3224
        // 3. Remove mow delete bitmap update lock and tablet job lock
3225
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3226
1
        txn->remove(lock_key);
3227
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3228
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3229
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3230
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3231
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3232
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3233
1
                     << " table_id=" << table_id;
3234
1
        err = txn->commit();
3235
1
        if (err != TxnErrorCode::TXN_OK) {
3236
0
            return -1;
3237
0
        }
3238
1
        metrics_context.total_recycled_num = ++num_recycled;
3239
1
        metrics_context.report();
3240
1
        is_recycled = true;
3241
1
        return 0;
3242
1
    };
3243
3244
12
    if (config::enable_recycler_stats_metrics) {
3245
0
        scan_and_statistics_versions();
3246
0
    }
3247
    // recycle_func and loop_done for scan and recycle
3248
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3249
14
}
3250
3251
3
int InstanceRecycler::recycle_orphan_partitions() {
3252
3
    int64_t num_scanned = 0;
3253
3
    int64_t num_recycled = 0;
3254
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3255
3256
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3257
3
            .tag("instance_id", instance_id_);
3258
3259
3
    auto start_time = steady_clock::now();
3260
3261
3
    DORIS_CLOUD_DEFER {
3262
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3263
3
        metrics_context.finish_report();
3264
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3265
3
                .tag("instance_id", instance_id_)
3266
3
                .tag("num_scanned", num_scanned)
3267
3
                .tag("num_recycled", num_recycled);
3268
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3261
3
    DORIS_CLOUD_DEFER {
3262
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3263
3
        metrics_context.finish_report();
3264
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3265
3
                .tag("instance_id", instance_id_)
3266
3
                .tag("num_scanned", num_scanned)
3267
3
                .tag("num_recycled", num_recycled);
3268
3
    };
3269
3270
3
    bool is_empty_table = false;        // whether the table has no indexes
3271
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3272
3
    int64_t current_table_id = 0;       // current scanning table id
3273
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3274
3
                         &current_table_id, &is_table_kvs_recycled,
3275
3
                         this](std::string_view k, std::string_view) {
3276
2
        ++num_scanned;
3277
3278
2
        std::string_view k1(k);
3279
2
        int64_t db_id, table_id, partition_id;
3280
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3281
2
                                                            &partition_id)) {
3282
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3283
0
            return -1;
3284
2
        } else if (table_id != current_table_id) {
3285
2
            current_table_id = table_id;
3286
2
            is_table_kvs_recycled = false;
3287
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3288
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3289
2
            if (err != TxnErrorCode::TXN_OK) {
3290
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3291
0
                             << " table_id=" << table_id << " err=" << err;
3292
0
                return -1;
3293
0
            }
3294
2
        }
3295
3296
2
        if (!is_empty_table) {
3297
            // table is not empty, skip recycle
3298
1
            return 0;
3299
1
        }
3300
3301
1
        std::unique_ptr<Transaction> txn;
3302
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3303
1
        if (err != TxnErrorCode::TXN_OK) {
3304
0
            return -1;
3305
0
        }
3306
3307
        // 1. Remove all partition related kvs
3308
1
        std::string partition_meta_key =
3309
1
                versioned::meta_partition_key({instance_id_, partition_id});
3310
1
        std::string partition_index_key =
3311
1
                versioned::partition_index_key({instance_id_, partition_id});
3312
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3313
1
                {instance_id_, db_id, table_id, partition_id});
3314
1
        std::string partition_version_key =
3315
1
                versioned::partition_version_key({instance_id_, partition_id});
3316
1
        txn->remove(partition_index_key);
3317
1
        txn->remove(partition_inverted_key);
3318
1
        versioned_remove_all(txn.get(), partition_meta_key);
3319
1
        versioned_remove_all(txn.get(), partition_version_key);
3320
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3321
1
                     << " table_id=" << table_id << " db_id=" << db_id
3322
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3323
1
                     << " partition_version_key=" << hex(partition_version_key);
3324
3325
1
        if (!is_table_kvs_recycled) {
3326
1
            is_table_kvs_recycled = true;
3327
3328
            // 2. Remove the table version kv of this table
3329
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3330
1
            versioned_remove_all(txn.get(), table_version_key);
3331
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3332
            // 3. Remove mow delete bitmap update lock and tablet job lock
3333
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3334
1
            txn->remove(lock_key);
3335
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3336
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3337
1
            std::string tablet_job_key_end =
3338
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3339
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3340
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3341
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3342
1
                         << " table_id=" << table_id;
3343
1
        }
3344
3345
1
        err = txn->commit();
3346
1
        if (err != TxnErrorCode::TXN_OK) {
3347
0
            return -1;
3348
0
        }
3349
1
        metrics_context.total_recycled_num = ++num_recycled;
3350
1
        metrics_context.report();
3351
1
        return 0;
3352
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3275
2
                         this](std::string_view k, std::string_view) {
3276
2
        ++num_scanned;
3277
3278
2
        std::string_view k1(k);
3279
2
        int64_t db_id, table_id, partition_id;
3280
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3281
2
                                                            &partition_id)) {
3282
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3283
0
            return -1;
3284
2
        } else if (table_id != current_table_id) {
3285
2
            current_table_id = table_id;
3286
2
            is_table_kvs_recycled = false;
3287
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3288
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3289
2
            if (err != TxnErrorCode::TXN_OK) {
3290
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3291
0
                             << " table_id=" << table_id << " err=" << err;
3292
0
                return -1;
3293
0
            }
3294
2
        }
3295
3296
2
        if (!is_empty_table) {
3297
            // table is not empty, skip recycle
3298
1
            return 0;
3299
1
        }
3300
3301
1
        std::unique_ptr<Transaction> txn;
3302
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3303
1
        if (err != TxnErrorCode::TXN_OK) {
3304
0
            return -1;
3305
0
        }
3306
3307
        // 1. Remove all partition related kvs
3308
1
        std::string partition_meta_key =
3309
1
                versioned::meta_partition_key({instance_id_, partition_id});
3310
1
        std::string partition_index_key =
3311
1
                versioned::partition_index_key({instance_id_, partition_id});
3312
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3313
1
                {instance_id_, db_id, table_id, partition_id});
3314
1
        std::string partition_version_key =
3315
1
                versioned::partition_version_key({instance_id_, partition_id});
3316
1
        txn->remove(partition_index_key);
3317
1
        txn->remove(partition_inverted_key);
3318
1
        versioned_remove_all(txn.get(), partition_meta_key);
3319
1
        versioned_remove_all(txn.get(), partition_version_key);
3320
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3321
1
                     << " table_id=" << table_id << " db_id=" << db_id
3322
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3323
1
                     << " partition_version_key=" << hex(partition_version_key);
3324
3325
1
        if (!is_table_kvs_recycled) {
3326
1
            is_table_kvs_recycled = true;
3327
3328
            // 2. Remove the table version kv of this table
3329
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3330
1
            versioned_remove_all(txn.get(), table_version_key);
3331
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3332
            // 3. Remove mow delete bitmap update lock and tablet job lock
3333
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3334
1
            txn->remove(lock_key);
3335
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3336
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3337
1
            std::string tablet_job_key_end =
3338
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3339
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3340
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3341
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3342
1
                         << " table_id=" << table_id;
3343
1
        }
3344
3345
1
        err = txn->commit();
3346
1
        if (err != TxnErrorCode::TXN_OK) {
3347
0
            return -1;
3348
0
        }
3349
1
        metrics_context.total_recycled_num = ++num_recycled;
3350
1
        metrics_context.report();
3351
1
        return 0;
3352
1
    };
3353
3354
    // recycle_func and loop_done for scan and recycle
3355
3
    return scan_and_recycle(
3356
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3357
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3358
3
            std::move(recycle_func));
3359
3
}
3360
3361
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3362
                                      RecyclerMetricsContext& metrics_context,
3363
54
                                      int64_t partition_id) {
3364
54
    int64_t num_scanned = 0;
3365
54
    std::atomic_long num_recycled = 0;
3366
3367
54
    std::string tablet_key_begin, tablet_key_end;
3368
54
    std::string stats_key_begin, stats_key_end;
3369
54
    std::string job_key_begin, job_key_end;
3370
3371
54
    std::string tablet_belongs;
3372
54
    if (partition_id > 0) {
3373
        // recycle tablets in a partition belonging to the index
3374
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3375
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3376
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3377
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3378
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3379
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3380
33
        tablet_belongs = "partition";
3381
33
    } else {
3382
        // recycle tablets in the index
3383
21
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3384
21
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3385
21
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3386
21
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3387
21
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3388
21
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3389
21
        tablet_belongs = "index";
3390
21
    }
3391
3392
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3393
54
            .tag("table_id", table_id)
3394
54
            .tag("index_id", index_id)
3395
54
            .tag("partition_id", partition_id);
3396
3397
54
    auto start_time = steady_clock::now();
3398
3399
54
    DORIS_CLOUD_DEFER {
3400
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3401
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3402
54
                .tag("instance_id", instance_id_)
3403
54
                .tag("table_id", table_id)
3404
54
                .tag("index_id", index_id)
3405
54
                .tag("partition_id", partition_id)
3406
54
                .tag("num_scanned", num_scanned)
3407
54
                .tag("num_recycled", num_recycled);
3408
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3399
4
    DORIS_CLOUD_DEFER {
3400
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3401
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3402
4
                .tag("instance_id", instance_id_)
3403
4
                .tag("table_id", table_id)
3404
4
                .tag("index_id", index_id)
3405
4
                .tag("partition_id", partition_id)
3406
4
                .tag("num_scanned", num_scanned)
3407
4
                .tag("num_recycled", num_recycled);
3408
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3399
50
    DORIS_CLOUD_DEFER {
3400
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3401
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3402
50
                .tag("instance_id", instance_id_)
3403
50
                .tag("table_id", table_id)
3404
50
                .tag("index_id", index_id)
3405
50
                .tag("partition_id", partition_id)
3406
50
                .tag("num_scanned", num_scanned)
3407
50
                .tag("num_recycled", num_recycled);
3408
50
    };
3409
3410
    // The tablet key and id which have been recycled.
3411
54
    struct TabletInfo {
3412
54
        std::string_view tablet_meta_key;
3413
54
        int64_t tablet_id;
3414
54
    };
3415
54
    SyncExecutor<TabletInfo> sync_executor(
3416
54
            _thread_pool_group.recycle_tablet_pool,
3417
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3418
54
                        index_id, partition_id),
3419
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3419
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3419
243
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3420
3421
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3422
54
    std::vector<std::string> init_rs_keys;
3423
54
    bool has_failure = false;
3424
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3425
8.25k
        ++num_scanned;
3426
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3427
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3428
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3429
0
            has_failure = true;
3430
0
            return -1;
3431
0
        }
3432
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3433
3434
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3435
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3436
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3437
4.00k
            has_failure = true;
3438
4.00k
            return -1;
3439
4.00k
        }
3440
3441
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3442
4.25k
        sync_executor.add(
3443
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3444
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3445
2
                        LOG_WARNING("failed to recycle tablet")
3446
2
                                .tag("instance_id", instance_id_)
3447
2
                                .tag("tablet_id", tid);
3448
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3449
2
                    }
3450
4.25k
                    ++num_recycled;
3451
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3452
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3453
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3443
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3444
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3445
0
                        LOG_WARNING("failed to recycle tablet")
3446
0
                                .tag("instance_id", instance_id_)
3447
0
                                .tag("tablet_id", tid);
3448
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3449
0
                    }
3450
4.00k
                    ++num_recycled;
3451
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3452
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3453
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3443
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3444
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3445
2
                        LOG_WARNING("failed to recycle tablet")
3446
2
                                .tag("instance_id", instance_id_)
3447
2
                                .tag("tablet_id", tid);
3448
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3449
2
                    }
3450
250
                    ++num_recycled;
3451
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3452
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3453
252
                });
3454
4.25k
        return 0;
3455
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3424
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3425
8.00k
        ++num_scanned;
3426
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3427
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3428
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3429
0
            has_failure = true;
3430
0
            return -1;
3431
0
        }
3432
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3433
3434
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3435
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3436
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3437
4.00k
            has_failure = true;
3438
4.00k
            return -1;
3439
4.00k
        }
3440
3441
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3442
4.00k
        sync_executor.add(
3443
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3444
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3445
4.00k
                        LOG_WARNING("failed to recycle tablet")
3446
4.00k
                                .tag("instance_id", instance_id_)
3447
4.00k
                                .tag("tablet_id", tid);
3448
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3449
4.00k
                    }
3450
4.00k
                    ++num_recycled;
3451
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3452
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3453
4.00k
                });
3454
4.00k
        return 0;
3455
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3424
253
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3425
253
        ++num_scanned;
3426
253
        doris::TabletMetaCloudPB tablet_meta_pb;
3427
253
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3428
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3429
0
            has_failure = true;
3430
0
            return -1;
3431
0
        }
3432
253
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3433
3434
253
        if (config::enable_recycler_check_lazy_txn_finished &&
3435
253
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3436
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3437
1
            has_failure = true;
3438
1
            return -1;
3439
1
        }
3440
3441
253
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3442
252
        sync_executor.add(
3443
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3444
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3445
252
                        LOG_WARNING("failed to recycle tablet")
3446
252
                                .tag("instance_id", instance_id_)
3447
252
                                .tag("tablet_id", tid);
3448
252
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3449
252
                    }
3450
252
                    ++num_recycled;
3451
252
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3452
252
                    return {.tablet_meta_key = k, .tablet_id = tid};
3453
252
                });
3454
252
        return 0;
3455
252
    };
3456
3457
54
    auto loop_done = [&, this]() -> int {
3458
54
        int ret = 0;
3459
54
        bool finished = true;
3460
54
        bool has_empty_key = false;
3461
54
        DORIS_CLOUD_DEFER {
3462
54
            init_rs_keys.clear();
3463
54
            has_failure = false;
3464
54
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3461
4
        DORIS_CLOUD_DEFER {
3462
4
            init_rs_keys.clear();
3463
4
            has_failure = false;
3464
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3461
50
        DORIS_CLOUD_DEFER {
3462
50
            init_rs_keys.clear();
3463
50
            has_failure = false;
3464
50
        };
3465
54
        auto tablets_info = sync_executor.when_all(&finished);
3466
54
        if (!finished) {
3467
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3468
1
            return -1;
3469
1
        }
3470
3471
53
        size_t size_before_erase = tablets_info.size();
3472
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
3472
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
3472
251
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3473
53
        if (tablets_info.empty()) {
3474
2
            return size_before_erase == 0 ? 0 : -1;
3475
51
        } else if (size_before_erase != tablets_info.size()) {
3476
1
            has_empty_key = true;
3477
1
        }
3478
3479
51
        ret = has_empty_key ? -1 : 0;
3480
        // sort the vector using key's order
3481
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3482
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3483
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3481
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3482
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3483
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3481
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3482
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3483
958
        });
3484
51
        std::unique_ptr<Transaction> txn;
3485
51
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3487
0
            return -1;
3488
0
        }
3489
51
        std::string tablet_key_end;
3490
51
        if (!tablets_info.empty()) {
3491
51
            if (!has_empty_key && !has_failure) {
3492
49
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3493
49
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3494
49
            } else {
3495
8
                for (auto& tablet_info : tablets_info) {
3496
8
                    txn->remove(tablet_info.tablet_meta_key);
3497
8
                }
3498
2
            }
3499
51
        }
3500
51
        if (should_recycle_versioned_keys()) {
3501
            // Remove tablet indexes in the same transaction as tablet metadata.
3502
7
            std::vector<std::string> versioned_idx_keys;
3503
7
            versioned_idx_keys.reserve(tablets_info.size());
3504
8
            for (const auto& tablet_info : tablets_info) {
3505
8
                versioned_idx_keys.push_back(
3506
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3507
8
            }
3508
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3509
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3510
7
            if (err != TxnErrorCode::TXN_OK) {
3511
0
                LOG_WARNING("failed to batch get tablet index kv")
3512
0
                        .tag("instance_id", instance_id_)
3513
0
                        .tag("num_tablets", tablets_info.size())
3514
0
                        .tag("err", err);
3515
0
                return -1;
3516
0
            }
3517
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3518
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3519
8
                if (!tablet_index_vals[i].has_value()) {
3520
0
                    continue;
3521
0
                }
3522
8
                const auto& tablet_info = tablets_info[i];
3523
8
                TabletIndexPB tablet_index_pb;
3524
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3525
0
                    LOG_WARNING("failed to parse tablet index pb")
3526
0
                            .tag("instance_id", instance_id_)
3527
0
                            .tag("tablet_id", tablet_info.tablet_id);
3528
0
                    return -1;
3529
0
                }
3530
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3531
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3532
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3533
8
                         tablet_info.tablet_id});
3534
8
                txn->remove(versioned_inverted_idx_key);
3535
8
                txn->remove(versioned_idx_keys[i]);
3536
8
            }
3537
8
            for (auto& tablet_info : tablets_info) {
3538
                // Remove all versions of tablet compact stats for recycled tablet
3539
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3540
8
                LOG_INFO("remove versioned tablet compact stats key")
3541
8
                        .tag("compact_stats_key", hex(k));
3542
8
                versioned_remove_all(txn.get(), k);
3543
8
            }
3544
8
            for (auto& tablet_info : tablets_info) {
3545
                // Remove all versions of tablet load stats for recycled tablet
3546
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3547
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3548
8
                versioned_remove_all(txn.get(), k);
3549
8
            }
3550
8
            for (auto& tablet_info : tablets_info) {
3551
                // Remove all versions of meta tablet for recycled tablet
3552
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3553
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3554
8
                versioned_remove_all(txn.get(), k);
3555
8
            }
3556
7
        }
3557
4.25k
        for (auto& tablet_info : tablets_info) {
3558
4.25k
            std::string k;
3559
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3560
4.25k
            txn->remove(k);
3561
4.25k
        }
3562
4.25k
        for (auto& tablet_info : tablets_info) {
3563
4.25k
            std::string k;
3564
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3565
4.25k
            txn->remove(k);
3566
4.25k
        }
3567
51
        for (auto& k : init_rs_keys) {
3568
0
            txn->remove(k);
3569
0
        }
3570
51
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3571
51
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3572
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3573
1
                         << ", err=" << err;
3574
1
            return -1;
3575
1
        }
3576
50
        return ret;
3577
51
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3457
4
    auto loop_done = [&, this]() -> int {
3458
4
        int ret = 0;
3459
4
        bool finished = true;
3460
4
        bool has_empty_key = false;
3461
4
        DORIS_CLOUD_DEFER {
3462
4
            init_rs_keys.clear();
3463
4
            has_failure = false;
3464
4
        };
3465
4
        auto tablets_info = sync_executor.when_all(&finished);
3466
4
        if (!finished) {
3467
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3468
0
            return -1;
3469
0
        }
3470
3471
4
        size_t size_before_erase = tablets_info.size();
3472
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3473
4
        if (tablets_info.empty()) {
3474
2
            return size_before_erase == 0 ? 0 : -1;
3475
2
        } else if (size_before_erase != tablets_info.size()) {
3476
0
            has_empty_key = true;
3477
0
        }
3478
3479
2
        ret = has_empty_key ? -1 : 0;
3480
        // sort the vector using key's order
3481
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3482
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3483
2
        });
3484
2
        std::unique_ptr<Transaction> txn;
3485
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3487
0
            return -1;
3488
0
        }
3489
2
        std::string tablet_key_end;
3490
2
        if (!tablets_info.empty()) {
3491
2
            if (!has_empty_key && !has_failure) {
3492
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3493
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3494
2
            } else {
3495
0
                for (auto& tablet_info : tablets_info) {
3496
0
                    txn->remove(tablet_info.tablet_meta_key);
3497
0
                }
3498
0
            }
3499
2
        }
3500
2
        if (should_recycle_versioned_keys()) {
3501
            // Remove tablet indexes in the same transaction as tablet metadata.
3502
0
            std::vector<std::string> versioned_idx_keys;
3503
0
            versioned_idx_keys.reserve(tablets_info.size());
3504
0
            for (const auto& tablet_info : tablets_info) {
3505
0
                versioned_idx_keys.push_back(
3506
0
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3507
0
            }
3508
0
            std::vector<std::optional<std::string>> tablet_index_vals;
3509
0
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3510
0
            if (err != TxnErrorCode::TXN_OK) {
3511
0
                LOG_WARNING("failed to batch get tablet index kv")
3512
0
                        .tag("instance_id", instance_id_)
3513
0
                        .tag("num_tablets", tablets_info.size())
3514
0
                        .tag("err", err);
3515
0
                return -1;
3516
0
            }
3517
0
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3518
0
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3519
0
                if (!tablet_index_vals[i].has_value()) {
3520
0
                    continue;
3521
0
                }
3522
0
                const auto& tablet_info = tablets_info[i];
3523
0
                TabletIndexPB tablet_index_pb;
3524
0
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3525
0
                    LOG_WARNING("failed to parse tablet index pb")
3526
0
                            .tag("instance_id", instance_id_)
3527
0
                            .tag("tablet_id", tablet_info.tablet_id);
3528
0
                    return -1;
3529
0
                }
3530
0
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3531
0
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3532
0
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3533
0
                         tablet_info.tablet_id});
3534
0
                txn->remove(versioned_inverted_idx_key);
3535
0
                txn->remove(versioned_idx_keys[i]);
3536
0
            }
3537
0
            for (auto& tablet_info : tablets_info) {
3538
                // Remove all versions of tablet compact stats for recycled tablet
3539
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3540
0
                LOG_INFO("remove versioned tablet compact stats key")
3541
0
                        .tag("compact_stats_key", hex(k));
3542
0
                versioned_remove_all(txn.get(), k);
3543
0
            }
3544
0
            for (auto& tablet_info : tablets_info) {
3545
                // Remove all versions of tablet load stats for recycled tablet
3546
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3547
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3548
0
                versioned_remove_all(txn.get(), k);
3549
0
            }
3550
0
            for (auto& tablet_info : tablets_info) {
3551
                // Remove all versions of meta tablet for recycled tablet
3552
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3553
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3554
0
                versioned_remove_all(txn.get(), k);
3555
0
            }
3556
0
        }
3557
4.00k
        for (auto& tablet_info : tablets_info) {
3558
4.00k
            std::string k;
3559
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3560
4.00k
            txn->remove(k);
3561
4.00k
        }
3562
4.00k
        for (auto& tablet_info : tablets_info) {
3563
4.00k
            std::string k;
3564
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3565
4.00k
            txn->remove(k);
3566
4.00k
        }
3567
2
        for (auto& k : init_rs_keys) {
3568
0
            txn->remove(k);
3569
0
        }
3570
2
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3571
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3572
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3573
0
                         << ", err=" << err;
3574
0
            return -1;
3575
0
        }
3576
2
        return ret;
3577
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3457
50
    auto loop_done = [&, this]() -> int {
3458
50
        int ret = 0;
3459
50
        bool finished = true;
3460
50
        bool has_empty_key = false;
3461
50
        DORIS_CLOUD_DEFER {
3462
50
            init_rs_keys.clear();
3463
50
            has_failure = false;
3464
50
        };
3465
50
        auto tablets_info = sync_executor.when_all(&finished);
3466
50
        if (!finished) {
3467
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3468
1
            return -1;
3469
1
        }
3470
3471
49
        size_t size_before_erase = tablets_info.size();
3472
49
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3473
49
        if (tablets_info.empty()) {
3474
0
            return size_before_erase == 0 ? 0 : -1;
3475
49
        } else if (size_before_erase != tablets_info.size()) {
3476
1
            has_empty_key = true;
3477
1
        }
3478
3479
49
        ret = has_empty_key ? -1 : 0;
3480
        // sort the vector using key's order
3481
49
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3482
49
            return prev.tablet_meta_key < last.tablet_meta_key;
3483
49
        });
3484
49
        std::unique_ptr<Transaction> txn;
3485
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3486
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3487
0
            return -1;
3488
0
        }
3489
49
        std::string tablet_key_end;
3490
49
        if (!tablets_info.empty()) {
3491
49
            if (!has_empty_key && !has_failure) {
3492
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3493
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3494
47
            } else {
3495
8
                for (auto& tablet_info : tablets_info) {
3496
8
                    txn->remove(tablet_info.tablet_meta_key);
3497
8
                }
3498
2
            }
3499
49
        }
3500
49
        if (should_recycle_versioned_keys()) {
3501
            // Remove tablet indexes in the same transaction as tablet metadata.
3502
7
            std::vector<std::string> versioned_idx_keys;
3503
7
            versioned_idx_keys.reserve(tablets_info.size());
3504
8
            for (const auto& tablet_info : tablets_info) {
3505
8
                versioned_idx_keys.push_back(
3506
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3507
8
            }
3508
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3509
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3510
7
            if (err != TxnErrorCode::TXN_OK) {
3511
0
                LOG_WARNING("failed to batch get tablet index kv")
3512
0
                        .tag("instance_id", instance_id_)
3513
0
                        .tag("num_tablets", tablets_info.size())
3514
0
                        .tag("err", err);
3515
0
                return -1;
3516
0
            }
3517
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3518
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3519
8
                if (!tablet_index_vals[i].has_value()) {
3520
0
                    continue;
3521
0
                }
3522
8
                const auto& tablet_info = tablets_info[i];
3523
8
                TabletIndexPB tablet_index_pb;
3524
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3525
0
                    LOG_WARNING("failed to parse tablet index pb")
3526
0
                            .tag("instance_id", instance_id_)
3527
0
                            .tag("tablet_id", tablet_info.tablet_id);
3528
0
                    return -1;
3529
0
                }
3530
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3531
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3532
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3533
8
                         tablet_info.tablet_id});
3534
8
                txn->remove(versioned_inverted_idx_key);
3535
8
                txn->remove(versioned_idx_keys[i]);
3536
8
            }
3537
8
            for (auto& tablet_info : tablets_info) {
3538
                // Remove all versions of tablet compact stats for recycled tablet
3539
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3540
8
                LOG_INFO("remove versioned tablet compact stats key")
3541
8
                        .tag("compact_stats_key", hex(k));
3542
8
                versioned_remove_all(txn.get(), k);
3543
8
            }
3544
8
            for (auto& tablet_info : tablets_info) {
3545
                // Remove all versions of tablet load stats for recycled tablet
3546
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3547
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3548
8
                versioned_remove_all(txn.get(), k);
3549
8
            }
3550
8
            for (auto& tablet_info : tablets_info) {
3551
                // Remove all versions of meta tablet for recycled tablet
3552
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3553
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3554
8
                versioned_remove_all(txn.get(), k);
3555
8
            }
3556
7
        }
3557
250
        for (auto& tablet_info : tablets_info) {
3558
250
            std::string k;
3559
250
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3560
250
            txn->remove(k);
3561
250
        }
3562
250
        for (auto& tablet_info : tablets_info) {
3563
250
            std::string k;
3564
250
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3565
250
            txn->remove(k);
3566
250
        }
3567
49
        for (auto& k : init_rs_keys) {
3568
0
            txn->remove(k);
3569
0
        }
3570
49
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3571
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3572
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3573
1
                         << ", err=" << err;
3574
1
            return -1;
3575
1
        }
3576
48
        return ret;
3577
49
    };
3578
3579
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3580
54
                               std::move(loop_done));
3581
54
    if (ret != 0) {
3582
6
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3583
6
        return ret;
3584
6
    }
3585
3586
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3587
48
    std::unique_ptr<Transaction> txn;
3588
48
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3589
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3590
0
        return -1;
3591
0
    }
3592
48
    txn->remove(stats_key_begin, stats_key_end);
3593
48
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3594
48
                 << " end=" << hex(stats_key_end);
3595
48
    txn->remove(job_key_begin, job_key_end);
3596
48
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3597
48
    std::string schema_key_begin, schema_key_end;
3598
48
    std::string schema_dict_key;
3599
48
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3600
48
    if (partition_id <= 0) {
3601
        // Delete schema kv of this index
3602
16
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3603
16
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3604
16
        txn->remove(schema_key_begin, schema_key_end);
3605
16
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3606
16
                     << " end=" << hex(schema_key_end);
3607
16
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3608
16
        txn->remove(schema_dict_key);
3609
16
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3610
16
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3611
16
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3612
16
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3613
16
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3614
16
                     << " end=" << hex(versioned_schema_key_end);
3615
16
    }
3616
3617
48
    TxnErrorCode err = txn->commit();
3618
48
    if (err != TxnErrorCode::TXN_OK) {
3619
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3620
0
                     << " err=" << err;
3621
0
        return -1;
3622
0
    }
3623
3624
48
    return ret;
3625
48
}
3626
3627
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3628
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3629
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3630
5.61k
    if (num_segments <= 0) return 0;
3631
3632
5.61k
    std::vector<std::string> file_paths;
3633
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3634
0
        return -1;
3635
0
    }
3636
3637
    // Process inverted indexes
3638
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3639
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3640
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3641
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3642
5.61k
    bool delete_rowset_data_by_prefix = false;
3643
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3644
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3645
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3646
0
        delete_rowset_data_by_prefix = true;
3647
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3648
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3649
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3650
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3651
10.0k
            }
3652
10.0k
        }
3653
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3654
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3655
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3656
2.00k
        }
3657
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3658
        // schema version and index id are not found, delete rowset data by prefix directly.
3659
0
        delete_rowset_data_by_prefix = true;
3660
808
    } else {
3661
        // otherwise, try to get schema kv
3662
808
        InvertedIndexInfo index_info;
3663
808
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3664
808
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3665
808
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3666
808
                                 &inverted_index_get_ret);
3667
809
        if (inverted_index_get_ret == 0) {
3668
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3669
809
                index_format = index_info.first;
3670
809
            }
3671
809
            index_ids = index_info.second;
3672
18.4E
        } else if (inverted_index_get_ret == 1) {
3673
            // 1. Schema kv not found means tablet has been recycled
3674
            // Maybe some tablet recycle failed by some bugs
3675
            // We need to delete again to double check
3676
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3677
            // because we are uncertain about the inverted index information.
3678
            // If there are inverted indexes, some data might not be deleted,
3679
            // but this is acceptable as we have made our best effort to delete the data.
3680
0
            LOG_INFO(
3681
0
                    "delete rowset data schema kv not found, need to delete again to double "
3682
0
                    "check")
3683
0
                    .tag("instance_id", instance_id_)
3684
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3685
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3686
            // Currently index_ids is guaranteed to be empty,
3687
            // but we clear it again here as a safeguard against future code changes
3688
            // that might cause index_ids to no longer be empty
3689
0
            index_format = InvertedIndexStorageFormatPB::V2;
3690
0
            index_ids.clear();
3691
18.4E
        } else {
3692
            // failed to get schema kv, delete rowset data by prefix directly.
3693
18.4E
            delete_rowset_data_by_prefix = true;
3694
18.4E
        }
3695
808
    }
3696
3697
5.61k
    if (delete_rowset_data_by_prefix) {
3698
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3699
0
                                  rs_meta_pb.rowset_id_v2());
3700
0
    }
3701
3702
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3703
5.61k
    if (it == accessor_map_.end()) {
3704
1.59k
        LOG_WARNING("instance has no such resource id")
3705
1.59k
                .tag("instance_id", instance_id_)
3706
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3707
1.59k
        return -1;
3708
1.59k
    }
3709
4.01k
    auto& accessor = it->second;
3710
3711
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3712
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3713
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3714
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3715
20.0k
                                         &file_paths);
3716
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3717
40.0k
            for (const auto& index_id : index_ids) {
3718
40.0k
                add_file_to_delete_if_not_packed(
3719
40.0k
                        rs_meta_pb,
3720
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3721
40.0k
                                               index_id.second),
3722
40.0k
                        &file_paths);
3723
40.0k
            }
3724
20.0k
        } else if (!index_ids.empty()) {
3725
0
            add_file_to_delete_if_not_packed(
3726
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3727
0
        }
3728
20.0k
    }
3729
3730
    // Process delete bitmap - check where it's stored.
3731
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3732
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3733
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3734
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3735
0
                .tag("instance_id", instance_id_)
3736
0
                .tag("tablet_id", tablet_id)
3737
0
                .tag("rowset_id", rowset_id);
3738
0
        return -1;
3739
0
    }
3740
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3741
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3742
2.00k
    }
3743
    // TODO(AlexYue): seems could do do batch
3744
4.01k
    return accessor->delete_files(file_paths);
3745
4.01k
}
3746
3747
102k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3748
102k
    LOG_INFO("begin process_packed_file_location_index")
3749
102k
            .tag("instance_id", instance_id_)
3750
102k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3751
102k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3752
102k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3753
102k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3754
102k
    if (index_map.empty()) {
3755
87.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3756
87.6k
                .tag("instance_id", instance_id_)
3757
87.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3758
87.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3759
87.6k
        return 0;
3760
87.6k
    }
3761
3762
14.9k
    struct PackedSmallFileInfo {
3763
14.9k
        std::string small_file_path;
3764
14.9k
    };
3765
14.9k
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3766
14.9k
    packed_file_updates.reserve(index_map.size());
3767
29.9k
    for (const auto& [small_path, index_pb] : index_map) {
3768
30.0k
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3769
0
            continue;
3770
0
        }
3771
29.9k
        packed_file_updates[index_pb.packed_file_path()].push_back(
3772
29.9k
                PackedSmallFileInfo {small_path});
3773
29.9k
    }
3774
14.9k
    if (packed_file_updates.empty()) {
3775
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3776
0
                .tag("instance_id", instance_id_)
3777
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3778
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3779
0
                .tag("index_map_size", index_map.size());
3780
0
        return 0;
3781
0
    }
3782
3783
14.9k
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3784
14.9k
    int ret = 0;
3785
15.0k
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3786
15.0k
        if (small_files.empty()) {
3787
0
            continue;
3788
0
        }
3789
3790
15.0k
        bool success = false;
3791
15.0k
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3792
14.9k
            std::unique_ptr<Transaction> txn;
3793
14.9k
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3794
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3795
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3796
0
                        .tag("instance_id", instance_id_)
3797
0
                        .tag("packed_file_path", packed_file_path)
3798
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3799
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3800
0
                        .tag("err", err);
3801
0
                ret = -1;
3802
0
                break;
3803
0
            }
3804
3805
14.9k
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3806
14.9k
            std::string packed_val;
3807
14.9k
            err = txn->get(packed_key, &packed_val);
3808
14.9k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3809
0
                LOG_WARNING("packed file info not found when recycling rowset")
3810
0
                        .tag("instance_id", instance_id_)
3811
0
                        .tag("packed_file_path", packed_file_path)
3812
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3813
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3814
0
                        .tag("key", hex(packed_key))
3815
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3816
                // Skip this packed file entry and continue with others
3817
0
                success = true;
3818
0
                break;
3819
0
            }
3820
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3821
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3822
0
                        .tag("instance_id", instance_id_)
3823
0
                        .tag("packed_file_path", packed_file_path)
3824
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3825
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3826
0
                        .tag("err", err);
3827
0
                ret = -1;
3828
0
                break;
3829
0
            }
3830
3831
14.9k
            cloud::PackedFileInfoPB packed_info;
3832
14.9k
            if (!packed_info.ParseFromString(packed_val)) {
3833
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3834
0
                        .tag("instance_id", instance_id_)
3835
0
                        .tag("packed_file_path", packed_file_path)
3836
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3837
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3838
0
                ret = -1;
3839
0
                break;
3840
0
            }
3841
3842
14.9k
            LOG_INFO("packed file update check")
3843
14.9k
                    .tag("instance_id", instance_id_)
3844
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3845
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3846
14.9k
                    .tag("merged_file_path", packed_file_path)
3847
14.9k
                    .tag("requested_small_files", small_files.size())
3848
14.9k
                    .tag("merge_entries", packed_info.slices_size());
3849
3850
14.9k
            auto* small_file_entries = packed_info.mutable_slices();
3851
14.9k
            int64_t changed_files = 0;
3852
14.9k
            int64_t missing_entries = 0;
3853
14.9k
            int64_t already_deleted = 0;
3854
29.9k
            for (const auto& small_file_info : small_files) {
3855
29.9k
                bool found = false;
3856
74.8k
                for (auto& small_file_entry : *small_file_entries) {
3857
74.8k
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3858
29.9k
                        if (!small_file_entry.deleted()) {
3859
29.9k
                            small_file_entry.set_deleted(true);
3860
29.9k
                            if (!small_file_entry.corrected()) {
3861
29.9k
                                small_file_entry.set_corrected(true);
3862
29.9k
                            }
3863
29.9k
                            ++changed_files;
3864
29.9k
                        } else {
3865
32
                            ++already_deleted;
3866
32
                        }
3867
29.9k
                        found = true;
3868
29.9k
                        break;
3869
29.9k
                    }
3870
74.8k
                }
3871
29.9k
                if (!found) {
3872
0
                    ++missing_entries;
3873
0
                    LOG_WARNING("packed file info missing small file entry")
3874
0
                            .tag("instance_id", instance_id_)
3875
0
                            .tag("packed_file_path", packed_file_path)
3876
0
                            .tag("small_file_path", small_file_info.small_file_path)
3877
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3878
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3879
0
                }
3880
29.9k
            }
3881
3882
14.9k
            if (changed_files == 0) {
3883
0
                LOG_INFO("skip merge file update: no merge entries changed")
3884
0
                        .tag("instance_id", instance_id_)
3885
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3886
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3887
0
                        .tag("merged_file_path", packed_file_path)
3888
0
                        .tag("missing_entries", missing_entries)
3889
0
                        .tag("already_deleted", already_deleted)
3890
0
                        .tag("requested_small_files", small_files.size())
3891
0
                        .tag("merge_entries", packed_info.slices_size());
3892
0
                success = true;
3893
0
                break;
3894
0
            }
3895
3896
            // Calculate remaining files
3897
14.9k
            int64_t left_file_count = 0;
3898
14.9k
            int64_t left_file_bytes = 0;
3899
59.9k
            for (const auto& small_file_entry : packed_info.slices()) {
3900
59.9k
                if (!small_file_entry.deleted()) {
3901
15.0k
                    ++left_file_count;
3902
15.0k
                    left_file_bytes += small_file_entry.size();
3903
15.0k
                }
3904
59.9k
            }
3905
14.9k
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3906
14.9k
            packed_info.set_ref_cnt(left_file_count);
3907
14.9k
            LOG_INFO("updated packed file reference info")
3908
14.9k
                    .tag("instance_id", instance_id_)
3909
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3910
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3911
14.9k
                    .tag("packed_file_path", packed_file_path)
3912
14.9k
                    .tag("ref_cnt", left_file_count)
3913
14.9k
                    .tag("left_file_bytes", left_file_bytes);
3914
3915
14.9k
            if (left_file_count == 0) {
3916
7.50k
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3917
7.50k
            }
3918
3919
14.9k
            std::string updated_val;
3920
14.9k
            if (!packed_info.SerializeToString(&updated_val)) {
3921
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3922
0
                        .tag("instance_id", instance_id_)
3923
0
                        .tag("packed_file_path", packed_file_path)
3924
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3925
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3926
0
                ret = -1;
3927
0
                break;
3928
0
            }
3929
3930
14.9k
            txn->put(packed_key, updated_val);
3931
14.9k
            err = txn->commit();
3932
15.0k
            if (err == TxnErrorCode::TXN_OK) {
3933
15.0k
                success = true;
3934
15.0k
                if (left_file_count == 0) {
3935
7.50k
                    LOG_INFO("packed file ready to delete, deleting immediately")
3936
7.50k
                            .tag("instance_id", instance_id_)
3937
7.50k
                            .tag("packed_file_path", packed_file_path);
3938
7.50k
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3939
0
                        ret = -1;
3940
0
                    }
3941
7.50k
                }
3942
15.0k
                break;
3943
15.0k
            }
3944
18.4E
            if (err == TxnErrorCode::TXN_CONFLICT) {
3945
0
                if (attempt >= max_retry_times) {
3946
0
                    LOG_WARNING("packed file info update conflict after max retry")
3947
0
                            .tag("instance_id", instance_id_)
3948
0
                            .tag("packed_file_path", packed_file_path)
3949
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3950
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3951
0
                            .tag("changed_files", changed_files)
3952
0
                            .tag("attempt", attempt);
3953
0
                    ret = -1;
3954
0
                    break;
3955
0
                }
3956
0
                LOG_WARNING("packed file info update conflict, retrying")
3957
0
                        .tag("instance_id", instance_id_)
3958
0
                        .tag("packed_file_path", packed_file_path)
3959
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3960
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3961
0
                        .tag("changed_files", changed_files)
3962
0
                        .tag("attempt", attempt);
3963
0
                sleep_for_packed_file_retry();
3964
0
                continue;
3965
0
            }
3966
3967
18.4E
            LOG_WARNING("failed to commit packed file info update")
3968
18.4E
                    .tag("instance_id", instance_id_)
3969
18.4E
                    .tag("packed_file_path", packed_file_path)
3970
18.4E
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3971
18.4E
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3972
18.4E
                    .tag("err", err)
3973
18.4E
                    .tag("changed_files", changed_files);
3974
18.4E
            ret = -1;
3975
18.4E
            break;
3976
18.4E
        }
3977
3978
15.0k
        if (!success) {
3979
0
            ret = -1;
3980
0
        }
3981
15.0k
    }
3982
3983
14.9k
    return ret;
3984
14.9k
}
3985
3986
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3987
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
3988
100k
        std::vector<std::string>* keys) {
3989
100k
    if (out_storage_type) {
3990
98.3k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3991
98.3k
    }
3992
3993
    // Get delete bitmap storage info from FDB
3994
100k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3995
100k
    std::unique_ptr<Transaction> txn;
3996
100k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3997
100k
    if (err != TxnErrorCode::TXN_OK) {
3998
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
3999
0
                .tag("instance_id", instance_id_)
4000
0
                .tag("tablet_id", tablet_id)
4001
0
                .tag("rowset_id", rowset_id)
4002
0
                .tag("err", err);
4003
0
        return -1;
4004
0
    }
4005
4006
100k
    ValueBuf dbm_val;
4007
100k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4008
100k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4009
        // No delete bitmap for this rowset, nothing to do
4010
36.1k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4011
36.1k
                .tag("instance_id", instance_id_)
4012
36.1k
                .tag("tablet_id", tablet_id)
4013
36.1k
                .tag("rowset_id", rowset_id);
4014
36.1k
        return 0;
4015
36.1k
    }
4016
64.7k
    if (err != TxnErrorCode::TXN_OK) {
4017
0
        LOG_WARNING("failed to get delete bitmap storage")
4018
0
                .tag("instance_id", instance_id_)
4019
0
                .tag("tablet_id", tablet_id)
4020
0
                .tag("rowset_id", rowset_id)
4021
0
                .tag("err", err);
4022
0
        return -1;
4023
0
    }
4024
4025
64.7k
    if (keys) {
4026
11.5k
        for (auto& key : dbm_val.keys()) {
4027
11.5k
            keys->push_back(std::move(key));
4028
11.5k
        }
4029
11.5k
    }
4030
4031
64.7k
    DeleteBitmapStoragePB storage;
4032
64.7k
    if (!dbm_val.to_pb(&storage)) {
4033
0
        LOG_WARNING("failed to parse delete bitmap storage")
4034
0
                .tag("instance_id", instance_id_)
4035
0
                .tag("tablet_id", tablet_id)
4036
0
                .tag("rowset_id", rowset_id);
4037
0
        return -1;
4038
0
    }
4039
4040
64.7k
    if (storage.store_in_fdb()) {
4041
1
        if (out_storage_type) {
4042
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4043
1
        }
4044
1
        return 0;
4045
1
    }
4046
4047
    // Check if delete bitmap is stored in standalone file.
4048
64.7k
    if (!storage.has_packed_slice_location() ||
4049
64.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4050
64.8k
        if (out_storage_type) {
4051
63.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4052
63.5k
        }
4053
64.8k
        return 0;
4054
64.8k
    }
4055
4056
18.4E
    if (out_storage_type) {
4057
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4058
0
    }
4059
4060
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4061
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4062
4063
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4064
18.4E
            .tag("instance_id", instance_id_)
4065
18.4E
            .tag("tablet_id", tablet_id)
4066
18.4E
            .tag("rowset_id", rowset_id)
4067
18.4E
            .tag("packed_file_path", packed_file_path);
4068
4069
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4070
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4071
1
        std::unique_ptr<Transaction> update_txn;
4072
1
        err = txn_kv_->create_txn(&update_txn);
4073
1
        if (err != TxnErrorCode::TXN_OK) {
4074
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4075
0
                    .tag("instance_id", instance_id_)
4076
0
                    .tag("tablet_id", tablet_id)
4077
0
                    .tag("rowset_id", rowset_id)
4078
0
                    .tag("err", err);
4079
0
            return -1;
4080
0
        }
4081
4082
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4083
1
        std::string packed_val;
4084
1
        err = update_txn->get(packed_key, &packed_val);
4085
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4086
0
            LOG_WARNING("packed file info not found for delete bitmap")
4087
0
                    .tag("instance_id", instance_id_)
4088
0
                    .tag("tablet_id", tablet_id)
4089
0
                    .tag("rowset_id", rowset_id)
4090
0
                    .tag("packed_file_path", packed_file_path);
4091
0
            return 0;
4092
0
        }
4093
1
        if (err != TxnErrorCode::TXN_OK) {
4094
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4095
0
                    .tag("instance_id", instance_id_)
4096
0
                    .tag("tablet_id", tablet_id)
4097
0
                    .tag("rowset_id", rowset_id)
4098
0
                    .tag("packed_file_path", packed_file_path)
4099
0
                    .tag("err", err);
4100
0
            return -1;
4101
0
        }
4102
4103
1
        cloud::PackedFileInfoPB packed_info;
4104
1
        if (!packed_info.ParseFromString(packed_val)) {
4105
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4106
0
                    .tag("instance_id", instance_id_)
4107
0
                    .tag("tablet_id", tablet_id)
4108
0
                    .tag("rowset_id", rowset_id)
4109
0
                    .tag("packed_file_path", packed_file_path);
4110
0
            return -1;
4111
0
        }
4112
4113
        // Find and mark the small file entry as deleted
4114
        // Use tablet_id and rowset_id to match entry instead of path,
4115
        // because path format may vary with path_version (with or without shard prefix)
4116
1
        auto* entries = packed_info.mutable_slices();
4117
1
        bool found = false;
4118
1
        bool already_deleted = false;
4119
1
        for (auto& entry : *entries) {
4120
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4121
1
                if (!entry.deleted()) {
4122
1
                    entry.set_deleted(true);
4123
1
                    if (!entry.corrected()) {
4124
1
                        entry.set_corrected(true);
4125
1
                    }
4126
1
                } else {
4127
0
                    already_deleted = true;
4128
0
                }
4129
1
                found = true;
4130
1
                break;
4131
1
            }
4132
1
        }
4133
4134
1
        if (!found) {
4135
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4136
0
                    .tag("instance_id", instance_id_)
4137
0
                    .tag("tablet_id", tablet_id)
4138
0
                    .tag("rowset_id", rowset_id)
4139
0
                    .tag("packed_file_path", packed_file_path);
4140
0
            return 0;
4141
0
        }
4142
4143
1
        if (already_deleted) {
4144
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4145
0
                    .tag("instance_id", instance_id_)
4146
0
                    .tag("tablet_id", tablet_id)
4147
0
                    .tag("rowset_id", rowset_id)
4148
0
                    .tag("packed_file_path", packed_file_path);
4149
0
            return 0;
4150
0
        }
4151
4152
        // Calculate remaining files
4153
1
        int64_t left_file_count = 0;
4154
1
        int64_t left_file_bytes = 0;
4155
1
        for (const auto& entry : packed_info.slices()) {
4156
1
            if (!entry.deleted()) {
4157
0
                ++left_file_count;
4158
0
                left_file_bytes += entry.size();
4159
0
            }
4160
1
        }
4161
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4162
1
        packed_info.set_ref_cnt(left_file_count);
4163
4164
1
        if (left_file_count == 0) {
4165
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4166
1
        }
4167
4168
1
        std::string updated_val;
4169
1
        if (!packed_info.SerializeToString(&updated_val)) {
4170
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4171
0
                    .tag("instance_id", instance_id_)
4172
0
                    .tag("tablet_id", tablet_id)
4173
0
                    .tag("rowset_id", rowset_id)
4174
0
                    .tag("packed_file_path", packed_file_path);
4175
0
            return -1;
4176
0
        }
4177
4178
1
        update_txn->put(packed_key, updated_val);
4179
1
        err = update_txn->commit();
4180
1
        if (err == TxnErrorCode::TXN_OK) {
4181
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4182
1
                    .tag("instance_id", instance_id_)
4183
1
                    .tag("tablet_id", tablet_id)
4184
1
                    .tag("rowset_id", rowset_id)
4185
1
                    .tag("packed_file_path", packed_file_path)
4186
1
                    .tag("left_file_count", left_file_count);
4187
1
            if (left_file_count == 0) {
4188
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4189
0
                    return -1;
4190
0
                }
4191
1
            }
4192
1
            return 0;
4193
1
        }
4194
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4195
0
            if (attempt >= max_retry_times) {
4196
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4197
0
                        .tag("instance_id", instance_id_)
4198
0
                        .tag("tablet_id", tablet_id)
4199
0
                        .tag("rowset_id", rowset_id)
4200
0
                        .tag("packed_file_path", packed_file_path)
4201
0
                        .tag("attempt", attempt);
4202
0
                return -1;
4203
0
            }
4204
0
            sleep_for_packed_file_retry();
4205
0
            continue;
4206
0
        }
4207
4208
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4209
0
                .tag("instance_id", instance_id_)
4210
0
                .tag("tablet_id", tablet_id)
4211
0
                .tag("rowset_id", rowset_id)
4212
0
                .tag("packed_file_path", packed_file_path)
4213
0
                .tag("err", err);
4214
0
        return -1;
4215
0
    }
4216
4217
18.4E
    return -1;
4218
18.4E
}
4219
4220
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4221
                                                const std::string& packed_key,
4222
7.49k
                                                const cloud::PackedFileInfoPB& packed_info) {
4223
7.49k
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4224
0
        LOG_WARNING("packed file missing resource id when recycling")
4225
0
                .tag("instance_id", instance_id_)
4226
0
                .tag("packed_file_path", packed_file_path);
4227
0
        return -1;
4228
0
    }
4229
4230
7.49k
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4231
7.49k
    if (!accessor) {
4232
0
        LOG_WARNING("no accessor available to delete packed file")
4233
0
                .tag("instance_id", instance_id_)
4234
0
                .tag("packed_file_path", packed_file_path)
4235
0
                .tag("resource_id", packed_info.resource_id());
4236
0
        return -1;
4237
0
    }
4238
4239
7.49k
    int del_ret = accessor->delete_file(packed_file_path);
4240
7.49k
    if (del_ret != 0 && del_ret != 1) {
4241
0
        LOG_WARNING("failed to delete packed file")
4242
0
                .tag("instance_id", instance_id_)
4243
0
                .tag("packed_file_path", packed_file_path)
4244
0
                .tag("resource_id", resource_id)
4245
0
                .tag("ret", del_ret);
4246
0
        return -1;
4247
0
    }
4248
7.49k
    if (del_ret == 1) {
4249
0
        LOG_INFO("packed file already removed")
4250
0
                .tag("instance_id", instance_id_)
4251
0
                .tag("packed_file_path", packed_file_path)
4252
0
                .tag("resource_id", resource_id);
4253
7.49k
    } else {
4254
7.49k
        LOG_INFO("deleted packed file")
4255
7.49k
                .tag("instance_id", instance_id_)
4256
7.49k
                .tag("packed_file_path", packed_file_path)
4257
7.49k
                .tag("resource_id", resource_id);
4258
7.49k
    }
4259
4260
7.49k
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4261
7.50k
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4262
7.50k
        std::unique_ptr<Transaction> del_txn;
4263
7.50k
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4264
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4265
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4266
0
                    .tag("instance_id", instance_id_)
4267
0
                    .tag("packed_file_path", packed_file_path)
4268
0
                    .tag("attempt", attempt)
4269
0
                    .tag("err", err);
4270
0
            return -1;
4271
0
        }
4272
4273
7.50k
        std::string latest_val;
4274
7.50k
        err = del_txn->get(packed_key, &latest_val);
4275
7.50k
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4276
0
            return 0;
4277
0
        }
4278
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4279
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4280
0
                    .tag("instance_id", instance_id_)
4281
0
                    .tag("packed_file_path", packed_file_path)
4282
0
                    .tag("attempt", attempt)
4283
0
                    .tag("err", err);
4284
0
            return -1;
4285
0
        }
4286
4287
7.50k
        cloud::PackedFileInfoPB latest_info;
4288
7.50k
        if (!latest_info.ParseFromString(latest_val)) {
4289
0
            LOG_WARNING("failed to parse packed file info before removal")
4290
0
                    .tag("instance_id", instance_id_)
4291
0
                    .tag("packed_file_path", packed_file_path)
4292
0
                    .tag("attempt", attempt);
4293
0
            return -1;
4294
0
        }
4295
4296
7.50k
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4297
7.50k
              latest_info.ref_cnt() == 0)) {
4298
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4299
0
                    .tag("instance_id", instance_id_)
4300
0
                    .tag("packed_file_path", packed_file_path)
4301
0
                    .tag("attempt", attempt);
4302
0
            return 0;
4303
0
        }
4304
4305
7.50k
        del_txn->remove(packed_key);
4306
7.50k
        err = del_txn->commit();
4307
7.50k
        if (err == TxnErrorCode::TXN_OK) {
4308
7.50k
            LOG_INFO("removed packed file metadata")
4309
7.50k
                    .tag("instance_id", instance_id_)
4310
7.50k
                    .tag("packed_file_path", packed_file_path);
4311
7.50k
            return 0;
4312
7.50k
        }
4313
1
        if (err == TxnErrorCode::TXN_CONFLICT) {
4314
0
            if (attempt >= max_retry_times) {
4315
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4316
0
                        .tag("instance_id", instance_id_)
4317
0
                        .tag("packed_file_path", packed_file_path)
4318
0
                        .tag("attempt", attempt);
4319
0
                return -1;
4320
0
            }
4321
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4322
0
                    .tag("instance_id", instance_id_)
4323
0
                    .tag("packed_file_path", packed_file_path)
4324
0
                    .tag("attempt", attempt);
4325
0
            sleep_for_packed_file_retry();
4326
0
            continue;
4327
0
        }
4328
1
        LOG_WARNING("failed to remove packed file kv")
4329
1
                .tag("instance_id", instance_id_)
4330
1
                .tag("packed_file_path", packed_file_path)
4331
1
                .tag("attempt", attempt)
4332
1
                .tag("err", err);
4333
1
        return -1;
4334
1
    }
4335
18.4E
    return -1;
4336
7.49k
}
4337
4338
int InstanceRecycler::delete_rowset_data(
4339
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4340
        RecyclerMetricsContext& metrics_context,
4341
439
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4342
439
    int ret = 0;
4343
    // resource_id -> file_paths
4344
439
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4345
    // (resource_id, tablet_id, rowset_id)
4346
439
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4347
439
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4348
4349
106k
    for (const auto& [_, rs] : rowsets) {
4350
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4351
        // due to aborted schema change.
4352
106k
        if (is_formal_rowset) {
4353
53.0k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4354
                // Tablet has been recycled and this rowset has no packed slices, so file data
4355
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4356
                // slice info must still run to decrement packed file ref counts.
4357
0
                continue;
4358
0
            }
4359
53.0k
        }
4360
4361
106k
        int64_t num_segments = rs.num_segments();
4362
        // Check num_segments before accessor lookup, because empty rowsets
4363
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4364
        // set. Skipping them early avoids a spurious "no such resource id" error
4365
        // that marks the entire batch as failed and prevents txn_remove from
4366
        // cleaning up recycle KV keys.
4367
106k
        if (num_segments <= 0) {
4368
10.0k
            metrics_context.total_recycled_num++;
4369
10.0k
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4370
10.0k
            continue;
4371
10.0k
        }
4372
4373
96.4k
        auto it = accessor_map_.find(rs.resource_id());
4374
        // possible if the accessor is not initilized correctly
4375
96.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4376
2.00k
            LOG_WARNING("instance has no such resource id")
4377
2.00k
                    .tag("instance_id", instance_id_)
4378
2.00k
                    .tag("resource_id", rs.resource_id());
4379
2.00k
            ret = -1;
4380
2.00k
            continue;
4381
2.00k
        }
4382
4383
94.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4384
94.4k
        const auto& rowset_id = rs.rowset_id_v2();
4385
94.4k
        int64_t tablet_id = rs.tablet_id();
4386
94.4k
        LOG_INFO("recycle rowset merge index size")
4387
94.4k
                .tag("instance_id", instance_id_)
4388
94.4k
                .tag("tablet_id", tablet_id)
4389
94.4k
                .tag("rowset_id", rowset_id)
4390
94.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4391
94.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4392
0
            ret = -1;
4393
0
            continue;
4394
0
        }
4395
4396
94.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4397
94.4k
        std::vector<std::string> rowset_dbm_keys;
4398
94.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4399
94.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4400
94.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4401
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4402
0
                    .tag("instance_id", instance_id_)
4403
0
                    .tag("tablet_id", tablet_id)
4404
0
                    .tag("rowset_id", rowset_id);
4405
0
            ret = -1;
4406
0
            continue;
4407
0
        }
4408
94.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4409
11.5k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4410
11.5k
        }
4411
94.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4412
61.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4413
61.5k
        }
4414
4415
        // Process inverted indexes
4416
94.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4417
        // default format as v1.
4418
94.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4419
94.4k
                                                            ? rs.inverted_index_storage_format()
4420
94.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4421
94.4k
        int inverted_index_get_ret = 0;
4422
94.4k
        if (rs.has_tablet_schema()) {
4423
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4424
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4425
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4426
53.5k
                }
4427
53.5k
            }
4428
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4429
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4430
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4431
26.5k
            }
4432
67.5k
        } else {
4433
67.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4434
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4435
0
                                "instance_id="
4436
0
                             << instance_id_ << " tablet_id=" << tablet_id
4437
0
                             << " rowset_id=" << rowset_id;
4438
0
                ret = -1;
4439
0
                continue;
4440
0
            }
4441
67.5k
            InvertedIndexInfo index_info;
4442
67.5k
            inverted_index_get_ret =
4443
67.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4444
67.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4445
67.5k
                                     &inverted_index_get_ret);
4446
67.5k
            if (inverted_index_get_ret == 0) {
4447
62.0k
                if (!rs.has_inverted_index_storage_format()) {
4448
62.0k
                    index_format = index_info.first;
4449
62.0k
                }
4450
62.0k
                index_ids = index_info.second;
4451
62.0k
            } else if (inverted_index_get_ret == 1) {
4452
                // 1. Schema kv not found means tablet has been recycled
4453
                // Maybe some tablet recycle failed by some bugs
4454
                // We need to delete again to double check
4455
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4456
                // because we are uncertain about the inverted index information.
4457
                // If there are inverted indexes, some data might not be deleted,
4458
                // but this is acceptable as we have made our best effort to delete the data.
4459
5.50k
                LOG_INFO(
4460
5.50k
                        "delete rowset data schema kv not found, need to delete again to "
4461
5.50k
                        "double "
4462
5.50k
                        "check")
4463
5.50k
                        .tag("instance_id", instance_id_)
4464
5.50k
                        .tag("tablet_id", tablet_id)
4465
5.50k
                        .tag("rowset", rs.ShortDebugString());
4466
                // Currently index_ids is guaranteed to be empty,
4467
                // but we clear it again here as a safeguard against future code changes
4468
                // that might cause index_ids to no longer be empty
4469
5.50k
                index_format = InvertedIndexStorageFormatPB::V2;
4470
5.50k
                index_ids.clear();
4471
18.4E
            } else {
4472
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4473
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4474
18.4E
                ret = -1;
4475
18.4E
                continue;
4476
18.4E
            }
4477
67.5k
        }
4478
94.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE && !is_formal_rowset) {
4479
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4480
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4481
6
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4482
6
            continue;
4483
6
        }
4484
404k
        for (int64_t i = 0; i < num_segments; ++i) {
4485
310k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4486
310k
                                             &file_paths);
4487
310k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4488
572k
                for (const auto& index_id : index_ids) {
4489
572k
                    add_file_to_delete_if_not_packed(
4490
572k
                            rs,
4491
572k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4492
572k
                                                   index_id.second),
4493
572k
                            &file_paths);
4494
572k
                }
4495
302k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4496
                // try to recycle inverted index v2 when get_ret == 1
4497
                // we treat schema not found as if it has a v2 format inverted index
4498
                // to reduce chance of data leakage
4499
7.49k
                if (inverted_index_get_ret == 1) {
4500
7.49k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4501
7.49k
                            .tag("instance_id", instance_id_)
4502
7.49k
                            .tag("inverted index v2 path",
4503
7.49k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4504
7.49k
                }
4505
7.49k
                add_file_to_delete_if_not_packed(
4506
7.49k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4507
7.49k
            }
4508
310k
        }
4509
94.4k
    }
4510
4511
439
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4512
439
                                                 "delete_rowset_data",
4513
439
                                                 [](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
4513
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
4513
198
                                                 [](const int& ret) { return ret != 0; });
4514
439
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4515
198
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4516
198
            DCHECK(accessor_map_.count(*rid))
4517
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4518
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4519
198
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4520
198
                                     &accessor_map_);
4521
198
            if (!accessor_map_.contains(*rid)) {
4522
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4523
0
                        .tag("resource_id", resource_id)
4524
0
                        .tag("instance_id", instance_id_);
4525
0
                return -1;
4526
0
            }
4527
198
            auto& accessor = accessor_map_[*rid];
4528
198
            int ret = accessor->delete_files(*paths);
4529
198
            if (!ret) {
4530
                // deduplication of different files with the same rowset id
4531
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4532
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4533
198
                std::set<std::string> deleted_rowset_id;
4534
4535
198
                std::for_each(paths->begin(), paths->end(),
4536
198
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4537
923k
                               this](const std::string& path) {
4538
923k
                                  std::vector<std::string> str;
4539
923k
                                  butil::SplitString(path, '/', &str);
4540
923k
                                  std::string rowset_id;
4541
923k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4542
916k
                                      rowset_id = str.back().substr(0, pos);
4543
916k
                                  } else {
4544
6.48k
                                      if (path.find("packed_file/") != std::string::npos) {
4545
0
                                          return; // packed files do not have rowset_id encoded
4546
0
                                      }
4547
6.48k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4548
6.48k
                                      return;
4549
6.48k
                                  }
4550
916k
                                  auto rs_meta = rowsets.find(rowset_id);
4551
916k
                                  if (rs_meta != rowsets.end() &&
4552
916k
                                      !deleted_rowset_id.contains(rowset_id)) {
4553
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4554
84.4k
                                      metrics_context.total_recycled_data_size +=
4555
84.4k
                                              rs_meta->second.total_disk_size();
4556
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4557
84.4k
                                              rs_meta->second.num_segments();
4558
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4559
84.4k
                                              rs_meta->second.total_disk_size();
4560
84.4k
                                      metrics_context.total_recycled_num++;
4561
84.4k
                                  }
4562
916k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4537
7
                               this](const std::string& path) {
4538
7
                                  std::vector<std::string> str;
4539
7
                                  butil::SplitString(path, '/', &str);
4540
7
                                  std::string rowset_id;
4541
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4542
7
                                      rowset_id = str.back().substr(0, pos);
4543
7
                                  } else {
4544
0
                                      if (path.find("packed_file/") != std::string::npos) {
4545
0
                                          return; // packed files do not have rowset_id encoded
4546
0
                                      }
4547
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4548
0
                                      return;
4549
0
                                  }
4550
7
                                  auto rs_meta = rowsets.find(rowset_id);
4551
7
                                  if (rs_meta != rowsets.end() &&
4552
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4553
7
                                      deleted_rowset_id.emplace(rowset_id);
4554
7
                                      metrics_context.total_recycled_data_size +=
4555
7
                                              rs_meta->second.total_disk_size();
4556
7
                                      segment_metrics_context_.total_recycled_num +=
4557
7
                                              rs_meta->second.num_segments();
4558
7
                                      segment_metrics_context_.total_recycled_data_size +=
4559
7
                                              rs_meta->second.total_disk_size();
4560
7
                                      metrics_context.total_recycled_num++;
4561
7
                                  }
4562
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
4537
923k
                               this](const std::string& path) {
4538
923k
                                  std::vector<std::string> str;
4539
923k
                                  butil::SplitString(path, '/', &str);
4540
923k
                                  std::string rowset_id;
4541
923k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4542
916k
                                      rowset_id = str.back().substr(0, pos);
4543
916k
                                  } else {
4544
6.48k
                                      if (path.find("packed_file/") != std::string::npos) {
4545
0
                                          return; // packed files do not have rowset_id encoded
4546
0
                                      }
4547
6.48k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4548
6.48k
                                      return;
4549
6.48k
                                  }
4550
916k
                                  auto rs_meta = rowsets.find(rowset_id);
4551
916k
                                  if (rs_meta != rowsets.end() &&
4552
916k
                                      !deleted_rowset_id.contains(rowset_id)) {
4553
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4554
84.4k
                                      metrics_context.total_recycled_data_size +=
4555
84.4k
                                              rs_meta->second.total_disk_size();
4556
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4557
84.4k
                                              rs_meta->second.num_segments();
4558
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4559
84.4k
                                              rs_meta->second.total_disk_size();
4560
84.4k
                                      metrics_context.total_recycled_num++;
4561
84.4k
                                  }
4562
916k
                              });
4563
198
            }
4564
198
            return ret;
4565
198
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4515
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4516
6
            DCHECK(accessor_map_.count(*rid))
4517
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4518
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4519
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4520
6
                                     &accessor_map_);
4521
6
            if (!accessor_map_.contains(*rid)) {
4522
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4523
0
                        .tag("resource_id", resource_id)
4524
0
                        .tag("instance_id", instance_id_);
4525
0
                return -1;
4526
0
            }
4527
6
            auto& accessor = accessor_map_[*rid];
4528
6
            int ret = accessor->delete_files(*paths);
4529
6
            if (!ret) {
4530
                // deduplication of different files with the same rowset id
4531
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4532
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4533
6
                std::set<std::string> deleted_rowset_id;
4534
4535
6
                std::for_each(paths->begin(), paths->end(),
4536
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4537
6
                               this](const std::string& path) {
4538
6
                                  std::vector<std::string> str;
4539
6
                                  butil::SplitString(path, '/', &str);
4540
6
                                  std::string rowset_id;
4541
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4542
6
                                      rowset_id = str.back().substr(0, pos);
4543
6
                                  } else {
4544
6
                                      if (path.find("packed_file/") != std::string::npos) {
4545
6
                                          return; // packed files do not have rowset_id encoded
4546
6
                                      }
4547
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4548
6
                                      return;
4549
6
                                  }
4550
6
                                  auto rs_meta = rowsets.find(rowset_id);
4551
6
                                  if (rs_meta != rowsets.end() &&
4552
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4553
6
                                      deleted_rowset_id.emplace(rowset_id);
4554
6
                                      metrics_context.total_recycled_data_size +=
4555
6
                                              rs_meta->second.total_disk_size();
4556
6
                                      segment_metrics_context_.total_recycled_num +=
4557
6
                                              rs_meta->second.num_segments();
4558
6
                                      segment_metrics_context_.total_recycled_data_size +=
4559
6
                                              rs_meta->second.total_disk_size();
4560
6
                                      metrics_context.total_recycled_num++;
4561
6
                                  }
4562
6
                              });
4563
6
            }
4564
6
            return ret;
4565
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4515
192
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4516
192
            DCHECK(accessor_map_.count(*rid))
4517
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4518
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4519
192
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4520
192
                                     &accessor_map_);
4521
192
            if (!accessor_map_.contains(*rid)) {
4522
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4523
0
                        .tag("resource_id", resource_id)
4524
0
                        .tag("instance_id", instance_id_);
4525
0
                return -1;
4526
0
            }
4527
192
            auto& accessor = accessor_map_[*rid];
4528
192
            int ret = accessor->delete_files(*paths);
4529
192
            if (!ret) {
4530
                // deduplication of different files with the same rowset id
4531
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4532
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4533
192
                std::set<std::string> deleted_rowset_id;
4534
4535
192
                std::for_each(paths->begin(), paths->end(),
4536
192
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4537
192
                               this](const std::string& path) {
4538
192
                                  std::vector<std::string> str;
4539
192
                                  butil::SplitString(path, '/', &str);
4540
192
                                  std::string rowset_id;
4541
192
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4542
192
                                      rowset_id = str.back().substr(0, pos);
4543
192
                                  } else {
4544
192
                                      if (path.find("packed_file/") != std::string::npos) {
4545
192
                                          return; // packed files do not have rowset_id encoded
4546
192
                                      }
4547
192
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4548
192
                                      return;
4549
192
                                  }
4550
192
                                  auto rs_meta = rowsets.find(rowset_id);
4551
192
                                  if (rs_meta != rowsets.end() &&
4552
192
                                      !deleted_rowset_id.contains(rowset_id)) {
4553
192
                                      deleted_rowset_id.emplace(rowset_id);
4554
192
                                      metrics_context.total_recycled_data_size +=
4555
192
                                              rs_meta->second.total_disk_size();
4556
192
                                      segment_metrics_context_.total_recycled_num +=
4557
192
                                              rs_meta->second.num_segments();
4558
192
                                      segment_metrics_context_.total_recycled_data_size +=
4559
192
                                              rs_meta->second.total_disk_size();
4560
192
                                      metrics_context.total_recycled_num++;
4561
192
                                  }
4562
192
                              });
4563
192
            }
4564
192
            return ret;
4565
192
        });
4566
198
    }
4567
439
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4568
6
        LOG_INFO(
4569
6
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4570
6
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4571
6
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4572
6
        concurrent_delete_executor.add([&]() -> int {
4573
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4574
6
            if (!ret) {
4575
6
                auto rs = rowsets.at(rowset_id);
4576
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4577
6
                metrics_context.total_recycled_num++;
4578
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4579
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4580
6
            }
4581
6
            return ret;
4582
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
4572
6
        concurrent_delete_executor.add([&]() -> int {
4573
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4574
6
            if (!ret) {
4575
6
                auto rs = rowsets.at(rowset_id);
4576
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4577
6
                metrics_context.total_recycled_num++;
4578
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4579
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4580
6
            }
4581
6
            return ret;
4582
6
        });
4583
6
    }
4584
4585
439
    bool finished = true;
4586
439
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4587
439
    for (int r : rets) {
4588
204
        if (r != 0) {
4589
0
            ret = -1;
4590
0
            break;
4591
0
        }
4592
204
    }
4593
439
    ret = finished ? ret : -1;
4594
439
    return ret;
4595
439
}
4596
4597
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4598
43.5k
                                         const std::string& rowset_id) {
4599
43.5k
    auto it = accessor_map_.find(resource_id);
4600
43.5k
    if (it == accessor_map_.end()) {
4601
400
        LOG_WARNING("instance has no such resource id")
4602
400
                .tag("instance_id", instance_id_)
4603
400
                .tag("resource_id", resource_id)
4604
400
                .tag("tablet_id", tablet_id)
4605
400
                .tag("rowset_id", rowset_id);
4606
400
        return -1;
4607
400
    }
4608
43.1k
    auto& accessor = it->second;
4609
43.1k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4610
43.5k
}
4611
4612
145k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4613
145k
    std::lock_guard lock(recycled_tablets_mtx_);
4614
145k
    return recycled_tablets_.contains(tablet_id);
4615
145k
}
4616
4617
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4618
92.3k
                                                                int64_t tablet_id) {
4619
92.3k
    bool is_mow = true;
4620
92.3k
    if (partition_id != -1) {
4621
82.1k
        std::lock_guard lock(partition_mow_cache_mutex);
4622
82.1k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4623
            // cache hit
4624
1
            is_mow = it->second;
4625
1
            return is_mow ? 1 : 0;
4626
1
        }
4627
82.1k
    }
4628
4629
92.3k
    TabletIndexPB tablet_index;
4630
92.3k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4631
92.3k
    if (ret == 1) {
4632
        // maybe recycled
4633
92.1k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4634
92.1k
    }
4635
240
    if (ret != 0) {
4636
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4637
0
                     << ", tablet_id=" << tablet_id;
4638
0
        return ret;
4639
0
    }
4640
4641
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4642
    // obtaining its partition ID from the tablet index.
4643
240
    if (partition_id == -1) {
4644
0
        partition_id = tablet_index.partition_id();
4645
0
        std::lock_guard lock(partition_mow_cache_mutex);
4646
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4647
0
            is_mow = it->second;
4648
0
            return is_mow ? 1 : 0;
4649
0
        }
4650
0
    }
4651
4652
240
    std::string tablet_meta_key =
4653
240
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4654
240
                             partition_id, tablet_id});
4655
240
    std::string tablet_meta_value;
4656
240
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4657
240
    if (ret == 1) {
4658
        // maybe recycled
4659
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4660
10
    }
4661
230
    if (ret != 0) {
4662
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4663
0
                     << ", tablet_id=" << tablet_id;
4664
0
        return ret;
4665
0
    }
4666
4667
230
    TabletMetaCloudPB tablet_meta;
4668
230
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4669
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4670
0
                     << ", tablet_id=" << tablet_id;
4671
0
        return -1;
4672
0
    }
4673
230
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4674
230
    std::lock_guard lock(partition_mow_cache_mutex);
4675
230
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4676
230
    return it->second ? 1 : 0;
4677
230
}
4678
4679
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4680
92.3k
                                                         const std::string& rowset_id) {
4681
92.3k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4682
92.3k
    if (ret <= 0) {
4683
1.00k
        return ret;
4684
1.00k
    }
4685
4686
91.3k
    std::string dbm_start_key =
4687
91.3k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4688
91.3k
    std::string dbm_end_key = dbm_start_key;
4689
91.3k
    encode_int64(INT64_MAX, &dbm_end_key);
4690
91.3k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4691
91.3k
    if (ret != 0) {
4692
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4693
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4694
0
                     << " rowset_id=" << rowset_id;
4695
0
    }
4696
91.3k
    return ret;
4697
92.3k
}
4698
4699
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4700
51.2k
    std::string delete_bitmap_start =
4701
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4702
51.2k
    std::string delete_bitmap_end =
4703
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4704
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4705
51.2k
    if (ret != 0) {
4706
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4707
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4708
0
    }
4709
51.2k
    return ret;
4710
51.2k
}
4711
4712
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4713
4
    if (key.empty()) {
4714
0
        return false;
4715
0
    }
4716
4
    std::string_view key_view = key;
4717
4
    key_view.remove_prefix(1); // remove keyspace prefix
4718
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4719
4
    if (decode_key(&key_view, &decoded) != 0) {
4720
0
        return false;
4721
0
    }
4722
4
    if (decoded.size() < 4) {
4723
0
        return false;
4724
0
    }
4725
4
    try {
4726
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4727
4
    } catch (const std::bad_variant_access&) {
4728
0
        return false;
4729
0
    }
4730
4
    return true;
4731
4
}
4732
4733
14
int InstanceRecycler::recycle_packed_files() {
4734
14
    const std::string task_name = "recycle_packed_files";
4735
14
    auto start_tp = steady_clock::now();
4736
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4737
14
    int ret = 0;
4738
14
    PackedFileRecycleStats stats;
4739
4740
14
    register_recycle_task(task_name, start_time);
4741
14
    DORIS_CLOUD_DEFER {
4742
14
        unregister_recycle_task(task_name);
4743
14
        int64_t cost =
4744
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4745
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4746
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4747
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4748
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4749
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4750
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4751
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4752
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4753
14
                                                             stats.bytes_object_deleted);
4754
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4755
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4756
14
                .tag("instance_id", instance_id_)
4757
14
                .tag("num_scanned", stats.num_scanned)
4758
14
                .tag("num_corrected", stats.num_corrected)
4759
14
                .tag("num_deleted", stats.num_deleted)
4760
14
                .tag("num_failed", stats.num_failed)
4761
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4762
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4763
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4764
14
                .tag("bytes_deleted", stats.bytes_deleted)
4765
14
                .tag("ret", ret);
4766
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4741
14
    DORIS_CLOUD_DEFER {
4742
14
        unregister_recycle_task(task_name);
4743
14
        int64_t cost =
4744
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4745
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4746
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4747
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4748
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4749
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4750
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4751
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4752
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4753
14
                                                             stats.bytes_object_deleted);
4754
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4755
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4756
14
                .tag("instance_id", instance_id_)
4757
14
                .tag("num_scanned", stats.num_scanned)
4758
14
                .tag("num_corrected", stats.num_corrected)
4759
14
                .tag("num_deleted", stats.num_deleted)
4760
14
                .tag("num_failed", stats.num_failed)
4761
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4762
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4763
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4764
14
                .tag("bytes_deleted", stats.bytes_deleted)
4765
14
                .tag("ret", ret);
4766
14
    };
4767
4768
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4769
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4770
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4771
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
4768
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4769
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4770
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4771
4
    };
4772
4773
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4774
4775
14
    std::string begin = packed_file_key({instance_id_, ""});
4776
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4777
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4778
0
        ret = -1;
4779
0
    }
4780
4781
14
    return ret;
4782
14
}
4783
4784
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4785
                                                  RecyclerMetricsContext& metrics_context,
4786
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4787
0
    std::string tablet_key_begin, tablet_key_end;
4788
4789
0
    if (partition_id > 0) {
4790
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4791
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4792
0
    } else {
4793
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4794
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4795
0
    }
4796
    // for calculate the total num or bytes of recyled objects
4797
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4798
0
                                                          std::string_view v) -> int {
4799
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4800
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4801
0
            return 0;
4802
0
        }
4803
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4804
4805
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4806
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4807
0
            return 0;
4808
0
        }
4809
4810
0
        if (!is_empty_tablet) {
4811
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4812
0
                return 0;
4813
0
            }
4814
0
            tablet_metrics_context_.total_need_recycle_num++;
4815
0
        }
4816
0
        return 0;
4817
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_
4818
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4819
0
    metrics_context.report(true);
4820
0
    tablet_metrics_context_.report(true);
4821
0
    segment_metrics_context_.report(true);
4822
0
    return ret;
4823
0
}
4824
4825
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4826
0
                                                 RecyclerMetricsContext& metrics_context) {
4827
0
    int ret = 0;
4828
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4829
0
    std::unique_ptr<Transaction> txn;
4830
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4831
0
        LOG_WARNING("failed to recycle tablet ")
4832
0
                .tag("tablet id", tablet_id)
4833
0
                .tag("instance_id", instance_id_)
4834
0
                .tag("reason", "failed to create txn");
4835
0
        ret = -1;
4836
0
    }
4837
0
    GetRowsetResponse resp;
4838
0
    std::string msg;
4839
0
    MetaServiceCode code = MetaServiceCode::OK;
4840
    // get rowsets in tablet
4841
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4842
0
                        tablet_id, code, msg, &resp);
4843
0
    if (code != MetaServiceCode::OK) {
4844
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4845
0
                .tag("tablet id", tablet_id)
4846
0
                .tag("msg", msg)
4847
0
                .tag("code", code)
4848
0
                .tag("instance id", instance_id_);
4849
0
        ret = -1;
4850
0
    }
4851
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4852
        /*
4853
        * For compatibility, we skip the loop for [0-1] here.
4854
        * The purpose of this loop is to delete object files,
4855
        * and since [0-1] only has meta and doesn't have object files,
4856
        * skipping it doesn't affect system correctness.
4857
        *
4858
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4859
        * would return error -1 directly, causing the recycle operation to fail.
4860
        *
4861
        * [0-1] doesn't have resource id is a bug.
4862
        * In the future, we will fix this problem, after that,
4863
        * we can remove this if statement.
4864
        *
4865
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4866
        */
4867
4868
0
        if (rs_meta.end_version() == 1) {
4869
            // Assert that [0-1] has no resource_id to make sure
4870
            // this if statement will not be forgetted to remove
4871
            // when the resource id bug is fixed
4872
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4873
0
            continue;
4874
0
        }
4875
0
        if (!rs_meta.has_resource_id()) {
4876
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4877
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4878
0
                    .tag("instance_id", instance_id_)
4879
0
                    .tag("tablet_id", tablet_id);
4880
0
            continue;
4881
0
        }
4882
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4883
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4884
        // possible if the accessor is not initilized correctly
4885
0
        if (it == accessor_map_.end()) [[unlikely]] {
4886
0
            LOG_WARNING(
4887
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4888
0
                    "recycle process")
4889
0
                    .tag("tablet id", tablet_id)
4890
0
                    .tag("instance_id", instance_id_)
4891
0
                    .tag("resource_id", rs_meta.resource_id())
4892
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4893
0
            continue;
4894
0
        }
4895
4896
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4897
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4898
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4899
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4900
0
    }
4901
0
    return ret;
4902
0
}
4903
4904
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4905
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4906
4.26k
            .tag("instance_id", instance_id_)
4907
4.26k
            .tag("tablet_id", tablet_id);
4908
4909
4.26k
    if (should_recycle_versioned_keys()) {
4910
16
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4911
16
        if (ret != 0) {
4912
0
            return ret;
4913
0
        }
4914
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4915
        // during the recycle_versioned_tablet process.
4916
        //
4917
        // .. And remove restore job rowsets of this tablet too
4918
16
    }
4919
4920
4.26k
    int ret = 0;
4921
4.26k
    auto start_time = steady_clock::now();
4922
4923
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4924
4925
    // collect resource ids
4926
262
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4927
262
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4928
262
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4929
262
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4930
262
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4931
262
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4932
4933
262
    std::set<std::string> resource_ids;
4934
262
    int64_t recycle_rowsets_number = 0;
4935
262
    int64_t recycle_segments_number = 0;
4936
262
    int64_t recycle_rowsets_data_size = 0;
4937
262
    int64_t recycle_rowsets_index_size = 0;
4938
262
    int64_t recycle_restore_job_rowsets_number = 0;
4939
262
    int64_t recycle_restore_job_segments_number = 0;
4940
262
    int64_t recycle_restore_job_rowsets_data_size = 0;
4941
262
    int64_t recycle_restore_job_rowsets_index_size = 0;
4942
262
    int64_t max_rowset_version = 0;
4943
262
    int64_t min_rowset_creation_time = INT64_MAX;
4944
262
    int64_t max_rowset_creation_time = 0;
4945
262
    int64_t min_rowset_expiration_time = INT64_MAX;
4946
262
    int64_t max_rowset_expiration_time = 0;
4947
4948
262
    DORIS_CLOUD_DEFER {
4949
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4950
262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4951
262
                .tag("instance_id", instance_id_)
4952
262
                .tag("tablet_id", tablet_id)
4953
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4954
262
                .tag("recycle segments number", recycle_segments_number)
4955
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4956
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4957
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4958
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4959
262
                .tag("all restore job rowsets recycle data size",
4960
262
                     recycle_restore_job_rowsets_data_size)
4961
262
                .tag("all restore job rowsets recycle index size",
4962
262
                     recycle_restore_job_rowsets_index_size)
4963
262
                .tag("max rowset version", max_rowset_version)
4964
262
                .tag("min rowset creation time", min_rowset_creation_time)
4965
262
                .tag("max rowset creation time", max_rowset_creation_time)
4966
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4967
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4968
262
                .tag("task type", metrics_context.operation_type)
4969
262
                .tag("ret", ret);
4970
262
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4948
262
    DORIS_CLOUD_DEFER {
4949
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4950
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4951
262
                .tag("instance_id", instance_id_)
4952
262
                .tag("tablet_id", tablet_id)
4953
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4954
262
                .tag("recycle segments number", recycle_segments_number)
4955
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4956
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4957
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4958
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4959
262
                .tag("all restore job rowsets recycle data size",
4960
262
                     recycle_restore_job_rowsets_data_size)
4961
262
                .tag("all restore job rowsets recycle index size",
4962
262
                     recycle_restore_job_rowsets_index_size)
4963
262
                .tag("max rowset version", max_rowset_version)
4964
262
                .tag("min rowset creation time", min_rowset_creation_time)
4965
262
                .tag("max rowset creation time", max_rowset_creation_time)
4966
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4967
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4968
262
                .tag("task type", metrics_context.operation_type)
4969
262
                .tag("ret", ret);
4970
262
    };
4971
4972
262
    std::unique_ptr<Transaction> txn;
4973
262
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4974
0
        LOG_WARNING("failed to recycle tablet ")
4975
0
                .tag("tablet id", tablet_id)
4976
0
                .tag("instance_id", instance_id_)
4977
0
                .tag("reason", "failed to create txn");
4978
0
        ret = -1;
4979
0
    }
4980
262
    GetRowsetResponse resp;
4981
262
    std::string msg;
4982
262
    MetaServiceCode code = MetaServiceCode::OK;
4983
    // get rowsets in tablet
4984
262
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4985
262
                        tablet_id, code, msg, &resp);
4986
262
    if (code != MetaServiceCode::OK) {
4987
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4988
0
                .tag("tablet id", tablet_id)
4989
0
                .tag("msg", msg)
4990
0
                .tag("code", code)
4991
0
                .tag("instance id", instance_id_);
4992
0
        ret = -1;
4993
0
    }
4994
262
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4995
4996
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4997
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4998
3
            if (rs_meta.num_segments() <= 0) {
4999
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5000
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5001
2
                        .tag("instance_id", instance_id_)
5002
2
                        .tag("tablet_id", tablet_id);
5003
2
                recycle_rowsets_number += 1;
5004
2
                continue;
5005
2
            }
5006
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5007
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5008
1
                    .tag("instance_id", instance_id_)
5009
1
                    .tag("tablet_id", tablet_id);
5010
1
            return -1;
5011
3
        }
5012
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5013
1
                << "rs_meta" << rs_meta.ShortDebugString();
5014
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5015
        // possible if the accessor is not initilized correctly
5016
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5017
1
            LOG_WARNING(
5018
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5019
1
                    "recycle process")
5020
1
                    .tag("tablet id", tablet_id)
5021
1
                    .tag("instance_id", instance_id_)
5022
1
                    .tag("resource_id", rs_meta.resource_id())
5023
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5024
1
            return -1;
5025
1
        }
5026
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5027
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5028
0
                    .tag("instance_id", instance_id_)
5029
0
                    .tag("tablet_id", tablet_id)
5030
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5031
0
            return -1;
5032
0
        }
5033
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5034
2.54k
                                                           nullptr) != 0) {
5035
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5036
0
                    .tag("instance_id", instance_id_)
5037
0
                    .tag("tablet_id", tablet_id)
5038
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5039
0
            return -1;
5040
0
        }
5041
2.54k
        recycle_rowsets_number += 1;
5042
2.54k
        recycle_segments_number += rs_meta.num_segments();
5043
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5044
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5045
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5046
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5047
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5048
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5049
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5050
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5051
2.54k
    }
5052
5053
    // get restore job rowset in tablet
5054
260
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5055
260
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5056
260
    if (code != MetaServiceCode::OK) {
5057
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5058
0
                .tag("tablet id", tablet_id)
5059
0
                .tag("msg", msg)
5060
0
                .tag("code", code)
5061
0
                .tag("instance id", instance_id_);
5062
0
        return -1;
5063
0
    }
5064
5065
260
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5066
0
        if (!rs_meta.has_resource_id()) {
5067
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5068
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5069
0
                    .tag("instance_id", instance_id_)
5070
0
                    .tag("tablet_id", tablet_id);
5071
0
            return -1;
5072
0
        }
5073
5074
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5075
        // possible if the accessor is not initilized correctly
5076
0
        if (it == accessor_map_.end()) [[unlikely]] {
5077
0
            LOG_WARNING(
5078
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5079
0
                    "recycle process")
5080
0
                    .tag("tablet id", tablet_id)
5081
0
                    .tag("instance_id", instance_id_)
5082
0
                    .tag("resource_id", rs_meta.resource_id())
5083
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5084
0
            return -1;
5085
0
        }
5086
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5087
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5088
0
                    .tag("instance_id", instance_id_)
5089
0
                    .tag("tablet_id", tablet_id)
5090
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5091
0
            return -1;
5092
0
        }
5093
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5094
0
                                                           nullptr) != 0) {
5095
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5096
0
                    .tag("instance_id", instance_id_)
5097
0
                    .tag("tablet_id", tablet_id)
5098
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5099
0
            return -1;
5100
0
        }
5101
0
        recycle_restore_job_rowsets_number += 1;
5102
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5103
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5104
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5105
0
        resource_ids.emplace(rs_meta.resource_id());
5106
0
    }
5107
5108
260
    LOG_INFO("recycle tablet start to delete object")
5109
260
            .tag("instance id", instance_id_)
5110
260
            .tag("tablet id", tablet_id)
5111
260
            .tag("recycle tablet resource ids are",
5112
260
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5113
260
                                 [](std::string rs_id, const auto& it) {
5114
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5115
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
5113
217
                                 [](std::string rs_id, const auto& it) {
5114
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5115
217
                                 }));
5116
5117
260
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5118
260
            _thread_pool_group.s3_producer_pool,
5119
260
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5120
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
5120
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5121
5122
    // delete all rowset data in this tablet
5123
    // ATTN: there may be data leak if not all accessor initilized successfully
5124
    //       partial data deleted if the tablet is stored cross-storage vault
5125
    //       vault id is not attached to TabletMeta...
5126
260
    for (const auto& resource_id : resource_ids) {
5127
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5128
217
        concurrent_delete_executor.add(
5129
217
                [&, rs_id = resource_id,
5130
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5131
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5132
217
                    if (res != 0) {
5133
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5134
3
                                     << " path=" << accessor_ptr->uri()
5135
3
                                     << " task type=" << metrics_context.operation_type;
5136
3
                        return std::make_pair(-1, rs_id);
5137
3
                    }
5138
214
                    return std::make_pair(0, rs_id);
5139
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5130
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5131
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5132
217
                    if (res != 0) {
5133
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5134
3
                                     << " path=" << accessor_ptr->uri()
5135
3
                                     << " task type=" << metrics_context.operation_type;
5136
3
                        return std::make_pair(-1, rs_id);
5137
3
                    }
5138
214
                    return std::make_pair(0, rs_id);
5139
217
                });
5140
217
    }
5141
5142
260
    bool finished = true;
5143
260
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5144
260
    for (auto& r : rets) {
5145
217
        if (r.first != 0) {
5146
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5147
3
            ret = -1;
5148
3
        }
5149
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5150
217
    }
5151
260
    ret = finished ? ret : -1;
5152
5153
260
    if (ret != 0) { // failed recycle tablet data
5154
3
        LOG_WARNING("ret!=0")
5155
3
                .tag("finished", finished)
5156
3
                .tag("ret", ret)
5157
3
                .tag("instance_id", instance_id_)
5158
3
                .tag("tablet_id", tablet_id);
5159
3
        return ret;
5160
3
    }
5161
5162
257
    tablet_metrics_context_.total_recycled_data_size +=
5163
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5164
257
    tablet_metrics_context_.total_recycled_num += 1;
5165
257
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5166
257
    segment_metrics_context_.total_recycled_data_size +=
5167
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5168
257
    metrics_context.total_recycled_data_size +=
5169
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5170
257
    tablet_metrics_context_.report();
5171
257
    segment_metrics_context_.report();
5172
257
    metrics_context.report();
5173
5174
257
    txn.reset();
5175
257
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5176
0
        LOG_WARNING("failed to recycle tablet ")
5177
0
                .tag("tablet id", tablet_id)
5178
0
                .tag("instance_id", instance_id_)
5179
0
                .tag("reason", "failed to create txn");
5180
0
        ret = -1;
5181
0
    }
5182
    // delete all rowset kv in this tablet
5183
257
    txn->remove(rs_key0, rs_key1);
5184
257
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5185
257
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5186
5187
    // remove delete bitmap for MoW table
5188
257
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5189
257
    txn->remove(pending_key);
5190
257
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5191
257
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5192
257
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5193
5194
257
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5195
257
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5196
257
    txn->remove(dbm_start_key, dbm_end_key);
5197
257
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5198
257
              << " end=" << hex(dbm_end_key);
5199
5200
257
    TxnErrorCode err = txn->commit();
5201
257
    if (err != TxnErrorCode::TXN_OK) {
5202
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5203
0
        ret = -1;
5204
0
    }
5205
5206
257
    if (ret == 0) {
5207
        // All object files under tablet have been deleted
5208
257
        std::lock_guard lock(recycled_tablets_mtx_);
5209
257
        recycled_tablets_.insert(tablet_id);
5210
257
    }
5211
5212
257
    return ret;
5213
260
}
5214
5215
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5216
16
                                               RecyclerMetricsContext& metrics_context) {
5217
16
    int ret = 0;
5218
16
    auto start_time = steady_clock::now();
5219
5220
16
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5221
5222
    // collect resource ids
5223
13
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5224
13
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5225
13
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5226
13
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5227
5228
13
    int64_t recycle_rowsets_number = 0;
5229
13
    int64_t recycle_segments_number = 0;
5230
13
    int64_t recycle_rowsets_data_size = 0;
5231
13
    int64_t recycle_rowsets_index_size = 0;
5232
13
    int64_t max_rowset_version = 0;
5233
13
    int64_t min_rowset_creation_time = INT64_MAX;
5234
13
    int64_t max_rowset_creation_time = 0;
5235
13
    int64_t min_rowset_expiration_time = INT64_MAX;
5236
13
    int64_t max_rowset_expiration_time = 0;
5237
5238
13
    DORIS_CLOUD_DEFER {
5239
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5240
13
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5241
13
                .tag("instance_id", instance_id_)
5242
13
                .tag("tablet_id", tablet_id)
5243
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5244
13
                .tag("recycle segments number", recycle_segments_number)
5245
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5246
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5247
13
                .tag("max rowset version", max_rowset_version)
5248
13
                .tag("min rowset creation time", min_rowset_creation_time)
5249
13
                .tag("max rowset creation time", max_rowset_creation_time)
5250
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5251
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5252
13
                .tag("ret", ret);
5253
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5238
13
    DORIS_CLOUD_DEFER {
5239
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5240
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5241
13
                .tag("instance_id", instance_id_)
5242
13
                .tag("tablet_id", tablet_id)
5243
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5244
13
                .tag("recycle segments number", recycle_segments_number)
5245
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5246
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5247
13
                .tag("max rowset version", max_rowset_version)
5248
13
                .tag("min rowset creation time", min_rowset_creation_time)
5249
13
                .tag("max rowset creation time", max_rowset_creation_time)
5250
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5251
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5252
13
                .tag("ret", ret);
5253
13
    };
5254
5255
13
    std::unique_ptr<Transaction> txn;
5256
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5257
0
        LOG_WARNING("failed to recycle tablet ")
5258
0
                .tag("tablet id", tablet_id)
5259
0
                .tag("instance_id", instance_id_)
5260
0
                .tag("reason", "failed to create txn");
5261
0
        ret = -1;
5262
0
    }
5263
5264
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5265
    // by the related operation logs.
5266
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5267
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5268
13
    MetaReader meta_reader(instance_id_);
5269
13
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5270
13
    if (err == TxnErrorCode::TXN_OK) {
5271
13
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5272
13
    }
5273
13
    if (err != TxnErrorCode::TXN_OK) {
5274
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5275
0
                .tag("tablet id", tablet_id)
5276
0
                .tag("err", err)
5277
0
                .tag("instance id", instance_id_);
5278
0
        ret = -1;
5279
0
    }
5280
5281
13
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5282
13
             load_rowset_metas.size(), compact_rowset_metas.size())
5283
13
            .tag("instance_id", instance_id_)
5284
13
            .tag("tablet_id", tablet_id);
5285
5286
13
    SyncExecutor<int> concurrent_delete_executor(
5287
13
            _thread_pool_group.s3_producer_pool,
5288
13
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5289
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
5290
5291
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5292
61
        recycle_rowsets_number += 1;
5293
61
        recycle_segments_number += rs_meta.num_segments();
5294
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5295
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5296
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5297
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5298
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5299
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5300
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5301
61
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5291
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5292
61
        recycle_rowsets_number += 1;
5293
61
        recycle_segments_number += rs_meta.num_segments();
5294
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5295
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5296
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5297
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5298
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5299
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5300
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5301
61
    };
5302
5303
13
    std::vector<RowsetDeleteTask> all_tasks;
5304
61
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5305
61
        update_rowset_stats(rs_meta);
5306
        // Version 0-1 rowset has no resource_id and no actual data files,
5307
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5308
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5309
61
        RowsetDeleteTask task;
5310
61
        task.rowset_meta = rs_meta;
5311
61
        task.versioned_rowset_key =
5312
61
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5313
61
        task.non_versioned_rowset_key =
5314
61
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5315
61
        task.versionstamp = versionstamp;
5316
61
        all_tasks.push_back(std::move(task));
5317
61
    }
5318
5319
13
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5320
0
        update_rowset_stats(rs_meta);
5321
        // Version 0-1 rowset has no resource_id and no actual data files,
5322
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5323
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5324
0
        RowsetDeleteTask task;
5325
0
        task.rowset_meta = rs_meta;
5326
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5327
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5328
0
        task.non_versioned_rowset_key =
5329
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5330
0
        task.versionstamp = versionstamp;
5331
0
        all_tasks.push_back(std::move(task));
5332
0
    }
5333
5334
13
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5335
0
        RecycleRowsetPB recycle_rowset;
5336
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5337
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5338
0
            return -1;
5339
0
        }
5340
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5341
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5342
                // in old version, keep this key-value pair and it needs to be checked manually
5343
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5344
0
                return -1;
5345
0
            }
5346
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5347
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5348
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5349
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5350
0
                return -1;
5351
0
            }
5352
            // decode rowset_id
5353
0
            auto k1 = k;
5354
0
            k1.remove_prefix(1);
5355
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5356
0
            decode_key(&k1, &out);
5357
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5358
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5359
0
            LOG_INFO("delete old-version rowset data")
5360
0
                    .tag("instance_id", instance_id_)
5361
0
                    .tag("tablet_id", tablet_id)
5362
0
                    .tag("rowset_id", rowset_id);
5363
5364
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5365
            // so we must use prefix deletion directly instead of batch delete.
5366
0
            concurrent_delete_executor.add(
5367
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5368
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5369
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5370
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
5371
0
        } else {
5372
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5373
            // Version 0-1 rowset has no resource_id and no actual data files,
5374
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5375
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5376
0
            RowsetDeleteTask task;
5377
0
            task.rowset_meta = rowset_meta;
5378
0
            task.recycle_rowset_key = k;
5379
0
            all_tasks.push_back(std::move(task));
5380
0
        }
5381
0
        return 0;
5382
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_
5383
5384
13
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5385
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5386
0
                .tag("tablet id", tablet_id)
5387
0
                .tag("instance_id", instance_id_)
5388
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5389
0
        ret = -1;
5390
0
    }
5391
5392
    // Phase 1: Classify tasks by ref_count
5393
13
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5394
61
    for (auto& task : all_tasks) {
5395
61
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5396
61
        if (classify_ret < 0) {
5397
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5398
0
                    .tag("instance_id", instance_id_)
5399
0
                    .tag("tablet_id", tablet_id)
5400
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5401
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5402
0
                return recycle_rowset_meta_and_data(t);
5403
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5404
0
        }
5405
61
    }
5406
5407
13
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5408
5409
13
    LOG_INFO("batch delete plan created")
5410
13
            .tag("instance_id", instance_id_)
5411
13
            .tag("tablet_id", tablet_id)
5412
13
            .tag("plan_count", batch_delete_tasks.size());
5413
5414
    // Phase 2: Execute batch delete using existing delete_rowset_data
5415
13
    if (!batch_delete_tasks.empty()) {
5416
11
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5417
50
        for (const auto& task : batch_delete_tasks) {
5418
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5419
50
            if (task.rowset_meta.resource_id().empty()) {
5420
11
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5421
11
                        .tag("instance_id", instance_id_)
5422
11
                        .tag("tablet_id", tablet_id)
5423
11
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5424
11
                continue;
5425
11
            }
5426
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5427
39
        }
5428
5429
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5430
11
        bool delete_success = true;
5431
11
        if (!rowsets_to_delete.empty()) {
5432
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5433
9
                                                         "batch_delete_versioned_tablet");
5434
9
            int delete_ret = delete_rowset_data(
5435
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5436
9
            if (delete_ret != 0) {
5437
0
                LOG_WARNING("batch delete execution failed")
5438
0
                        .tag("instance_id", instance_id_)
5439
0
                        .tag("tablet_id", tablet_id);
5440
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5441
0
                ret = -1;
5442
0
                delete_success = false;
5443
0
            }
5444
9
        }
5445
5446
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5447
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5448
11
        if (delete_success) {
5449
11
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5450
11
            if (cleanup_ret != 0) {
5451
0
                LOG_WARNING("batch delete cleanup failed")
5452
0
                        .tag("instance_id", instance_id_)
5453
0
                        .tag("tablet_id", tablet_id);
5454
0
                ret = -1;
5455
0
            }
5456
11
        }
5457
11
    }
5458
5459
    // Always wait for fallback tasks to complete before returning
5460
13
    bool finished = true;
5461
13
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5462
13
    for (int r : rets) {
5463
0
        if (r != 0) {
5464
0
            ret = -1;
5465
0
        }
5466
0
    }
5467
5468
13
    ret = finished ? ret : -1;
5469
5470
13
    if (ret != 0) { // failed recycle tablet data
5471
0
        LOG_WARNING("recycle versioned tablet failed")
5472
0
                .tag("finished", finished)
5473
0
                .tag("ret", ret)
5474
0
                .tag("instance_id", instance_id_)
5475
0
                .tag("tablet_id", tablet_id);
5476
0
        return ret;
5477
0
    }
5478
5479
13
    tablet_metrics_context_.total_recycled_data_size +=
5480
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5481
13
    tablet_metrics_context_.total_recycled_num += 1;
5482
13
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5483
13
    segment_metrics_context_.total_recycled_data_size +=
5484
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5485
13
    metrics_context.total_recycled_data_size +=
5486
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5487
13
    tablet_metrics_context_.report();
5488
13
    segment_metrics_context_.report();
5489
13
    metrics_context.report();
5490
5491
13
    txn.reset();
5492
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5493
0
        LOG_WARNING("failed to recycle tablet ")
5494
0
                .tag("tablet id", tablet_id)
5495
0
                .tag("instance_id", instance_id_)
5496
0
                .tag("reason", "failed to create txn");
5497
0
        ret = -1;
5498
0
    }
5499
    // delete all rowset kv in this tablet
5500
13
    txn->remove(rs_key0, rs_key1);
5501
13
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5502
5503
    // remove delete bitmap for MoW table
5504
13
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5505
13
    txn->remove(pending_key);
5506
13
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5507
13
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5508
13
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5509
5510
13
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5511
13
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5512
13
    txn->remove(dbm_start_key, dbm_end_key);
5513
13
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5514
13
              << " end=" << hex(dbm_end_key);
5515
5516
13
    err = txn->commit();
5517
13
    if (err != TxnErrorCode::TXN_OK) {
5518
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5519
0
        ret = -1;
5520
0
    }
5521
5522
13
    if (ret == 0) {
5523
        // All object files under tablet have been deleted
5524
13
        std::lock_guard lock(recycled_tablets_mtx_);
5525
13
        recycled_tablets_.insert(tablet_id);
5526
13
    }
5527
5528
13
    return ret;
5529
13
}
5530
5531
66
int InstanceRecycler::recycle_rowsets() {
5532
66
    if (should_recycle_versioned_keys()) {
5533
5
        return recycle_versioned_rowsets();
5534
5
    }
5535
5536
61
    const std::string task_name = "recycle_rowsets";
5537
61
    int64_t num_scanned = 0;
5538
61
    int64_t num_expired = 0;
5539
61
    int64_t num_prepare = 0;
5540
61
    int64_t num_compacted = 0;
5541
61
    int64_t num_empty_rowset = 0;
5542
61
    size_t total_rowset_key_size = 0;
5543
61
    size_t total_rowset_value_size = 0;
5544
61
    size_t expired_rowset_size = 0;
5545
61
    std::atomic_long num_recycled = 0;
5546
61
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5547
5548
61
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5549
61
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5550
61
    std::string recyc_rs_key0;
5551
61
    std::string recyc_rs_key1;
5552
61
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5553
61
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5554
5555
61
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5556
5557
61
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5558
61
    register_recycle_task(task_name, start_time);
5559
5560
61
    DORIS_CLOUD_DEFER {
5561
61
        unregister_recycle_task(task_name);
5562
61
        int64_t cost =
5563
61
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5564
61
        metrics_context.finish_report();
5565
61
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5566
61
                .tag("instance_id", instance_id_)
5567
61
                .tag("num_scanned", num_scanned)
5568
61
                .tag("num_expired", num_expired)
5569
61
                .tag("num_recycled", num_recycled)
5570
61
                .tag("num_recycled.prepare", num_prepare)
5571
61
                .tag("num_recycled.compacted", num_compacted)
5572
61
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5573
61
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5574
61
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5575
61
                .tag("expired_rowset_meta_size", expired_rowset_size);
5576
61
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5560
7
    DORIS_CLOUD_DEFER {
5561
7
        unregister_recycle_task(task_name);
5562
7
        int64_t cost =
5563
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5564
7
        metrics_context.finish_report();
5565
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5566
7
                .tag("instance_id", instance_id_)
5567
7
                .tag("num_scanned", num_scanned)
5568
7
                .tag("num_expired", num_expired)
5569
7
                .tag("num_recycled", num_recycled)
5570
7
                .tag("num_recycled.prepare", num_prepare)
5571
7
                .tag("num_recycled.compacted", num_compacted)
5572
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5573
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5574
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5575
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5576
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5560
54
    DORIS_CLOUD_DEFER {
5561
54
        unregister_recycle_task(task_name);
5562
54
        int64_t cost =
5563
54
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5564
54
        metrics_context.finish_report();
5565
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5566
54
                .tag("instance_id", instance_id_)
5567
54
                .tag("num_scanned", num_scanned)
5568
54
                .tag("num_expired", num_expired)
5569
54
                .tag("num_recycled", num_recycled)
5570
54
                .tag("num_recycled.prepare", num_prepare)
5571
54
                .tag("num_recycled.compacted", num_compacted)
5572
54
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5573
54
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5574
54
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5575
54
                .tag("expired_rowset_meta_size", expired_rowset_size);
5576
54
    };
5577
5578
61
    std::vector<std::string> rowset_keys;
5579
61
    std::vector<std::string> rowset_keys_to_mark_recycled;
5580
61
    std::vector<std::string> rowset_keys_to_abort_job;
5581
    // rowset_id -> rowset_meta
5582
    // store rowset id and meta for statistics rs size when delete
5583
61
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5584
5585
61
    std::mutex async_recycled_rowset_keys_mutex;
5586
61
    std::vector<std::string> async_recycled_rowset_keys;
5587
61
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5588
61
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5589
61
    worker_pool->start();
5590
61
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5591
61
                                            int64_t partition_id, int64_t tablet_id,
5592
30.9k
                                            const std::string& rowset_id) {
5593
        // Try to delete rowset data in background thread
5594
30.9k
        int ret = worker_pool->submit_with_timeout(
5595
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5596
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5598
0
                        return;
5599
0
                    }
5600
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5601
28.4k
                        0) {
5602
0
                        return;
5603
0
                    }
5604
28.4k
                    std::vector<std::string> keys;
5605
28.4k
                    {
5606
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5607
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5608
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5609
278
                            keys.swap(async_recycled_rowset_keys);
5610
278
                        }
5611
28.4k
                    }
5612
28.4k
                    if (keys.empty()) return;
5613
278
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5614
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5615
0
                                     << instance_id_;
5616
278
                    } else {
5617
278
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5618
278
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5619
278
                                           num_recycled, start_time);
5620
278
                    }
5621
278
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5595
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5596
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5598
0
                        return;
5599
0
                    }
5600
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5601
1
                        0) {
5602
0
                        return;
5603
0
                    }
5604
1
                    std::vector<std::string> keys;
5605
1
                    {
5606
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5607
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5608
1
                        if (async_recycled_rowset_keys.size() > 100) {
5609
0
                            keys.swap(async_recycled_rowset_keys);
5610
0
                        }
5611
1
                    }
5612
1
                    if (keys.empty()) return;
5613
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5614
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5615
0
                                     << instance_id_;
5616
0
                    } else {
5617
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5618
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5619
0
                                           num_recycled, start_time);
5620
0
                    }
5621
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5595
28.4k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5596
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5597
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5598
0
                        return;
5599
0
                    }
5600
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5601
28.4k
                        0) {
5602
0
                        return;
5603
0
                    }
5604
28.4k
                    std::vector<std::string> keys;
5605
28.4k
                    {
5606
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5607
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5608
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5609
278
                            keys.swap(async_recycled_rowset_keys);
5610
278
                        }
5611
28.4k
                    }
5612
28.4k
                    if (keys.empty()) return;
5613
278
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5614
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5615
0
                                     << instance_id_;
5616
278
                    } else {
5617
278
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5618
278
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5619
278
                                           num_recycled, start_time);
5620
278
                    }
5621
278
                },
5622
30.9k
                0);
5623
30.9k
        if (ret == 0) return 0;
5624
        // Submit task failed, delete rowset data in current thread
5625
2.43k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5626
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5627
0
            return -1;
5628
0
        }
5629
2.43k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5630
0
            return -1;
5631
0
        }
5632
2.43k
        rowset_keys.push_back(std::move(key));
5633
2.43k
        return 0;
5634
2.43k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5592
1
                                            const std::string& rowset_id) {
5593
        // Try to delete rowset data in background thread
5594
1
        int ret = worker_pool->submit_with_timeout(
5595
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5596
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5597
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5598
1
                        return;
5599
1
                    }
5600
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5601
1
                        0) {
5602
1
                        return;
5603
1
                    }
5604
1
                    std::vector<std::string> keys;
5605
1
                    {
5606
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5607
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5608
1
                        if (async_recycled_rowset_keys.size() > 100) {
5609
1
                            keys.swap(async_recycled_rowset_keys);
5610
1
                        }
5611
1
                    }
5612
1
                    if (keys.empty()) return;
5613
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5614
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5615
1
                                     << instance_id_;
5616
1
                    } else {
5617
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5618
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5619
1
                                           num_recycled, start_time);
5620
1
                    }
5621
1
                },
5622
1
                0);
5623
1
        if (ret == 0) return 0;
5624
        // Submit task failed, delete rowset data in current thread
5625
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5626
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5627
0
            return -1;
5628
0
        }
5629
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5630
0
            return -1;
5631
0
        }
5632
0
        rowset_keys.push_back(std::move(key));
5633
0
        return 0;
5634
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5592
30.9k
                                            const std::string& rowset_id) {
5593
        // Try to delete rowset data in background thread
5594
30.9k
        int ret = worker_pool->submit_with_timeout(
5595
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5596
30.9k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5597
30.9k
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5598
30.9k
                        return;
5599
30.9k
                    }
5600
30.9k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5601
30.9k
                        0) {
5602
30.9k
                        return;
5603
30.9k
                    }
5604
30.9k
                    std::vector<std::string> keys;
5605
30.9k
                    {
5606
30.9k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5607
30.9k
                        async_recycled_rowset_keys.push_back(std::move(key));
5608
30.9k
                        if (async_recycled_rowset_keys.size() > 100) {
5609
30.9k
                            keys.swap(async_recycled_rowset_keys);
5610
30.9k
                        }
5611
30.9k
                    }
5612
30.9k
                    if (keys.empty()) return;
5613
30.9k
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5614
30.9k
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5615
30.9k
                                     << instance_id_;
5616
30.9k
                    } else {
5617
30.9k
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5618
30.9k
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5619
30.9k
                                           num_recycled, start_time);
5620
30.9k
                    }
5621
30.9k
                },
5622
30.9k
                0);
5623
30.9k
        if (ret == 0) return 0;
5624
        // Submit task failed, delete rowset data in current thread
5625
2.43k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5626
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5627
0
            return -1;
5628
0
        }
5629
2.43k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5630
0
            return -1;
5631
0
        }
5632
2.43k
        rowset_keys.push_back(std::move(key));
5633
2.43k
        return 0;
5634
2.43k
    };
5635
5636
61
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5637
5638
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5639
124k
        ++num_scanned;
5640
124k
        total_rowset_key_size += k.size();
5641
124k
        total_rowset_value_size += v.size();
5642
124k
        RecycleRowsetPB rowset;
5643
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5644
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5645
0
            return -1;
5646
0
        }
5647
5648
124k
        int64_t current_time = ::time(nullptr);
5649
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5650
5651
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5652
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5653
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5654
124k
        if (current_time < expiration) { // not expired
5655
0
            return 0;
5656
0
        }
5657
124k
        ++num_expired;
5658
124k
        expired_rowset_size += v.size();
5659
5660
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5661
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5662
                // in old version, keep this key-value pair and it needs to be checked manually
5663
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5664
0
                return -1;
5665
0
            }
5666
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5667
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5668
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5669
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5670
10.0k
                rowset_keys.emplace_back(k);
5671
10.0k
                return 0;
5672
10.0k
            }
5673
            // decode rowset_id
5674
10.2k
            auto k1 = k;
5675
10.2k
            k1.remove_prefix(1);
5676
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5677
10.2k
            decode_key(&k1, &out);
5678
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5679
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5680
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5681
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5682
10.2k
                      << " task_type=" << metrics_context.operation_type;
5683
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5684
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5685
0
                return -1;
5686
0
            }
5687
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5688
10.2k
            metrics_context.total_recycled_num++;
5689
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5690
10.2k
                    rowset.rowset_meta().total_disk_size();
5691
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5692
10.2k
            return 0;
5693
10.2k
        }
5694
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5695
5696
        // TODO(plat1ko): check rowset not referenced
5697
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5698
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5699
0
                LOG_INFO("recycle rowset that has empty resource id");
5700
0
            } else {
5701
                // other situations, keep this key-value pair and it needs to be checked manually
5702
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5703
0
                return -1;
5704
0
            }
5705
0
        }
5706
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5707
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5708
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5709
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5710
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5711
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5712
104k
                  << " rowset_meta_size=" << v.size()
5713
104k
                  << " creation_time=" << rowset_meta->creation_time()
5714
104k
                  << " task_type=" << metrics_context.operation_type;
5715
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5716
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5717
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5718
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5719
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5720
20.0k
                                 "kv "
5721
20.0k
                                 "at next turn, instance_id="
5722
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5723
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5724
20.0k
                              << rowset_meta->end_version() << "]";
5725
20.0k
                    return 0;
5726
20.0k
                }
5727
50.0k
            }
5728
5729
30.9k
            num_prepare += 1;
5730
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5731
30.9k
                rowset_meta->end_version() != 1) {
5732
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5733
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5734
10.2k
                                 "instance_id="
5735
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5736
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5737
10.2k
                              << rowset_meta->end_version() << "]";
5738
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5739
10.2k
                    return 0;
5740
10.2k
                }
5741
30.2k
            }
5742
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5743
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5744
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5745
0
                return -1;
5746
0
            }
5747
53.1k
        } else {
5748
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5749
53.1k
            rowset_keys.emplace_back(k);
5750
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5751
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5752
53.1k
                ++num_empty_rowset;
5753
53.1k
            }
5754
53.1k
        }
5755
73.7k
        return 0;
5756
104k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5638
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5639
7
        ++num_scanned;
5640
7
        total_rowset_key_size += k.size();
5641
7
        total_rowset_value_size += v.size();
5642
7
        RecycleRowsetPB rowset;
5643
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5644
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5645
0
            return -1;
5646
0
        }
5647
5648
7
        int64_t current_time = ::time(nullptr);
5649
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5650
5651
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5652
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5653
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5654
7
        if (current_time < expiration) { // not expired
5655
0
            return 0;
5656
0
        }
5657
7
        ++num_expired;
5658
7
        expired_rowset_size += v.size();
5659
5660
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5661
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5662
                // in old version, keep this key-value pair and it needs to be checked manually
5663
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5664
0
                return -1;
5665
0
            }
5666
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5667
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5668
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5669
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5670
0
                rowset_keys.emplace_back(k);
5671
0
                return 0;
5672
0
            }
5673
            // decode rowset_id
5674
0
            auto k1 = k;
5675
0
            k1.remove_prefix(1);
5676
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5677
0
            decode_key(&k1, &out);
5678
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5679
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5680
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5681
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5682
0
                      << " task_type=" << metrics_context.operation_type;
5683
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5684
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5685
0
                return -1;
5686
0
            }
5687
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5688
0
            metrics_context.total_recycled_num++;
5689
0
            segment_metrics_context_.total_recycled_data_size +=
5690
0
                    rowset.rowset_meta().total_disk_size();
5691
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5692
0
            return 0;
5693
0
        }
5694
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5695
5696
        // TODO(plat1ko): check rowset not referenced
5697
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5698
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5699
0
                LOG_INFO("recycle rowset that has empty resource id");
5700
0
            } else {
5701
                // other situations, keep this key-value pair and it needs to be checked manually
5702
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5703
0
                return -1;
5704
0
            }
5705
0
        }
5706
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5707
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5708
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5709
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5710
7
                  << "] txn_id=" << rowset_meta->txn_id()
5711
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5712
7
                  << " rowset_meta_size=" << v.size()
5713
7
                  << " creation_time=" << rowset_meta->creation_time()
5714
7
                  << " task_type=" << metrics_context.operation_type;
5715
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5716
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5717
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5718
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5719
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5720
4
                                 "kv "
5721
4
                                 "at next turn, instance_id="
5722
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5723
4
                              << " version=[" << rowset_meta->start_version() << '-'
5724
4
                              << rowset_meta->end_version() << "]";
5725
4
                    return 0;
5726
4
                }
5727
6
            }
5728
5729
3
            num_prepare += 1;
5730
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5731
3
                rowset_meta->end_version() != 1) {
5732
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5733
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5734
2
                                 "instance_id="
5735
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5736
2
                              << " version=[" << rowset_meta->start_version() << '-'
5737
2
                              << rowset_meta->end_version() << "]";
5738
2
                    rowset_keys_to_abort_job.emplace_back(k);
5739
2
                    return 0;
5740
2
                }
5741
2
            }
5742
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5743
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5744
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5745
0
                return -1;
5746
0
            }
5747
1
        } else {
5748
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5749
0
            rowset_keys.emplace_back(k);
5750
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5751
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5752
0
                ++num_empty_rowset;
5753
0
            }
5754
0
        }
5755
1
        return 0;
5756
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5638
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5639
124k
        ++num_scanned;
5640
124k
        total_rowset_key_size += k.size();
5641
124k
        total_rowset_value_size += v.size();
5642
124k
        RecycleRowsetPB rowset;
5643
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5644
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5645
0
            return -1;
5646
0
        }
5647
5648
124k
        int64_t current_time = ::time(nullptr);
5649
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5650
5651
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5652
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5653
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5654
124k
        if (current_time < expiration) { // not expired
5655
0
            return 0;
5656
0
        }
5657
124k
        ++num_expired;
5658
124k
        expired_rowset_size += v.size();
5659
5660
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5661
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5662
                // in old version, keep this key-value pair and it needs to be checked manually
5663
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5664
0
                return -1;
5665
0
            }
5666
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5667
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5668
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5669
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5670
10.0k
                rowset_keys.emplace_back(k);
5671
10.0k
                return 0;
5672
10.0k
            }
5673
            // decode rowset_id
5674
10.2k
            auto k1 = k;
5675
10.2k
            k1.remove_prefix(1);
5676
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5677
10.2k
            decode_key(&k1, &out);
5678
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5679
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5680
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5681
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5682
10.2k
                      << " task_type=" << metrics_context.operation_type;
5683
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5684
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5685
0
                return -1;
5686
0
            }
5687
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5688
10.2k
            metrics_context.total_recycled_num++;
5689
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5690
10.2k
                    rowset.rowset_meta().total_disk_size();
5691
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5692
10.2k
            return 0;
5693
10.2k
        }
5694
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5695
5696
        // TODO(plat1ko): check rowset not referenced
5697
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5698
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5699
0
                LOG_INFO("recycle rowset that has empty resource id");
5700
0
            } else {
5701
                // other situations, keep this key-value pair and it needs to be checked manually
5702
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5703
0
                return -1;
5704
0
            }
5705
0
        }
5706
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5707
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5708
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5709
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5710
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5711
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5712
104k
                  << " rowset_meta_size=" << v.size()
5713
104k
                  << " creation_time=" << rowset_meta->creation_time()
5714
104k
                  << " task_type=" << metrics_context.operation_type;
5715
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5716
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5717
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5718
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5719
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5720
20.0k
                                 "kv "
5721
20.0k
                                 "at next turn, instance_id="
5722
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5723
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5724
20.0k
                              << rowset_meta->end_version() << "]";
5725
20.0k
                    return 0;
5726
20.0k
                }
5727
50.0k
            }
5728
5729
30.9k
            num_prepare += 1;
5730
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5731
30.9k
                rowset_meta->end_version() != 1) {
5732
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5733
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5734
10.2k
                                 "instance_id="
5735
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5736
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5737
10.2k
                              << rowset_meta->end_version() << "]";
5738
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5739
10.2k
                    return 0;
5740
10.2k
                }
5741
30.2k
            }
5742
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5743
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5744
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5745
0
                return -1;
5746
0
            }
5747
53.1k
        } else {
5748
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5749
53.1k
            rowset_keys.emplace_back(k);
5750
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5751
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5752
53.1k
                ++num_empty_rowset;
5753
53.1k
            }
5754
53.1k
        }
5755
73.7k
        return 0;
5756
104k
    };
5757
5758
390
    auto loop_done = [&]() -> int {
5759
390
        std::vector<std::string> rowset_keys_to_delete;
5760
        // rowset_id -> rowset_meta
5761
        // store rowset id and meta for statistics rs size when delete
5762
390
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5763
390
        std::vector<std::string> mark_keys_to_process;
5764
390
        std::vector<std::string> abort_job_keys_to_process;
5765
390
        rowset_keys_to_delete.swap(rowset_keys);
5766
390
        rowsets_to_delete.swap(rowsets);
5767
390
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5768
390
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5769
390
        if (!mark_keys_to_process.empty()) {
5770
69
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5771
69
                    *worker_pool, std::move(mark_keys_to_process));
5772
69
        }
5773
390
        if (!abort_job_keys_to_process.empty()) {
5774
46
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5775
46
                                               &num_recycled);
5776
46
        }
5777
390
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5778
390
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5779
390
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5780
390
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5781
390
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5782
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5783
0
                return;
5784
0
            }
5785
390
            if (!versioned_delete_bitmap_key_groups.empty() &&
5786
390
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5787
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
5788
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5789
0
                             << instance_id_;
5790
0
                return;
5791
0
            }
5792
390
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5793
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5794
0
                return;
5795
0
            }
5796
390
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5797
390
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5778
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5779
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5780
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5781
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5782
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5783
0
                return;
5784
0
            }
5785
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5786
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5787
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
5788
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5789
0
                             << instance_id_;
5790
0
                return;
5791
0
            }
5792
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5793
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5794
0
                return;
5795
0
            }
5796
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5797
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5778
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5779
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5780
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5781
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5782
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5783
0
                return;
5784
0
            }
5785
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
5786
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5787
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
5788
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5789
0
                             << instance_id_;
5790
0
                return;
5791
0
            }
5792
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5793
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5794
0
                return;
5795
0
            }
5796
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5797
383
        });
5798
390
        return 0;
5799
390
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5758
7
    auto loop_done = [&]() -> int {
5759
7
        std::vector<std::string> rowset_keys_to_delete;
5760
        // rowset_id -> rowset_meta
5761
        // store rowset id and meta for statistics rs size when delete
5762
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5763
7
        std::vector<std::string> mark_keys_to_process;
5764
7
        std::vector<std::string> abort_job_keys_to_process;
5765
7
        rowset_keys_to_delete.swap(rowset_keys);
5766
7
        rowsets_to_delete.swap(rowsets);
5767
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5768
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5769
7
        if (!mark_keys_to_process.empty()) {
5770
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5771
4
                    *worker_pool, std::move(mark_keys_to_process));
5772
4
        }
5773
7
        if (!abort_job_keys_to_process.empty()) {
5774
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5775
2
                                               &num_recycled);
5776
2
        }
5777
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5778
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5779
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5780
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5781
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5782
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5783
7
                return;
5784
7
            }
5785
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5786
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5787
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
5788
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5789
7
                             << instance_id_;
5790
7
                return;
5791
7
            }
5792
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5793
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5794
7
                return;
5795
7
            }
5796
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5797
7
        });
5798
7
        return 0;
5799
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5758
383
    auto loop_done = [&]() -> int {
5759
383
        std::vector<std::string> rowset_keys_to_delete;
5760
        // rowset_id -> rowset_meta
5761
        // store rowset id and meta for statistics rs size when delete
5762
383
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5763
383
        std::vector<std::string> mark_keys_to_process;
5764
383
        std::vector<std::string> abort_job_keys_to_process;
5765
383
        rowset_keys_to_delete.swap(rowset_keys);
5766
383
        rowsets_to_delete.swap(rowsets);
5767
383
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5768
383
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5769
383
        if (!mark_keys_to_process.empty()) {
5770
65
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5771
65
                    *worker_pool, std::move(mark_keys_to_process));
5772
65
        }
5773
383
        if (!abort_job_keys_to_process.empty()) {
5774
44
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5775
44
                                               &num_recycled);
5776
44
        }
5777
383
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5778
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5779
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5780
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5781
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5782
383
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5783
383
                return;
5784
383
            }
5785
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
5786
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5787
383
                                                         versioned_delete_bitmap_key_groups) != 0) {
5788
383
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5789
383
                             << instance_id_;
5790
383
                return;
5791
383
            }
5792
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5793
383
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5794
383
                return;
5795
383
            }
5796
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5797
383
        });
5798
383
        return 0;
5799
383
    };
5800
5801
61
    if (config::enable_recycler_stats_metrics) {
5802
0
        scan_and_statistics_rowsets();
5803
0
    }
5804
    // recycle_func and loop_done for scan and recycle
5805
61
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5806
61
                               std::move(loop_done));
5807
5808
61
    worker_pool->stop();
5809
5810
61
    if (!async_recycled_rowset_keys.empty()) {
5811
9
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5812
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5813
0
            return -1;
5814
9
        } else {
5815
9
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5816
9
        }
5817
9
    }
5818
5819
    // Report final metrics after all concurrent tasks completed
5820
61
    segment_metrics_context_.report();
5821
61
    metrics_context.report();
5822
5823
61
    return ret;
5824
61
}
5825
5826
13
int InstanceRecycler::recycle_restore_jobs() {
5827
13
    const std::string task_name = "recycle_restore_jobs";
5828
13
    int64_t num_scanned = 0;
5829
13
    int64_t num_expired = 0;
5830
13
    int64_t num_recycled = 0;
5831
13
    int64_t num_aborted = 0;
5832
5833
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5834
5835
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5836
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5837
13
    std::string restore_job_key0;
5838
13
    std::string restore_job_key1;
5839
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5840
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5841
5842
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5843
5844
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5845
13
    register_recycle_task(task_name, start_time);
5846
5847
13
    DORIS_CLOUD_DEFER {
5848
13
        unregister_recycle_task(task_name);
5849
13
        int64_t cost =
5850
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5851
13
        metrics_context.finish_report();
5852
5853
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5854
13
                .tag("instance_id", instance_id_)
5855
13
                .tag("num_scanned", num_scanned)
5856
13
                .tag("num_expired", num_expired)
5857
13
                .tag("num_recycled", num_recycled)
5858
13
                .tag("num_aborted", num_aborted);
5859
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5847
13
    DORIS_CLOUD_DEFER {
5848
13
        unregister_recycle_task(task_name);
5849
13
        int64_t cost =
5850
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5851
13
        metrics_context.finish_report();
5852
5853
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5854
13
                .tag("instance_id", instance_id_)
5855
13
                .tag("num_scanned", num_scanned)
5856
13
                .tag("num_expired", num_expired)
5857
13
                .tag("num_recycled", num_recycled)
5858
13
                .tag("num_aborted", num_aborted);
5859
13
    };
5860
5861
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5862
5863
13
    std::vector<std::string_view> restore_job_keys;
5864
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5865
41
        ++num_scanned;
5866
41
        RestoreJobCloudPB restore_job_pb;
5867
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5868
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5869
0
            return -1;
5870
0
        }
5871
41
        int64_t expiration =
5872
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5873
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5874
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5875
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5876
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5877
0
                   << " state=" << restore_job_pb.state();
5878
41
        int64_t current_time = ::time(nullptr);
5879
41
        if (current_time < expiration) { // not expired
5880
0
            return 0;
5881
0
        }
5882
41
        ++num_expired;
5883
5884
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5885
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5886
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5887
5888
41
        std::unique_ptr<Transaction> txn;
5889
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5890
41
        if (err != TxnErrorCode::TXN_OK) {
5891
0
            LOG_WARNING("failed to recycle restore job")
5892
0
                    .tag("err", err)
5893
0
                    .tag("tablet id", tablet_id)
5894
0
                    .tag("instance_id", instance_id_)
5895
0
                    .tag("reason", "failed to create txn");
5896
0
            return -1;
5897
0
        }
5898
5899
41
        std::string val;
5900
41
        err = txn->get(k, &val);
5901
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5902
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5903
0
            return 0;
5904
0
        }
5905
41
        if (err != TxnErrorCode::TXN_OK) {
5906
0
            LOG_WARNING("failed to get kv");
5907
0
            return -1;
5908
0
        }
5909
41
        restore_job_pb.Clear();
5910
41
        if (!restore_job_pb.ParseFromString(val)) {
5911
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5912
0
            return -1;
5913
0
        }
5914
5915
        // PREPARED or COMMITTED, change state to DROPPED and return
5916
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5917
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5918
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5919
0
            restore_job_pb.set_need_recycle_data(true);
5920
0
            txn->put(k, restore_job_pb.SerializeAsString());
5921
0
            err = txn->commit();
5922
0
            if (err != TxnErrorCode::TXN_OK) {
5923
0
                LOG_WARNING("failed to commit txn: {}", err);
5924
0
                return -1;
5925
0
            }
5926
0
            num_aborted++;
5927
0
            return 0;
5928
0
        }
5929
5930
        // Change state to RECYCLING
5931
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5932
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5933
21
            txn->put(k, restore_job_pb.SerializeAsString());
5934
21
            err = txn->commit();
5935
21
            if (err != TxnErrorCode::TXN_OK) {
5936
0
                LOG_WARNING("failed to commit txn: {}", err);
5937
0
                return -1;
5938
0
            }
5939
21
            return 0;
5940
21
        }
5941
5942
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5943
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5944
5945
        // Recycle all data associated with the restore job.
5946
        // This includes rowsets, segments, and related resources.
5947
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5948
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5949
0
            LOG_WARNING("failed to recycle tablet")
5950
0
                    .tag("tablet_id", tablet_id)
5951
0
                    .tag("instance_id", instance_id_);
5952
0
            return -1;
5953
0
        }
5954
5955
        // delete all restore job rowset kv
5956
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5957
5958
20
        err = txn->commit();
5959
20
        if (err != TxnErrorCode::TXN_OK) {
5960
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5961
0
                    .tag("err", err)
5962
0
                    .tag("tablet id", tablet_id)
5963
0
                    .tag("instance_id", instance_id_)
5964
0
                    .tag("reason", "failed to commit txn");
5965
0
            return -1;
5966
0
        }
5967
5968
20
        metrics_context.total_recycled_num = ++num_recycled;
5969
20
        metrics_context.report();
5970
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5971
20
        restore_job_keys.push_back(k);
5972
5973
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5974
20
                  << " tablet_id=" << tablet_id;
5975
20
        return 0;
5976
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
5864
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5865
41
        ++num_scanned;
5866
41
        RestoreJobCloudPB restore_job_pb;
5867
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5868
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5869
0
            return -1;
5870
0
        }
5871
41
        int64_t expiration =
5872
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5873
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5874
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5875
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5876
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5877
0
                   << " state=" << restore_job_pb.state();
5878
41
        int64_t current_time = ::time(nullptr);
5879
41
        if (current_time < expiration) { // not expired
5880
0
            return 0;
5881
0
        }
5882
41
        ++num_expired;
5883
5884
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5885
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5886
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5887
5888
41
        std::unique_ptr<Transaction> txn;
5889
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5890
41
        if (err != TxnErrorCode::TXN_OK) {
5891
0
            LOG_WARNING("failed to recycle restore job")
5892
0
                    .tag("err", err)
5893
0
                    .tag("tablet id", tablet_id)
5894
0
                    .tag("instance_id", instance_id_)
5895
0
                    .tag("reason", "failed to create txn");
5896
0
            return -1;
5897
0
        }
5898
5899
41
        std::string val;
5900
41
        err = txn->get(k, &val);
5901
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5902
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5903
0
            return 0;
5904
0
        }
5905
41
        if (err != TxnErrorCode::TXN_OK) {
5906
0
            LOG_WARNING("failed to get kv");
5907
0
            return -1;
5908
0
        }
5909
41
        restore_job_pb.Clear();
5910
41
        if (!restore_job_pb.ParseFromString(val)) {
5911
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5912
0
            return -1;
5913
0
        }
5914
5915
        // PREPARED or COMMITTED, change state to DROPPED and return
5916
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5917
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5918
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5919
0
            restore_job_pb.set_need_recycle_data(true);
5920
0
            txn->put(k, restore_job_pb.SerializeAsString());
5921
0
            err = txn->commit();
5922
0
            if (err != TxnErrorCode::TXN_OK) {
5923
0
                LOG_WARNING("failed to commit txn: {}", err);
5924
0
                return -1;
5925
0
            }
5926
0
            num_aborted++;
5927
0
            return 0;
5928
0
        }
5929
5930
        // Change state to RECYCLING
5931
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5932
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5933
21
            txn->put(k, restore_job_pb.SerializeAsString());
5934
21
            err = txn->commit();
5935
21
            if (err != TxnErrorCode::TXN_OK) {
5936
0
                LOG_WARNING("failed to commit txn: {}", err);
5937
0
                return -1;
5938
0
            }
5939
21
            return 0;
5940
21
        }
5941
5942
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5943
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5944
5945
        // Recycle all data associated with the restore job.
5946
        // This includes rowsets, segments, and related resources.
5947
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5948
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5949
0
            LOG_WARNING("failed to recycle tablet")
5950
0
                    .tag("tablet_id", tablet_id)
5951
0
                    .tag("instance_id", instance_id_);
5952
0
            return -1;
5953
0
        }
5954
5955
        // delete all restore job rowset kv
5956
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5957
5958
20
        err = txn->commit();
5959
20
        if (err != TxnErrorCode::TXN_OK) {
5960
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5961
0
                    .tag("err", err)
5962
0
                    .tag("tablet id", tablet_id)
5963
0
                    .tag("instance_id", instance_id_)
5964
0
                    .tag("reason", "failed to commit txn");
5965
0
            return -1;
5966
0
        }
5967
5968
20
        metrics_context.total_recycled_num = ++num_recycled;
5969
20
        metrics_context.report();
5970
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5971
20
        restore_job_keys.push_back(k);
5972
5973
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5974
20
                  << " tablet_id=" << tablet_id;
5975
20
        return 0;
5976
20
    };
5977
5978
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5979
3
        if (restore_job_keys.empty()) return 0;
5980
1
        DORIS_CLOUD_DEFER {
5981
1
            restore_job_keys.clear();
5982
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5980
1
        DORIS_CLOUD_DEFER {
5981
1
            restore_job_keys.clear();
5982
1
        };
5983
5984
1
        std::unique_ptr<Transaction> txn;
5985
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5986
1
        if (err != TxnErrorCode::TXN_OK) {
5987
0
            LOG_WARNING("failed to recycle restore job")
5988
0
                    .tag("err", err)
5989
0
                    .tag("instance_id", instance_id_)
5990
0
                    .tag("reason", "failed to create txn");
5991
0
            return -1;
5992
0
        }
5993
20
        for (auto& k : restore_job_keys) {
5994
20
            txn->remove(k);
5995
20
        }
5996
1
        err = txn->commit();
5997
1
        if (err != TxnErrorCode::TXN_OK) {
5998
0
            LOG_WARNING("failed to recycle restore job")
5999
0
                    .tag("err", err)
6000
0
                    .tag("instance_id", instance_id_)
6001
0
                    .tag("reason", "failed to commit txn");
6002
0
            return -1;
6003
0
        }
6004
1
        return 0;
6005
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5978
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5979
3
        if (restore_job_keys.empty()) return 0;
5980
1
        DORIS_CLOUD_DEFER {
5981
1
            restore_job_keys.clear();
5982
1
        };
5983
5984
1
        std::unique_ptr<Transaction> txn;
5985
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5986
1
        if (err != TxnErrorCode::TXN_OK) {
5987
0
            LOG_WARNING("failed to recycle restore job")
5988
0
                    .tag("err", err)
5989
0
                    .tag("instance_id", instance_id_)
5990
0
                    .tag("reason", "failed to create txn");
5991
0
            return -1;
5992
0
        }
5993
20
        for (auto& k : restore_job_keys) {
5994
20
            txn->remove(k);
5995
20
        }
5996
1
        err = txn->commit();
5997
1
        if (err != TxnErrorCode::TXN_OK) {
5998
0
            LOG_WARNING("failed to recycle restore job")
5999
0
                    .tag("err", err)
6000
0
                    .tag("instance_id", instance_id_)
6001
0
                    .tag("reason", "failed to commit txn");
6002
0
            return -1;
6003
0
        }
6004
1
        return 0;
6005
1
    };
6006
6007
13
    if (config::enable_recycler_stats_metrics) {
6008
0
        scan_and_statistics_restore_jobs();
6009
0
    }
6010
6011
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6012
13
                            std::move(loop_done));
6013
13
}
6014
6015
11
int InstanceRecycler::recycle_versioned_rowsets() {
6016
11
    const std::string task_name = "recycle_rowsets";
6017
11
    int64_t num_scanned = 0;
6018
11
    int64_t num_expired = 0;
6019
11
    int64_t num_prepare = 0;
6020
11
    int64_t num_compacted = 0;
6021
11
    int64_t num_empty_rowset = 0;
6022
11
    size_t total_rowset_key_size = 0;
6023
11
    size_t total_rowset_value_size = 0;
6024
11
    size_t expired_rowset_size = 0;
6025
11
    std::atomic_long num_recycled = 0;
6026
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6027
6028
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6029
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6030
11
    std::string recyc_rs_key0;
6031
11
    std::string recyc_rs_key1;
6032
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6033
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6034
6035
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6036
6037
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6038
11
    register_recycle_task(task_name, start_time);
6039
6040
11
    DORIS_CLOUD_DEFER {
6041
11
        unregister_recycle_task(task_name);
6042
11
        int64_t cost =
6043
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6044
11
        metrics_context.finish_report();
6045
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6046
11
                .tag("instance_id", instance_id_)
6047
11
                .tag("num_scanned", num_scanned)
6048
11
                .tag("num_expired", num_expired)
6049
11
                .tag("num_recycled", num_recycled)
6050
11
                .tag("num_recycled.prepare", num_prepare)
6051
11
                .tag("num_recycled.compacted", num_compacted)
6052
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6053
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6054
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6055
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6056
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6040
11
    DORIS_CLOUD_DEFER {
6041
11
        unregister_recycle_task(task_name);
6042
11
        int64_t cost =
6043
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6044
11
        metrics_context.finish_report();
6045
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6046
11
                .tag("instance_id", instance_id_)
6047
11
                .tag("num_scanned", num_scanned)
6048
11
                .tag("num_expired", num_expired)
6049
11
                .tag("num_recycled", num_recycled)
6050
11
                .tag("num_recycled.prepare", num_prepare)
6051
11
                .tag("num_recycled.compacted", num_compacted)
6052
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6053
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6054
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6055
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6056
11
    };
6057
6058
11
    std::vector<std::string> orphan_rowset_keys;
6059
6060
    // Store keys of rowset recycled by background workers
6061
11
    std::mutex async_recycled_rowset_keys_mutex;
6062
11
    std::vector<std::string> async_recycled_rowset_keys;
6063
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6064
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6065
11
    worker_pool->start();
6066
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6067
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6068
        // Try to delete rowset data in background thread
6069
400
        int ret = worker_pool->submit_with_timeout(
6070
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6071
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6072
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6073
400
                        return;
6074
400
                    }
6075
                    // The async recycled rowsets are staled format or has not been used,
6076
                    // so we don't need to check the rowset ref count key.
6077
0
                    std::vector<std::string> keys;
6078
0
                    {
6079
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6080
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6081
0
                        if (async_recycled_rowset_keys.size() > 100) {
6082
0
                            keys.swap(async_recycled_rowset_keys);
6083
0
                        }
6084
0
                    }
6085
0
                    if (keys.empty()) return;
6086
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6087
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6088
0
                                     << instance_id_;
6089
0
                    } else {
6090
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6091
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6092
0
                                           num_recycled, start_time);
6093
0
                    }
6094
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
6070
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6071
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6072
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6073
400
                        return;
6074
400
                    }
6075
                    // The async recycled rowsets are staled format or has not been used,
6076
                    // so we don't need to check the rowset ref count key.
6077
0
                    std::vector<std::string> keys;
6078
0
                    {
6079
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6080
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6081
0
                        if (async_recycled_rowset_keys.size() > 100) {
6082
0
                            keys.swap(async_recycled_rowset_keys);
6083
0
                        }
6084
0
                    }
6085
0
                    if (keys.empty()) return;
6086
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6087
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6088
0
                                     << instance_id_;
6089
0
                    } else {
6090
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6091
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6092
0
                                           num_recycled, start_time);
6093
0
                    }
6094
0
                },
6095
400
                0);
6096
400
        if (ret == 0) return 0;
6097
        // Submit task failed, delete rowset data in current thread
6098
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6099
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6100
0
            return -1;
6101
0
        }
6102
0
        orphan_rowset_keys.push_back(std::move(key));
6103
0
        return 0;
6104
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
6067
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6068
        // Try to delete rowset data in background thread
6069
400
        int ret = worker_pool->submit_with_timeout(
6070
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6071
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6072
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6073
400
                        return;
6074
400
                    }
6075
                    // The async recycled rowsets are staled format or has not been used,
6076
                    // so we don't need to check the rowset ref count key.
6077
400
                    std::vector<std::string> keys;
6078
400
                    {
6079
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6080
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6081
400
                        if (async_recycled_rowset_keys.size() > 100) {
6082
400
                            keys.swap(async_recycled_rowset_keys);
6083
400
                        }
6084
400
                    }
6085
400
                    if (keys.empty()) return;
6086
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6087
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6088
400
                                     << instance_id_;
6089
400
                    } else {
6090
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6091
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6092
400
                                           num_recycled, start_time);
6093
400
                    }
6094
400
                },
6095
400
                0);
6096
400
        if (ret == 0) return 0;
6097
        // Submit task failed, delete rowset data in current thread
6098
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6099
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6100
0
            return -1;
6101
0
        }
6102
0
        orphan_rowset_keys.push_back(std::move(key));
6103
0
        return 0;
6104
0
    };
6105
6106
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6107
6108
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6109
2.01k
        ++num_scanned;
6110
2.01k
        total_rowset_key_size += k.size();
6111
2.01k
        total_rowset_value_size += v.size();
6112
2.01k
        RecycleRowsetPB rowset;
6113
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6114
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6115
0
            return -1;
6116
0
        }
6117
6118
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6119
6120
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6121
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6122
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6123
2.01k
        int64_t current_time = ::time(nullptr);
6124
2.01k
        if (current_time < final_expiration) { // not expired
6125
0
            return 0;
6126
0
        }
6127
2.01k
        ++num_expired;
6128
2.01k
        expired_rowset_size += v.size();
6129
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6130
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6131
                // in old version, keep this key-value pair and it needs to be checked manually
6132
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6133
0
                return -1;
6134
0
            }
6135
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6136
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6137
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6138
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6139
0
                orphan_rowset_keys.emplace_back(k);
6140
0
                return -1;
6141
0
            }
6142
            // decode rowset_id
6143
0
            auto k1 = k;
6144
0
            k1.remove_prefix(1);
6145
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6146
0
            decode_key(&k1, &out);
6147
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6148
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6149
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6150
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6151
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6152
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6153
0
                return -1;
6154
0
            }
6155
0
            return 0;
6156
0
        }
6157
        // TODO(plat1ko): check rowset not referenced
6158
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6159
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6160
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6161
0
                LOG_INFO("recycle rowset that has empty resource id");
6162
0
            } else {
6163
                // other situations, keep this key-value pair and it needs to be checked manually
6164
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6165
0
                return -1;
6166
0
            }
6167
0
        }
6168
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6169
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6170
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6171
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6172
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6173
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6174
2.01k
                  << " rowset_meta_size=" << v.size()
6175
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6176
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6177
            // unable to calculate file path, can only be deleted by rowset id prefix
6178
400
            num_prepare += 1;
6179
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6180
400
                                             rowset_meta->tablet_id(),
6181
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6182
0
                return -1;
6183
0
            }
6184
1.61k
        } else {
6185
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6186
1.61k
            worker_pool->submit(
6187
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6188
                        // The load & compact rowset keys are recycled during recycling operation logs.
6189
1.61k
                        RowsetDeleteTask task;
6190
1.61k
                        task.rowset_meta = rowset_meta;
6191
1.61k
                        task.recycle_rowset_key = k;
6192
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6193
1.59k
                            return;
6194
1.59k
                        }
6195
14
                        num_compacted += is_compacted;
6196
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6197
14
                        if (rowset_meta.num_segments() == 0) {
6198
0
                            ++num_empty_rowset;
6199
0
                        }
6200
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
6187
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6188
                        // The load & compact rowset keys are recycled during recycling operation logs.
6189
1.61k
                        RowsetDeleteTask task;
6190
1.61k
                        task.rowset_meta = rowset_meta;
6191
1.61k
                        task.recycle_rowset_key = k;
6192
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6193
1.59k
                            return;
6194
1.59k
                        }
6195
14
                        num_compacted += is_compacted;
6196
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6197
14
                        if (rowset_meta.num_segments() == 0) {
6198
0
                            ++num_empty_rowset;
6199
0
                        }
6200
14
                    });
6201
1.61k
        }
6202
2.01k
        return 0;
6203
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
6108
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6109
2.01k
        ++num_scanned;
6110
2.01k
        total_rowset_key_size += k.size();
6111
2.01k
        total_rowset_value_size += v.size();
6112
2.01k
        RecycleRowsetPB rowset;
6113
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6114
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6115
0
            return -1;
6116
0
        }
6117
6118
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6119
6120
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6121
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6122
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6123
2.01k
        int64_t current_time = ::time(nullptr);
6124
2.01k
        if (current_time < final_expiration) { // not expired
6125
0
            return 0;
6126
0
        }
6127
2.01k
        ++num_expired;
6128
2.01k
        expired_rowset_size += v.size();
6129
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6130
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6131
                // in old version, keep this key-value pair and it needs to be checked manually
6132
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6133
0
                return -1;
6134
0
            }
6135
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6136
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6137
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6138
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6139
0
                orphan_rowset_keys.emplace_back(k);
6140
0
                return -1;
6141
0
            }
6142
            // decode rowset_id
6143
0
            auto k1 = k;
6144
0
            k1.remove_prefix(1);
6145
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6146
0
            decode_key(&k1, &out);
6147
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6148
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6149
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6150
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6151
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6152
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6153
0
                return -1;
6154
0
            }
6155
0
            return 0;
6156
0
        }
6157
        // TODO(plat1ko): check rowset not referenced
6158
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6159
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6160
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6161
0
                LOG_INFO("recycle rowset that has empty resource id");
6162
0
            } else {
6163
                // other situations, keep this key-value pair and it needs to be checked manually
6164
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6165
0
                return -1;
6166
0
            }
6167
0
        }
6168
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6169
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6170
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6171
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6172
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6173
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6174
2.01k
                  << " rowset_meta_size=" << v.size()
6175
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6176
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6177
            // unable to calculate file path, can only be deleted by rowset id prefix
6178
400
            num_prepare += 1;
6179
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6180
400
                                             rowset_meta->tablet_id(),
6181
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6182
0
                return -1;
6183
0
            }
6184
1.61k
        } else {
6185
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6186
1.61k
            worker_pool->submit(
6187
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6188
                        // The load & compact rowset keys are recycled during recycling operation logs.
6189
1.61k
                        RowsetDeleteTask task;
6190
1.61k
                        task.rowset_meta = rowset_meta;
6191
1.61k
                        task.recycle_rowset_key = k;
6192
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6193
1.61k
                            return;
6194
1.61k
                        }
6195
1.61k
                        num_compacted += is_compacted;
6196
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6197
1.61k
                        if (rowset_meta.num_segments() == 0) {
6198
1.61k
                            ++num_empty_rowset;
6199
1.61k
                        }
6200
1.61k
                    });
6201
1.61k
        }
6202
2.01k
        return 0;
6203
2.01k
    };
6204
6205
11
    if (config::enable_recycler_stats_metrics) {
6206
0
        scan_and_statistics_rowsets();
6207
0
    }
6208
6209
11
    auto loop_done = [&]() -> int {
6210
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6211
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6212
0
        }
6213
6
        orphan_rowset_keys.clear();
6214
6
        return 0;
6215
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6209
6
    auto loop_done = [&]() -> int {
6210
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6211
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6212
0
        }
6213
6
        orphan_rowset_keys.clear();
6214
6
        return 0;
6215
6
    };
6216
6217
    // recycle_func and loop_done for scan and recycle
6218
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6219
11
                               std::move(loop_done));
6220
6221
11
    worker_pool->stop();
6222
6223
11
    if (!async_recycled_rowset_keys.empty()) {
6224
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6225
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6226
0
            return -1;
6227
0
        } else {
6228
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6229
0
        }
6230
0
    }
6231
6232
    // Report final metrics after all concurrent tasks completed
6233
11
    segment_metrics_context_.report();
6234
11
    metrics_context.report();
6235
6236
11
    return ret;
6237
11
}
6238
6239
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6240
1.61k
    constexpr int MAX_RETRY = 10;
6241
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6242
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6243
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6244
1.61k
    std::string_view reference_instance_id = instance_id_;
6245
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6246
8
        reference_instance_id = rowset_meta.reference_instance_id();
6247
8
    }
6248
6249
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6250
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6251
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6252
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6253
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6254
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6255
1.61k
        std::unique_ptr<Transaction> txn;
6256
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6257
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6258
0
            LOG_WARNING("failed to create txn").tag("err", err);
6259
0
            return -1;
6260
0
        }
6261
6262
1.61k
        std::string rowset_ref_count_key =
6263
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6264
1.61k
        int64_t ref_count = 0;
6265
1.61k
        {
6266
1.61k
            std::string value;
6267
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6268
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6269
                // This is the old version rowset, we could recycle it directly.
6270
1.60k
                ref_count = 1;
6271
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6272
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6273
0
                return -1;
6274
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6275
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6276
0
                return -1;
6277
0
            }
6278
1.61k
        }
6279
6280
1.61k
        if (ref_count == 1) {
6281
            // It would not be added since it is recycling.
6282
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6283
1.59k
                LOG_WARNING("failed to delete rowset data");
6284
1.59k
                return -1;
6285
1.59k
            }
6286
6287
            // Reset the transaction to avoid timeout.
6288
11
            err = txn_kv_->create_txn(&txn);
6289
11
            if (err != TxnErrorCode::TXN_OK) {
6290
0
                LOG_WARNING("failed to create txn").tag("err", err);
6291
0
                return -1;
6292
0
            }
6293
11
            txn->remove(rowset_ref_count_key);
6294
11
            LOG_INFO("delete rowset data ref count key")
6295
11
                    .tag("txn_id", rowset_meta.txn_id())
6296
11
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6297
6298
11
            std::string dbm_start_key =
6299
11
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6300
11
            std::string dbm_end_key = meta_delete_bitmap_key(
6301
11
                    {reference_instance_id, tablet_id, rowset_id,
6302
11
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6303
11
            txn->remove(dbm_start_key, dbm_end_key);
6304
11
            LOG_INFO("remove delete bitmap kv")
6305
11
                    .tag("begin", hex(dbm_start_key))
6306
11
                    .tag("end", hex(dbm_end_key));
6307
6308
11
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6309
11
                    {reference_instance_id, tablet_id, rowset_id});
6310
11
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6311
11
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6312
11
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6313
11
            LOG_INFO("remove versioned delete bitmap kv")
6314
11
                    .tag("begin", hex(versioned_dbm_start_key))
6315
11
                    .tag("end", hex(versioned_dbm_end_key));
6316
11
        } else {
6317
            // Decrease the rowset ref count.
6318
            //
6319
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6320
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6321
3
            txn->atomic_add(rowset_ref_count_key, -1);
6322
3
            LOG_INFO("decrease rowset data ref count")
6323
3
                    .tag("txn_id", rowset_meta.txn_id())
6324
3
                    .tag("ref_count", ref_count - 1)
6325
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6326
3
        }
6327
6328
14
        if (!task.versioned_rowset_key.empty()) {
6329
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6330
0
                                                          task.versionstamp);
6331
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6332
0
        }
6333
6334
14
        if (!task.non_versioned_rowset_key.empty()) {
6335
0
            txn->remove(task.non_versioned_rowset_key);
6336
0
            LOG_INFO("remove non versioned rowset key")
6337
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6338
0
        }
6339
6340
        // empty when recycle ref rowsets for deleted instance
6341
14
        if (!task.recycle_rowset_key.empty()) {
6342
13
            txn->remove(task.recycle_rowset_key);
6343
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6344
13
        }
6345
6346
14
        err = txn->commit();
6347
14
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6348
            // The rowset ref count key has been changed, we need to retry.
6349
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6350
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6351
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6352
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6353
0
            continue;
6354
14
        } else if (err != TxnErrorCode::TXN_OK) {
6355
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6356
0
            return -1;
6357
0
        }
6358
14
        LOG_INFO("recycle rowset meta and data success");
6359
14
        return 0;
6360
14
    }
6361
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6362
0
            .tag("tablet_id", tablet_id)
6363
0
            .tag("rowset_id", rowset_id)
6364
0
            .tag("retry", MAX_RETRY);
6365
0
    return -1;
6366
1.61k
}
6367
6368
37
int InstanceRecycler::recycle_tmp_rowsets() {
6369
37
    const std::string task_name = "recycle_tmp_rowsets";
6370
37
    int64_t num_scanned = 0;
6371
37
    int64_t num_expired = 0;
6372
37
    std::atomic_long num_recycled = 0;
6373
37
    size_t expired_rowset_size = 0;
6374
37
    size_t total_rowset_key_size = 0;
6375
37
    size_t total_rowset_value_size = 0;
6376
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6377
6378
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6379
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6380
37
    std::string tmp_rs_key0;
6381
37
    std::string tmp_rs_key1;
6382
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6383
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6384
6385
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6386
6387
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6388
37
    register_recycle_task(task_name, start_time);
6389
6390
37
    DORIS_CLOUD_DEFER {
6391
37
        unregister_recycle_task(task_name);
6392
37
        int64_t cost =
6393
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6394
37
        metrics_context.finish_report();
6395
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6396
37
                .tag("instance_id", instance_id_)
6397
37
                .tag("num_scanned", num_scanned)
6398
37
                .tag("num_expired", num_expired)
6399
37
                .tag("num_recycled", num_recycled)
6400
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6401
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6402
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6403
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6390
12
    DORIS_CLOUD_DEFER {
6391
12
        unregister_recycle_task(task_name);
6392
12
        int64_t cost =
6393
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6394
12
        metrics_context.finish_report();
6395
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6396
12
                .tag("instance_id", instance_id_)
6397
12
                .tag("num_scanned", num_scanned)
6398
12
                .tag("num_expired", num_expired)
6399
12
                .tag("num_recycled", num_recycled)
6400
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6401
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6402
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6403
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6390
25
    DORIS_CLOUD_DEFER {
6391
25
        unregister_recycle_task(task_name);
6392
25
        int64_t cost =
6393
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6394
25
        metrics_context.finish_report();
6395
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6396
25
                .tag("instance_id", instance_id_)
6397
25
                .tag("num_scanned", num_scanned)
6398
25
                .tag("num_expired", num_expired)
6399
25
                .tag("num_recycled", num_recycled)
6400
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6401
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6402
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6403
25
    };
6404
6405
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6406
37
    std::vector<std::string> tmp_rowset_keys;
6407
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6408
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6409
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6410
6411
    // rowset_id -> rowset_meta
6412
    // store tmp_rowset id and meta for statistics rs size when delete
6413
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6414
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6415
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6416
37
    worker_pool->start();
6417
6418
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6419
6420
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6421
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6422
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6423
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6424
53.2k
                                    std::string_view k, std::string_view v) -> int {
6425
53.2k
        ++num_scanned;
6426
53.2k
        total_rowset_key_size += k.size();
6427
53.2k
        total_rowset_value_size += v.size();
6428
53.2k
        doris::RowsetMetaCloudPB rowset;
6429
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6430
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6431
0
            return -1;
6432
0
        }
6433
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6434
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6435
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6436
0
                   << " txn_expiration=" << rowset.txn_expiration()
6437
0
                   << " rowset_creation_time=" << rowset.creation_time();
6438
53.2k
        int64_t current_time = ::time(nullptr);
6439
53.2k
        if (current_time < expiration) { // not expired
6440
0
            return 0;
6441
0
        }
6442
53.2k
        ++num_expired;
6443
53.2k
        expired_rowset_size += v.size();
6444
53.2k
        if (!rowset.has_resource_id()) {
6445
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6446
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6447
0
                return -1;
6448
0
            }
6449
            // might be a delete pred rowset
6450
0
            tmp_rowset_keys.emplace_back(k);
6451
0
            return 0;
6452
0
        }
6453
6454
        // TODO(plat1ko): check rowset not referenced
6455
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6456
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6457
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6458
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6459
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6460
53.2k
                  << " num_expired=" << num_expired
6461
53.2k
                  << " task_type=" << metrics_context.operation_type;
6462
6463
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6464
16
            if (need_mark_rowset_as_recycled(rowset)) {
6465
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6466
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6467
9
                             "at next turn, instance_id="
6468
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6469
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6470
9
                return 0;
6471
9
            }
6472
16
        }
6473
6474
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6475
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6476
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6477
261
                             "instance_id="
6478
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6479
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6480
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6481
261
                return 0;
6482
261
            }
6483
265
        }
6484
6485
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6486
        // Remove the rowset ref count key directly since it has not been used.
6487
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6488
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6489
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6490
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6491
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6492
6493
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6494
53.0k
        return 0;
6495
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6424
16
                                    std::string_view k, std::string_view v) -> int {
6425
16
        ++num_scanned;
6426
16
        total_rowset_key_size += k.size();
6427
16
        total_rowset_value_size += v.size();
6428
16
        doris::RowsetMetaCloudPB rowset;
6429
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6430
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6431
0
            return -1;
6432
0
        }
6433
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6434
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6435
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6436
0
                   << " txn_expiration=" << rowset.txn_expiration()
6437
0
                   << " rowset_creation_time=" << rowset.creation_time();
6438
16
        int64_t current_time = ::time(nullptr);
6439
16
        if (current_time < expiration) { // not expired
6440
0
            return 0;
6441
0
        }
6442
16
        ++num_expired;
6443
16
        expired_rowset_size += v.size();
6444
16
        if (!rowset.has_resource_id()) {
6445
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6446
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6447
0
                return -1;
6448
0
            }
6449
            // might be a delete pred rowset
6450
0
            tmp_rowset_keys.emplace_back(k);
6451
0
            return 0;
6452
0
        }
6453
6454
        // TODO(plat1ko): check rowset not referenced
6455
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6456
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6457
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6458
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6459
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6460
16
                  << " num_expired=" << num_expired
6461
16
                  << " task_type=" << metrics_context.operation_type;
6462
6463
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6464
16
            if (need_mark_rowset_as_recycled(rowset)) {
6465
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6466
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6467
9
                             "at next turn, instance_id="
6468
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6469
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6470
9
                return 0;
6471
9
            }
6472
16
        }
6473
6474
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6475
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6476
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6477
3
                             "instance_id="
6478
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6479
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6480
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6481
3
                return 0;
6482
3
            }
6483
7
        }
6484
6485
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6486
        // Remove the rowset ref count key directly since it has not been used.
6487
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6488
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6489
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6490
4
                  << "key=" << hex(rowset_ref_count_key);
6491
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6492
6493
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6494
4
        return 0;
6495
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6424
53.2k
                                    std::string_view k, std::string_view v) -> int {
6425
53.2k
        ++num_scanned;
6426
53.2k
        total_rowset_key_size += k.size();
6427
53.2k
        total_rowset_value_size += v.size();
6428
53.2k
        doris::RowsetMetaCloudPB rowset;
6429
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6430
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6431
0
            return -1;
6432
0
        }
6433
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6434
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6435
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6436
0
                   << " txn_expiration=" << rowset.txn_expiration()
6437
0
                   << " rowset_creation_time=" << rowset.creation_time();
6438
53.2k
        int64_t current_time = ::time(nullptr);
6439
53.2k
        if (current_time < expiration) { // not expired
6440
0
            return 0;
6441
0
        }
6442
53.2k
        ++num_expired;
6443
53.2k
        expired_rowset_size += v.size();
6444
53.2k
        if (!rowset.has_resource_id()) {
6445
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6446
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6447
0
                return -1;
6448
0
            }
6449
            // might be a delete pred rowset
6450
0
            tmp_rowset_keys.emplace_back(k);
6451
0
            return 0;
6452
0
        }
6453
6454
        // TODO(plat1ko): check rowset not referenced
6455
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6456
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6457
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6458
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6459
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6460
53.2k
                  << " num_expired=" << num_expired
6461
53.2k
                  << " task_type=" << metrics_context.operation_type;
6462
6463
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6464
0
            if (need_mark_rowset_as_recycled(rowset)) {
6465
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6466
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6467
0
                             "at next turn, instance_id="
6468
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6469
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6470
0
                return 0;
6471
0
            }
6472
0
        }
6473
6474
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6475
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6476
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6477
258
                             "instance_id="
6478
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6479
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6480
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6481
258
                return 0;
6482
258
            }
6483
258
        }
6484
6485
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6486
        // Remove the rowset ref count key directly since it has not been used.
6487
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6488
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6489
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6490
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6491
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6492
6493
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6494
53.0k
        return 0;
6495
53.2k
    };
6496
6497
37
    auto loop_done = [&]() -> int {
6498
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6499
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6500
24
        std::vector<std::string> mark_keys_to_process;
6501
24
        std::vector<std::string> abort_keys_to_process;
6502
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6503
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6504
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6505
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6506
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6507
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6508
24
        if (!mark_keys_to_process.empty()) {
6509
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6510
7
                    *worker_pool, std::move(mark_keys_to_process));
6511
7
        }
6512
24
        if (!abort_keys_to_process.empty()) {
6513
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6514
5
                                           &num_recycled, &metrics_context);
6515
5
        }
6516
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6517
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6518
24
                             tmp_rowset_ref_count_keys_to_delete =
6519
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6520
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6521
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6522
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6523
24
                                   metrics_context) != 0) {
6524
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6525
2
                return;
6526
2
            }
6527
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6528
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6529
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6530
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6531
0
                                 << rs.ShortDebugString();
6532
0
                    return;
6533
0
                }
6534
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6535
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6536
0
                                 << rs.ShortDebugString();
6537
0
                    return;
6538
0
                }
6539
51.0k
            }
6540
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6541
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6542
0
                return;
6543
0
            }
6544
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6545
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6546
0
                return;
6547
0
            }
6548
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6549
22
            return;
6550
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6521
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6522
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6523
12
                                   metrics_context) != 0) {
6524
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6525
0
                return;
6526
0
            }
6527
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6528
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6529
4
                                                       rs.rowset_id_v2()) != 0) {
6530
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6531
0
                                 << rs.ShortDebugString();
6532
0
                    return;
6533
0
                }
6534
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6535
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6536
0
                                 << rs.ShortDebugString();
6537
0
                    return;
6538
0
                }
6539
4
            }
6540
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6541
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6542
0
                return;
6543
0
            }
6544
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6545
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6546
0
                return;
6547
0
            }
6548
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6549
12
            return;
6550
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6521
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6522
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6523
12
                                   metrics_context) != 0) {
6524
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6525
2
                return;
6526
2
            }
6527
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6528
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6529
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6530
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6531
0
                                 << rs.ShortDebugString();
6532
0
                    return;
6533
0
                }
6534
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6535
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6536
0
                                 << rs.ShortDebugString();
6537
0
                    return;
6538
0
                }
6539
51.0k
            }
6540
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6541
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6542
0
                return;
6543
0
            }
6544
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6545
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6546
0
                return;
6547
0
            }
6548
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6549
10
            return;
6550
10
        });
6551
24
        return 0;
6552
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6497
12
    auto loop_done = [&]() -> int {
6498
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6499
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6500
12
        std::vector<std::string> mark_keys_to_process;
6501
12
        std::vector<std::string> abort_keys_to_process;
6502
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6503
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6504
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6505
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6506
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6507
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6508
12
        if (!mark_keys_to_process.empty()) {
6509
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6510
7
                    *worker_pool, std::move(mark_keys_to_process));
6511
7
        }
6512
12
        if (!abort_keys_to_process.empty()) {
6513
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6514
3
                                           &num_recycled, &metrics_context);
6515
3
        }
6516
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6517
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6518
12
                             tmp_rowset_ref_count_keys_to_delete =
6519
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6520
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6521
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6522
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6523
12
                                   metrics_context) != 0) {
6524
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6525
12
                return;
6526
12
            }
6527
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6528
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6529
12
                                                       rs.rowset_id_v2()) != 0) {
6530
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6531
12
                                 << rs.ShortDebugString();
6532
12
                    return;
6533
12
                }
6534
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6535
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6536
12
                                 << rs.ShortDebugString();
6537
12
                    return;
6538
12
                }
6539
12
            }
6540
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6541
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6542
12
                return;
6543
12
            }
6544
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6545
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6546
12
                return;
6547
12
            }
6548
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6549
12
            return;
6550
12
        });
6551
12
        return 0;
6552
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6497
12
    auto loop_done = [&]() -> int {
6498
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6499
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6500
12
        std::vector<std::string> mark_keys_to_process;
6501
12
        std::vector<std::string> abort_keys_to_process;
6502
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6503
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6504
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6505
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6506
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6507
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6508
12
        if (!mark_keys_to_process.empty()) {
6509
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6510
0
                    *worker_pool, std::move(mark_keys_to_process));
6511
0
        }
6512
12
        if (!abort_keys_to_process.empty()) {
6513
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6514
2
                                           &num_recycled, &metrics_context);
6515
2
        }
6516
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6517
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6518
12
                             tmp_rowset_ref_count_keys_to_delete =
6519
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6520
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6521
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6522
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6523
12
                                   metrics_context) != 0) {
6524
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6525
12
                return;
6526
12
            }
6527
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6528
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6529
12
                                                       rs.rowset_id_v2()) != 0) {
6530
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6531
12
                                 << rs.ShortDebugString();
6532
12
                    return;
6533
12
                }
6534
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6535
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6536
12
                                 << rs.ShortDebugString();
6537
12
                    return;
6538
12
                }
6539
12
            }
6540
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6541
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6542
12
                return;
6543
12
            }
6544
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6545
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6546
12
                return;
6547
12
            }
6548
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6549
12
            return;
6550
12
        });
6551
12
        return 0;
6552
12
    };
6553
6554
37
    if (config::enable_recycler_stats_metrics) {
6555
0
        scan_and_statistics_tmp_rowsets();
6556
0
    }
6557
    // recycle_func and loop_done for scan and recycle
6558
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6559
37
                               std::move(loop_done));
6560
6561
37
    worker_pool->stop();
6562
6563
    // Report final metrics after all concurrent tasks completed
6564
37
    segment_metrics_context_.report();
6565
37
    metrics_context.report();
6566
6567
37
    return ret;
6568
37
}
6569
6570
int InstanceRecycler::scan_and_recycle(
6571
        std::string begin, std::string_view end,
6572
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6573
316
        std::function<int()> loop_done) {
6574
316
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6575
316
    int ret = 0;
6576
316
    int64_t cnt = 0;
6577
316
    int get_range_retried = 0;
6578
316
    std::string err;
6579
316
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6580
316
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6581
316
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6582
316
                  << " ret=" << ret << " err=" << err;
6583
316
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6579
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6580
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6581
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6582
31
                  << " ret=" << ret << " err=" << err;
6583
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6579
285
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6580
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6581
285
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6582
285
                  << " ret=" << ret << " err=" << err;
6583
285
    };
6584
6585
316
    std::unique_ptr<RangeGetIterator> it;
6586
840
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6587
669
        if (get_range_retried > 1000) {
6588
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6589
0
            ret = -3;
6590
0
            return ret;
6591
0
        }
6592
669
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6593
669
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6594
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6595
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6596
0
                         << " get_range_retried=" << get_range_retried;
6597
0
            ++get_range_retried;
6598
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6599
0
            continue; // try again
6600
0
        }
6601
669
        if (!it->has_next()) {
6602
145
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6603
145
            break; // scan finished
6604
145
        }
6605
238k
        while (it->has_next()) {
6606
237k
            ++cnt;
6607
            // recycle corresponding resources
6608
237k
            auto [k, v] = it->next();
6609
237k
            if (!it->has_next()) {
6610
524
                begin = k;
6611
524
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6612
524
            }
6613
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6614
237k
            if (recycle_func(k, v) != 0) {
6615
4.00k
                err = "recycle_func error";
6616
4.00k
                ret = -1;
6617
4.00k
            }
6618
237k
        }
6619
524
        begin.push_back('\x00'); // Update to next smallest key for iteration
6620
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6621
524
        if (loop_done && loop_done() != 0) {
6622
9
            err = "loop_done error";
6623
9
            ret = -1;
6624
9
        }
6625
524
    }
6626
316
    return ret;
6627
316
}
6628
6629
19
int InstanceRecycler::abort_timeout_txn() {
6630
19
    const std::string task_name = "abort_timeout_txn";
6631
19
    int64_t num_scanned = 0;
6632
19
    int64_t num_timeout = 0;
6633
19
    int64_t num_abort = 0;
6634
19
    int64_t num_advance = 0;
6635
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6636
6637
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6638
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6639
19
    std::string begin_txn_running_key;
6640
19
    std::string end_txn_running_key;
6641
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6642
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6643
6644
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6645
6646
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6647
19
    register_recycle_task(task_name, start_time);
6648
6649
19
    DORIS_CLOUD_DEFER {
6650
19
        unregister_recycle_task(task_name);
6651
19
        int64_t cost =
6652
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6653
19
        metrics_context.finish_report();
6654
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6655
19
                .tag("instance_id", instance_id_)
6656
19
                .tag("num_scanned", num_scanned)
6657
19
                .tag("num_timeout", num_timeout)
6658
19
                .tag("num_abort", num_abort)
6659
19
                .tag("num_advance", num_advance);
6660
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6649
3
    DORIS_CLOUD_DEFER {
6650
3
        unregister_recycle_task(task_name);
6651
3
        int64_t cost =
6652
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6653
3
        metrics_context.finish_report();
6654
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6655
3
                .tag("instance_id", instance_id_)
6656
3
                .tag("num_scanned", num_scanned)
6657
3
                .tag("num_timeout", num_timeout)
6658
3
                .tag("num_abort", num_abort)
6659
3
                .tag("num_advance", num_advance);
6660
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6649
16
    DORIS_CLOUD_DEFER {
6650
16
        unregister_recycle_task(task_name);
6651
16
        int64_t cost =
6652
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6653
16
        metrics_context.finish_report();
6654
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6655
16
                .tag("instance_id", instance_id_)
6656
16
                .tag("num_scanned", num_scanned)
6657
16
                .tag("num_timeout", num_timeout)
6658
16
                .tag("num_abort", num_abort)
6659
16
                .tag("num_advance", num_advance);
6660
16
    };
6661
6662
19
    int64_t current_time =
6663
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6664
6665
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6666
19
                                  &current_time, &metrics_context,
6667
19
                                  this](std::string_view k, std::string_view v) -> int {
6668
9
        ++num_scanned;
6669
6670
9
        std::unique_ptr<Transaction> txn;
6671
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6672
9
        if (err != TxnErrorCode::TXN_OK) {
6673
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6674
0
            return -1;
6675
0
        }
6676
9
        std::string_view k1 = k;
6677
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6678
9
        k1.remove_prefix(1); // Remove key space
6679
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6680
9
        if (decode_key(&k1, &out) != 0) {
6681
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6685
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6686
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6687
        // Update txn_info
6688
9
        std::string txn_inf_key, txn_inf_val;
6689
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6690
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6691
9
        if (err != TxnErrorCode::TXN_OK) {
6692
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6693
0
            return -1;
6694
0
        }
6695
9
        TxnInfoPB txn_info;
6696
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6697
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
6701
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6702
3
            txn.reset();
6703
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6704
3
            std::shared_ptr<TxnLazyCommitTask> task =
6705
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6706
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6707
3
            if (ret.first != MetaServiceCode::OK) {
6708
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6709
0
                             << "msg=" << ret.second;
6710
0
                return -1;
6711
0
            }
6712
3
            ++num_advance;
6713
3
            return 0;
6714
6
        } else {
6715
6
            TxnRunningPB txn_running_pb;
6716
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6717
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6718
0
                return -1;
6719
0
            }
6720
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6721
4
                return 0;
6722
4
            }
6723
2
            ++num_timeout;
6724
6725
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6726
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6727
2
            txn_info.set_finish_time(current_time);
6728
2
            txn_info.set_reason("timeout");
6729
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6730
2
            txn_inf_val.clear();
6731
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6732
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6733
0
                return -1;
6734
0
            }
6735
2
            txn->put(txn_inf_key, txn_inf_val);
6736
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6737
            // Put recycle txn key
6738
2
            std::string recyc_txn_key, recyc_txn_val;
6739
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6740
2
            RecycleTxnPB recycle_txn_pb;
6741
2
            recycle_txn_pb.set_creation_time(current_time);
6742
2
            recycle_txn_pb.set_label(txn_info.label());
6743
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6744
0
                LOG_WARNING("failed to serialize txn recycle info")
6745
0
                        .tag("key", hex(k))
6746
0
                        .tag("db_id", db_id)
6747
0
                        .tag("txn_id", txn_id);
6748
0
                return -1;
6749
0
            }
6750
2
            txn->put(recyc_txn_key, recyc_txn_val);
6751
            // Remove txn running key
6752
2
            txn->remove(k);
6753
2
            err = txn->commit();
6754
2
            if (err != TxnErrorCode::TXN_OK) {
6755
0
                LOG_WARNING("failed to commit txn err={}", err)
6756
0
                        .tag("key", hex(k))
6757
0
                        .tag("db_id", db_id)
6758
0
                        .tag("txn_id", txn_id);
6759
0
                return -1;
6760
0
            }
6761
2
            metrics_context.total_recycled_num = ++num_abort;
6762
2
            metrics_context.report();
6763
2
        }
6764
6765
2
        return 0;
6766
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6667
3
                                  this](std::string_view k, std::string_view v) -> int {
6668
3
        ++num_scanned;
6669
6670
3
        std::unique_ptr<Transaction> txn;
6671
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6672
3
        if (err != TxnErrorCode::TXN_OK) {
6673
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6674
0
            return -1;
6675
0
        }
6676
3
        std::string_view k1 = k;
6677
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6678
3
        k1.remove_prefix(1); // Remove key space
6679
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6680
3
        if (decode_key(&k1, &out) != 0) {
6681
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6685
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6686
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6687
        // Update txn_info
6688
3
        std::string txn_inf_key, txn_inf_val;
6689
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6690
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6691
3
        if (err != TxnErrorCode::TXN_OK) {
6692
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6693
0
            return -1;
6694
0
        }
6695
3
        TxnInfoPB txn_info;
6696
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6697
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
6701
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6702
3
            txn.reset();
6703
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6704
3
            std::shared_ptr<TxnLazyCommitTask> task =
6705
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6706
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6707
3
            if (ret.first != MetaServiceCode::OK) {
6708
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6709
0
                             << "msg=" << ret.second;
6710
0
                return -1;
6711
0
            }
6712
3
            ++num_advance;
6713
3
            return 0;
6714
3
        } else {
6715
0
            TxnRunningPB txn_running_pb;
6716
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6717
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6718
0
                return -1;
6719
0
            }
6720
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6721
0
                return 0;
6722
0
            }
6723
0
            ++num_timeout;
6724
6725
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6726
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6727
0
            txn_info.set_finish_time(current_time);
6728
0
            txn_info.set_reason("timeout");
6729
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6730
0
            txn_inf_val.clear();
6731
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6732
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6733
0
                return -1;
6734
0
            }
6735
0
            txn->put(txn_inf_key, txn_inf_val);
6736
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6737
            // Put recycle txn key
6738
0
            std::string recyc_txn_key, recyc_txn_val;
6739
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6740
0
            RecycleTxnPB recycle_txn_pb;
6741
0
            recycle_txn_pb.set_creation_time(current_time);
6742
0
            recycle_txn_pb.set_label(txn_info.label());
6743
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6744
0
                LOG_WARNING("failed to serialize txn recycle info")
6745
0
                        .tag("key", hex(k))
6746
0
                        .tag("db_id", db_id)
6747
0
                        .tag("txn_id", txn_id);
6748
0
                return -1;
6749
0
            }
6750
0
            txn->put(recyc_txn_key, recyc_txn_val);
6751
            // Remove txn running key
6752
0
            txn->remove(k);
6753
0
            err = txn->commit();
6754
0
            if (err != TxnErrorCode::TXN_OK) {
6755
0
                LOG_WARNING("failed to commit txn err={}", err)
6756
0
                        .tag("key", hex(k))
6757
0
                        .tag("db_id", db_id)
6758
0
                        .tag("txn_id", txn_id);
6759
0
                return -1;
6760
0
            }
6761
0
            metrics_context.total_recycled_num = ++num_abort;
6762
0
            metrics_context.report();
6763
0
        }
6764
6765
0
        return 0;
6766
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6667
6
                                  this](std::string_view k, std::string_view v) -> int {
6668
6
        ++num_scanned;
6669
6670
6
        std::unique_ptr<Transaction> txn;
6671
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6672
6
        if (err != TxnErrorCode::TXN_OK) {
6673
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6674
0
            return -1;
6675
0
        }
6676
6
        std::string_view k1 = k;
6677
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6678
6
        k1.remove_prefix(1); // Remove key space
6679
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6680
6
        if (decode_key(&k1, &out) != 0) {
6681
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6682
0
            return -1;
6683
0
        }
6684
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6685
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6686
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6687
        // Update txn_info
6688
6
        std::string txn_inf_key, txn_inf_val;
6689
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6690
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6691
6
        if (err != TxnErrorCode::TXN_OK) {
6692
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6693
0
            return -1;
6694
0
        }
6695
6
        TxnInfoPB txn_info;
6696
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6697
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6698
0
            return -1;
6699
0
        }
6700
6701
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6702
0
            txn.reset();
6703
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6704
0
            std::shared_ptr<TxnLazyCommitTask> task =
6705
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6706
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6707
0
            if (ret.first != MetaServiceCode::OK) {
6708
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6709
0
                             << "msg=" << ret.second;
6710
0
                return -1;
6711
0
            }
6712
0
            ++num_advance;
6713
0
            return 0;
6714
6
        } else {
6715
6
            TxnRunningPB txn_running_pb;
6716
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6717
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6718
0
                return -1;
6719
0
            }
6720
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6721
4
                return 0;
6722
4
            }
6723
2
            ++num_timeout;
6724
6725
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6726
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6727
2
            txn_info.set_finish_time(current_time);
6728
2
            txn_info.set_reason("timeout");
6729
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6730
2
            txn_inf_val.clear();
6731
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6732
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6733
0
                return -1;
6734
0
            }
6735
2
            txn->put(txn_inf_key, txn_inf_val);
6736
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6737
            // Put recycle txn key
6738
2
            std::string recyc_txn_key, recyc_txn_val;
6739
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6740
2
            RecycleTxnPB recycle_txn_pb;
6741
2
            recycle_txn_pb.set_creation_time(current_time);
6742
2
            recycle_txn_pb.set_label(txn_info.label());
6743
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6744
0
                LOG_WARNING("failed to serialize txn recycle info")
6745
0
                        .tag("key", hex(k))
6746
0
                        .tag("db_id", db_id)
6747
0
                        .tag("txn_id", txn_id);
6748
0
                return -1;
6749
0
            }
6750
2
            txn->put(recyc_txn_key, recyc_txn_val);
6751
            // Remove txn running key
6752
2
            txn->remove(k);
6753
2
            err = txn->commit();
6754
2
            if (err != TxnErrorCode::TXN_OK) {
6755
0
                LOG_WARNING("failed to commit txn err={}", err)
6756
0
                        .tag("key", hex(k))
6757
0
                        .tag("db_id", db_id)
6758
0
                        .tag("txn_id", txn_id);
6759
0
                return -1;
6760
0
            }
6761
2
            metrics_context.total_recycled_num = ++num_abort;
6762
2
            metrics_context.report();
6763
2
        }
6764
6765
2
        return 0;
6766
6
    };
6767
6768
19
    if (config::enable_recycler_stats_metrics) {
6769
0
        scan_and_statistics_abort_timeout_txn();
6770
0
    }
6771
    // recycle_func and loop_done for scan and recycle
6772
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6773
19
                            std::move(handle_txn_running_kv));
6774
19
}
6775
6776
22
int InstanceRecycler::recycle_expired_txn_label() {
6777
22
    const std::string task_name = "recycle_expired_txn_label";
6778
22
    int64_t num_scanned = 0;
6779
22
    int64_t num_expired = 0;
6780
22
    std::atomic_long num_recycled = 0;
6781
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6782
22
    int ret = 0;
6783
6784
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6785
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6786
22
    std::string begin_recycle_txn_key;
6787
22
    std::string end_recycle_txn_key;
6788
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6789
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6790
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
6791
6792
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6793
6794
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6795
22
    register_recycle_task(task_name, start_time);
6796
22
    DORIS_CLOUD_DEFER {
6797
22
        unregister_recycle_task(task_name);
6798
22
        int64_t cost =
6799
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6800
22
        metrics_context.finish_report();
6801
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6802
22
                .tag("instance_id", instance_id_)
6803
22
                .tag("num_scanned", num_scanned)
6804
22
                .tag("num_expired", num_expired)
6805
22
                .tag("num_recycled", num_recycled);
6806
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6796
1
    DORIS_CLOUD_DEFER {
6797
1
        unregister_recycle_task(task_name);
6798
1
        int64_t cost =
6799
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6800
1
        metrics_context.finish_report();
6801
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6802
1
                .tag("instance_id", instance_id_)
6803
1
                .tag("num_scanned", num_scanned)
6804
1
                .tag("num_expired", num_expired)
6805
1
                .tag("num_recycled", num_recycled);
6806
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6796
21
    DORIS_CLOUD_DEFER {
6797
21
        unregister_recycle_task(task_name);
6798
21
        int64_t cost =
6799
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6800
21
        metrics_context.finish_report();
6801
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6802
21
                .tag("instance_id", instance_id_)
6803
21
                .tag("num_scanned", num_scanned)
6804
21
                .tag("num_expired", num_expired)
6805
21
                .tag("num_recycled", num_recycled);
6806
21
    };
6807
6808
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6809
6810
22
    SyncExecutor<int> concurrent_delete_executor(
6811
22
            _thread_pool_group.s3_producer_pool,
6812
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6813
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6813
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6813
38.0k
            [](const int& ret) { return ret != 0; });
6814
6815
22
    int64_t current_time_ms =
6816
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6817
6818
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6819
50.0k
        ++num_scanned;
6820
50.0k
        RecycleTxnPB recycle_txn_pb;
6821
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6822
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6823
0
            return -1;
6824
0
        }
6825
50.0k
        if ((config::force_immediate_recycle) ||
6826
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6827
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6828
50.0k
             current_time_ms)) {
6829
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6830
38.0k
            num_expired++;
6831
6832
38.0k
            std::string_view k1 = k;
6833
38.0k
            k1.remove_prefix(1); // Remove key space
6834
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
38.0k
            if (decode_key(&k1, &out) != 0) {
6836
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
                return -1;
6838
0
            }
6839
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6841
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6842
38.0k
        }
6843
50.0k
        return 0;
6844
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6818
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6819
1
        ++num_scanned;
6820
1
        RecycleTxnPB recycle_txn_pb;
6821
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6822
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6823
0
            return -1;
6824
0
        }
6825
1
        if ((config::force_immediate_recycle) ||
6826
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6827
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6828
1
             current_time_ms)) {
6829
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6830
1
            num_expired++;
6831
6832
1
            std::string_view k1 = k;
6833
1
            k1.remove_prefix(1); // Remove key space
6834
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
1
            if (decode_key(&k1, &out) != 0) {
6836
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
                return -1;
6838
0
            }
6839
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6841
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6842
1
        }
6843
1
        return 0;
6844
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6818
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6819
50.0k
        ++num_scanned;
6820
50.0k
        RecycleTxnPB recycle_txn_pb;
6821
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6822
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6823
0
            return -1;
6824
0
        }
6825
50.0k
        if ((config::force_immediate_recycle) ||
6826
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6827
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6828
50.0k
             current_time_ms)) {
6829
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6830
38.0k
            num_expired++;
6831
6832
38.0k
            std::string_view k1 = k;
6833
38.0k
            k1.remove_prefix(1); // Remove key space
6834
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
38.0k
            if (decode_key(&k1, &out) != 0) {
6836
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
                return -1;
6838
0
            }
6839
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6841
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6842
38.0k
        }
6843
50.0k
        return 0;
6844
50.0k
    };
6845
6846
    // int 0 for success, 1 for conflict, -1 for error
6847
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6848
38.0k
        std::string_view k1 = k;
6849
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6850
38.0k
        k1.remove_prefix(1); // Remove key space
6851
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6852
38.0k
        int ret = decode_key(&k1, &out);
6853
38.0k
        if (ret != 0) {
6854
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6855
0
            return -1;
6856
0
        }
6857
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6858
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6859
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6860
38.0k
        std::unique_ptr<Transaction> txn;
6861
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6862
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6863
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6864
0
            return -1;
6865
0
        }
6866
        // Remove txn index kv
6867
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6868
38.0k
        txn->remove(index_key);
6869
        // Remove txn info kv
6870
38.0k
        std::string info_key, info_val;
6871
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6872
38.0k
        err = txn->get(info_key, &info_val);
6873
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6874
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6875
0
            return -1;
6876
0
        }
6877
38.0k
        TxnInfoPB txn_info;
6878
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6879
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6880
0
            return -1;
6881
0
        }
6882
38.0k
        txn->remove(info_key);
6883
        // Remove sub txn index kvs
6884
38.0k
        std::vector<std::string> sub_txn_index_keys;
6885
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6886
37.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6887
37.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6888
37.9k
        }
6889
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6890
37.9k
            txn->remove(sub_txn_index_key);
6891
37.9k
        }
6892
        // Update txn label
6893
38.0k
        std::string label_key, label_val;
6894
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6895
38.0k
        err = txn->get(label_key, &label_val);
6896
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6897
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6898
0
                         << " err=" << err;
6899
0
            return -1;
6900
0
        }
6901
38.0k
        TxnLabelPB txn_label;
6902
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6903
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6904
0
            return -1;
6905
0
        }
6906
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6907
38.0k
        if (it != txn_label.txn_ids().end()) {
6908
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6909
38.0k
        }
6910
38.0k
        if (txn_label.txn_ids().empty()) {
6911
38.0k
            txn->remove(label_key);
6912
38.0k
            TEST_SYNC_POINT_CALLBACK(
6913
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6914
38.0k
        } else {
6915
10
            if (!txn_label.SerializeToString(&label_val)) {
6916
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6917
0
                return -1;
6918
0
            }
6919
10
            TEST_SYNC_POINT_CALLBACK(
6920
10
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6921
10
            txn->atomic_set_ver_value(label_key, label_val);
6922
10
            TEST_SYNC_POINT_CALLBACK(
6923
10
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6924
10
        }
6925
        // Remove recycle txn kv
6926
38.0k
        txn->remove(k);
6927
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6928
38.0k
        err = txn->commit();
6929
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6930
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6931
4
                TEST_SYNC_POINT_CALLBACK(
6932
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6933
                // log the txn_id and label
6934
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6935
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6936
4
                             << " txn_label=" << txn_info.label();
6937
4
                return 1;
6938
4
            }
6939
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6940
0
            return -1;
6941
4
        }
6942
38.0k
        ++num_recycled;
6943
6944
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6945
38.0k
        return 0;
6946
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6847
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6848
1
        std::string_view k1 = k;
6849
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6850
1
        k1.remove_prefix(1); // Remove key space
6851
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6852
1
        int ret = decode_key(&k1, &out);
6853
1
        if (ret != 0) {
6854
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6855
0
            return -1;
6856
0
        }
6857
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6858
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6859
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6860
1
        std::unique_ptr<Transaction> txn;
6861
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6862
1
        if (err != TxnErrorCode::TXN_OK) {
6863
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6864
0
            return -1;
6865
0
        }
6866
        // Remove txn index kv
6867
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6868
1
        txn->remove(index_key);
6869
        // Remove txn info kv
6870
1
        std::string info_key, info_val;
6871
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6872
1
        err = txn->get(info_key, &info_val);
6873
1
        if (err != TxnErrorCode::TXN_OK) {
6874
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6875
0
            return -1;
6876
0
        }
6877
1
        TxnInfoPB txn_info;
6878
1
        if (!txn_info.ParseFromString(info_val)) {
6879
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6880
0
            return -1;
6881
0
        }
6882
1
        txn->remove(info_key);
6883
        // Remove sub txn index kvs
6884
1
        std::vector<std::string> sub_txn_index_keys;
6885
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6886
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6887
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6888
0
        }
6889
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6890
0
            txn->remove(sub_txn_index_key);
6891
0
        }
6892
        // Update txn label
6893
1
        std::string label_key, label_val;
6894
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6895
1
        err = txn->get(label_key, &label_val);
6896
1
        if (err != TxnErrorCode::TXN_OK) {
6897
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6898
0
                         << " err=" << err;
6899
0
            return -1;
6900
0
        }
6901
1
        TxnLabelPB txn_label;
6902
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6903
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6904
0
            return -1;
6905
0
        }
6906
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6907
1
        if (it != txn_label.txn_ids().end()) {
6908
1
            txn_label.mutable_txn_ids()->erase(it);
6909
1
        }
6910
1
        if (txn_label.txn_ids().empty()) {
6911
1
            txn->remove(label_key);
6912
1
            TEST_SYNC_POINT_CALLBACK(
6913
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6914
1
        } else {
6915
0
            if (!txn_label.SerializeToString(&label_val)) {
6916
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6917
0
                return -1;
6918
0
            }
6919
0
            TEST_SYNC_POINT_CALLBACK(
6920
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6921
0
            txn->atomic_set_ver_value(label_key, label_val);
6922
0
            TEST_SYNC_POINT_CALLBACK(
6923
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6924
0
        }
6925
        // Remove recycle txn kv
6926
1
        txn->remove(k);
6927
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6928
1
        err = txn->commit();
6929
1
        if (err != TxnErrorCode::TXN_OK) {
6930
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6931
0
                TEST_SYNC_POINT_CALLBACK(
6932
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6933
                // log the txn_id and label
6934
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6935
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6936
0
                             << " txn_label=" << txn_info.label();
6937
0
                return 1;
6938
0
            }
6939
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6940
0
            return -1;
6941
0
        }
6942
1
        ++num_recycled;
6943
6944
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6945
1
        return 0;
6946
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6847
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6848
38.0k
        std::string_view k1 = k;
6849
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6850
38.0k
        k1.remove_prefix(1); // Remove key space
6851
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6852
38.0k
        int ret = decode_key(&k1, &out);
6853
38.0k
        if (ret != 0) {
6854
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6855
0
            return -1;
6856
0
        }
6857
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6858
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6859
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6860
38.0k
        std::unique_ptr<Transaction> txn;
6861
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6862
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6863
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6864
0
            return -1;
6865
0
        }
6866
        // Remove txn index kv
6867
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6868
38.0k
        txn->remove(index_key);
6869
        // Remove txn info kv
6870
38.0k
        std::string info_key, info_val;
6871
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6872
38.0k
        err = txn->get(info_key, &info_val);
6873
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6874
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6875
0
            return -1;
6876
0
        }
6877
38.0k
        TxnInfoPB txn_info;
6878
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6879
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6880
0
            return -1;
6881
0
        }
6882
38.0k
        txn->remove(info_key);
6883
        // Remove sub txn index kvs
6884
38.0k
        std::vector<std::string> sub_txn_index_keys;
6885
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6886
37.9k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6887
37.9k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6888
37.9k
        }
6889
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6890
37.9k
            txn->remove(sub_txn_index_key);
6891
37.9k
        }
6892
        // Update txn label
6893
38.0k
        std::string label_key, label_val;
6894
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6895
38.0k
        err = txn->get(label_key, &label_val);
6896
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6897
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6898
0
                         << " err=" << err;
6899
0
            return -1;
6900
0
        }
6901
38.0k
        TxnLabelPB txn_label;
6902
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6903
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6904
0
            return -1;
6905
0
        }
6906
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6907
38.0k
        if (it != txn_label.txn_ids().end()) {
6908
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6909
38.0k
        }
6910
38.0k
        if (txn_label.txn_ids().empty()) {
6911
38.0k
            txn->remove(label_key);
6912
38.0k
            TEST_SYNC_POINT_CALLBACK(
6913
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6914
38.0k
        } else {
6915
10
            if (!txn_label.SerializeToString(&label_val)) {
6916
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6917
0
                return -1;
6918
0
            }
6919
10
            TEST_SYNC_POINT_CALLBACK(
6920
10
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6921
10
            txn->atomic_set_ver_value(label_key, label_val);
6922
10
            TEST_SYNC_POINT_CALLBACK(
6923
10
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6924
10
        }
6925
        // Remove recycle txn kv
6926
38.0k
        txn->remove(k);
6927
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6928
38.0k
        err = txn->commit();
6929
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6930
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6931
4
                TEST_SYNC_POINT_CALLBACK(
6932
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6933
                // log the txn_id and label
6934
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6935
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6936
4
                             << " txn_label=" << txn_info.label();
6937
4
                return 1;
6938
4
            }
6939
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6940
0
            return -1;
6941
4
        }
6942
38.0k
        ++num_recycled;
6943
6944
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6945
38.0k
        return 0;
6946
38.0k
    };
6947
6948
22
    auto loop_done = [&]() -> int {
6949
15
        DORIS_CLOUD_DEFER {
6950
15
            recycle_txn_keys_by_label.clear();
6951
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6949
1
        DORIS_CLOUD_DEFER {
6950
1
            recycle_txn_keys_by_label.clear();
6951
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6949
14
        DORIS_CLOUD_DEFER {
6950
14
            recycle_txn_keys_by_label.clear();
6951
14
        };
6952
15
        TEST_SYNC_POINT_CALLBACK(
6953
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6954
15
                &recycle_txn_keys_by_label);
6955
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6956
38.0k
            int ret = delete_recycle_txn_kv(k);
6957
38.0k
            TEST_SYNC_POINT_CALLBACK(
6958
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6959
38.0k
                    &ret);
6960
38.0k
            if (ret == 1) {
6961
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6962
4
                for (int i = 1; i <= max_retry; ++i) {
6963
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6964
3
                    ret = delete_recycle_txn_kv(k);
6965
3
                    TEST_SYNC_POINT_CALLBACK(
6966
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6967
3
                            "error",
6968
3
                            &ret);
6969
3
                    if (ret != 1) {
6970
1
                        break;
6971
1
                    }
6972
                    // random sleep 0-100 ms to retry
6973
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6974
2
                }
6975
2
            }
6976
38.0k
            return ret;
6977
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6955
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6956
1
            int ret = delete_recycle_txn_kv(k);
6957
1
            TEST_SYNC_POINT_CALLBACK(
6958
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6959
1
                    &ret);
6960
1
            if (ret == 1) {
6961
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6962
0
                for (int i = 1; i <= max_retry; ++i) {
6963
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6964
0
                    ret = delete_recycle_txn_kv(k);
6965
0
                    TEST_SYNC_POINT_CALLBACK(
6966
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6967
0
                            "error",
6968
0
                            &ret);
6969
0
                    if (ret != 1) {
6970
0
                        break;
6971
0
                    }
6972
                    // random sleep 0-100 ms to retry
6973
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6974
0
                }
6975
0
            }
6976
1
            return ret;
6977
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6955
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6956
38.0k
            int ret = delete_recycle_txn_kv(k);
6957
38.0k
            TEST_SYNC_POINT_CALLBACK(
6958
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6959
38.0k
                    &ret);
6960
38.0k
            if (ret == 1) {
6961
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6962
4
                for (int i = 1; i <= max_retry; ++i) {
6963
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6964
3
                    ret = delete_recycle_txn_kv(k);
6965
3
                    TEST_SYNC_POINT_CALLBACK(
6966
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6967
3
                            "error",
6968
3
                            &ret);
6969
3
                    if (ret != 1) {
6970
1
                        break;
6971
1
                    }
6972
                    // random sleep 0-100 ms to retry
6973
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6974
2
                }
6975
2
            }
6976
38.0k
            return ret;
6977
38.0k
        };
6978
6979
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6980
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6981
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6982
0
                           << " txn_count=" << txn_keys.size();
6983
38.0k
                for (const auto& k : txn_keys) {
6984
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6985
38.0k
                    if (ret != 0) {
6986
2
                        LOG_WARNING("failed to delete recycle txn kv")
6987
2
                                .tag("instance id", instance_id_)
6988
2
                                .tag("key", hex(k))
6989
2
                                .tag("label_key", hex(label_key));
6990
2
                        return -1;
6991
2
                    }
6992
38.0k
                }
6993
38.0k
                return 0;
6994
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6980
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6981
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6982
0
                           << " txn_count=" << txn_keys.size();
6983
1
                for (const auto& k : txn_keys) {
6984
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
6985
1
                    if (ret != 0) {
6986
0
                        LOG_WARNING("failed to delete recycle txn kv")
6987
0
                                .tag("instance id", instance_id_)
6988
0
                                .tag("key", hex(k))
6989
0
                                .tag("label_key", hex(label_key));
6990
0
                        return -1;
6991
0
                    }
6992
1
                }
6993
1
                return 0;
6994
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6980
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6981
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6982
0
                           << " txn_count=" << txn_keys.size();
6983
38.0k
                for (const auto& k : txn_keys) {
6984
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6985
38.0k
                    if (ret != 0) {
6986
2
                        LOG_WARNING("failed to delete recycle txn kv")
6987
2
                                .tag("instance id", instance_id_)
6988
2
                                .tag("key", hex(k))
6989
2
                                .tag("label_key", hex(label_key));
6990
2
                        return -1;
6991
2
                    }
6992
38.0k
                }
6993
38.0k
                return 0;
6994
38.0k
            });
6995
38.0k
        }
6996
15
        bool finished = true;
6997
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6998
38.0k
        for (int r : rets) {
6999
38.0k
            if (r != 0) {
7000
2
                ret = -1;
7001
2
            }
7002
38.0k
        }
7003
7004
15
        ret = finished ? ret : -1;
7005
7006
        // Update metrics after all concurrent tasks completed
7007
15
        metrics_context.total_recycled_num = num_recycled.load();
7008
15
        metrics_context.report();
7009
7010
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7011
7012
15
        if (ret != 0) {
7013
6
            LOG_WARNING("recycle txn kv ret!=0")
7014
6
                    .tag("finished", finished)
7015
6
                    .tag("ret", ret)
7016
6
                    .tag("instance_id", instance_id_);
7017
6
            return ret;
7018
6
        }
7019
9
        return ret;
7020
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6948
1
    auto loop_done = [&]() -> int {
6949
1
        DORIS_CLOUD_DEFER {
6950
1
            recycle_txn_keys_by_label.clear();
6951
1
        };
6952
1
        TEST_SYNC_POINT_CALLBACK(
6953
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6954
1
                &recycle_txn_keys_by_label);
6955
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6956
1
            int ret = delete_recycle_txn_kv(k);
6957
1
            TEST_SYNC_POINT_CALLBACK(
6958
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6959
1
                    &ret);
6960
1
            if (ret == 1) {
6961
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6962
1
                for (int i = 1; i <= max_retry; ++i) {
6963
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6964
1
                    ret = delete_recycle_txn_kv(k);
6965
1
                    TEST_SYNC_POINT_CALLBACK(
6966
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6967
1
                            "error",
6968
1
                            &ret);
6969
1
                    if (ret != 1) {
6970
1
                        break;
6971
1
                    }
6972
                    // random sleep 0-100 ms to retry
6973
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6974
1
                }
6975
1
            }
6976
1
            return ret;
6977
1
        };
6978
6979
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6980
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6981
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6982
1
                           << " txn_count=" << txn_keys.size();
6983
1
                for (const auto& k : txn_keys) {
6984
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
6985
1
                    if (ret != 0) {
6986
1
                        LOG_WARNING("failed to delete recycle txn kv")
6987
1
                                .tag("instance id", instance_id_)
6988
1
                                .tag("key", hex(k))
6989
1
                                .tag("label_key", hex(label_key));
6990
1
                        return -1;
6991
1
                    }
6992
1
                }
6993
1
                return 0;
6994
1
            });
6995
1
        }
6996
1
        bool finished = true;
6997
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6998
1
        for (int r : rets) {
6999
1
            if (r != 0) {
7000
0
                ret = -1;
7001
0
            }
7002
1
        }
7003
7004
1
        ret = finished ? ret : -1;
7005
7006
        // Update metrics after all concurrent tasks completed
7007
1
        metrics_context.total_recycled_num = num_recycled.load();
7008
1
        metrics_context.report();
7009
7010
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7011
7012
1
        if (ret != 0) {
7013
0
            LOG_WARNING("recycle txn kv ret!=0")
7014
0
                    .tag("finished", finished)
7015
0
                    .tag("ret", ret)
7016
0
                    .tag("instance_id", instance_id_);
7017
0
            return ret;
7018
0
        }
7019
1
        return ret;
7020
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6948
14
    auto loop_done = [&]() -> int {
6949
14
        DORIS_CLOUD_DEFER {
6950
14
            recycle_txn_keys_by_label.clear();
6951
14
        };
6952
14
        TEST_SYNC_POINT_CALLBACK(
6953
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6954
14
                &recycle_txn_keys_by_label);
6955
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6956
14
            int ret = delete_recycle_txn_kv(k);
6957
14
            TEST_SYNC_POINT_CALLBACK(
6958
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6959
14
                    &ret);
6960
14
            if (ret == 1) {
6961
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6962
14
                for (int i = 1; i <= max_retry; ++i) {
6963
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6964
14
                    ret = delete_recycle_txn_kv(k);
6965
14
                    TEST_SYNC_POINT_CALLBACK(
6966
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6967
14
                            "error",
6968
14
                            &ret);
6969
14
                    if (ret != 1) {
6970
14
                        break;
6971
14
                    }
6972
                    // random sleep 0-100 ms to retry
6973
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6974
14
                }
6975
14
            }
6976
14
            return ret;
6977
14
        };
6978
6979
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6980
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6981
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6982
38.0k
                           << " txn_count=" << txn_keys.size();
6983
38.0k
                for (const auto& k : txn_keys) {
6984
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6985
38.0k
                    if (ret != 0) {
6986
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
6987
38.0k
                                .tag("instance id", instance_id_)
6988
38.0k
                                .tag("key", hex(k))
6989
38.0k
                                .tag("label_key", hex(label_key));
6990
38.0k
                        return -1;
6991
38.0k
                    }
6992
38.0k
                }
6993
38.0k
                return 0;
6994
38.0k
            });
6995
38.0k
        }
6996
14
        bool finished = true;
6997
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6998
38.0k
        for (int r : rets) {
6999
38.0k
            if (r != 0) {
7000
2
                ret = -1;
7001
2
            }
7002
38.0k
        }
7003
7004
14
        ret = finished ? ret : -1;
7005
7006
        // Update metrics after all concurrent tasks completed
7007
14
        metrics_context.total_recycled_num = num_recycled.load();
7008
14
        metrics_context.report();
7009
7010
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7011
7012
14
        if (ret != 0) {
7013
6
            LOG_WARNING("recycle txn kv ret!=0")
7014
6
                    .tag("finished", finished)
7015
6
                    .tag("ret", ret)
7016
6
                    .tag("instance_id", instance_id_);
7017
6
            return ret;
7018
6
        }
7019
8
        return ret;
7020
14
    };
7021
7022
22
    if (config::enable_recycler_stats_metrics) {
7023
0
        scan_and_statistics_expired_txn_label();
7024
0
    }
7025
    // recycle_func and loop_done for scan and recycle
7026
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7027
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7028
22
}
7029
7030
struct CopyJobIdTuple {
7031
    std::string instance_id;
7032
    std::string stage_id;
7033
    long table_id;
7034
    std::string copy_id;
7035
    std::string stage_path;
7036
};
7037
struct BatchObjStoreAccessor {
7038
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7039
                          TxnKv* txn_kv)
7040
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7041
3
    ~BatchObjStoreAccessor() {
7042
3
        if (!paths_.empty()) {
7043
3
            consume();
7044
3
        }
7045
3
    }
7046
7047
    /**
7048
    * To implicitely do batch work and submit the batch delete task to s3
7049
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7050
    *
7051
    * @param copy_job The protubuf struct consists of the copy job files.
7052
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7053
    *            it would last until we finish the delete task, here we need pass one string value
7054
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7055
    */
7056
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7057
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7058
5
        auto& file_keys = copy_file_keys_[key];
7059
5
        file_keys.log_trace =
7060
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7061
5
                            instance_id, stage_id, table_id, copy_id, path);
7062
5
        std::string_view log_trace = file_keys.log_trace;
7063
2.03k
        for (const auto& file : copy_job.object_files()) {
7064
2.03k
            auto relative_path = file.relative_path();
7065
2.03k
            paths_.push_back(relative_path);
7066
2.03k
            file_keys.keys.push_back(copy_file_key(
7067
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7068
2.03k
            LOG_INFO(log_trace)
7069
2.03k
                    .tag("relative_path", relative_path)
7070
2.03k
                    .tag("batch_count", batch_count_);
7071
2.03k
        }
7072
5
        LOG_INFO(log_trace)
7073
5
                .tag("objects_num", copy_job.object_files().size())
7074
5
                .tag("batch_count", batch_count_);
7075
        // 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
7076
        // recommend using delete objects when objects num is less than 10)
7077
5
        if (paths_.size() < 1000) {
7078
3
            return;
7079
3
        }
7080
2
        consume();
7081
2
    }
7082
7083
private:
7084
5
    void consume() {
7085
5
        DORIS_CLOUD_DEFER {
7086
5
            paths_.clear();
7087
5
            copy_file_keys_.clear();
7088
5
            batch_count_++;
7089
7090
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7091
5
                        batch_count_);
7092
5
        };
7093
7094
5
        StopWatch sw;
7095
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7096
5
        if (0 != accessor_->delete_files(paths_)) {
7097
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7098
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7099
2
            return;
7100
2
        }
7101
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7102
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7103
        // delete fdb's keys
7104
3
        for (auto& file_keys : copy_file_keys_) {
7105
3
            auto& [log_trace, keys] = file_keys.second;
7106
3
            std::unique_ptr<Transaction> txn;
7107
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7108
0
                LOG(WARNING) << "failed to create txn";
7109
0
                continue;
7110
0
            }
7111
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7112
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7113
            // limited, should not cause the txn commit failed.
7114
1.02k
            for (const auto& key : keys) {
7115
1.02k
                txn->remove(key);
7116
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7117
1.02k
            }
7118
3
            txn->remove(file_keys.first);
7119
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7120
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7121
0
                continue;
7122
0
            }
7123
3
        }
7124
3
    }
7125
    std::shared_ptr<StorageVaultAccessor> accessor_;
7126
    // the path of the s3 files to be deleted
7127
    std::vector<std::string> paths_;
7128
    struct CopyFiles {
7129
        std::string log_trace;
7130
        std::vector<std::string> keys;
7131
    };
7132
    // pair<std::string, std::vector<std::string>>
7133
    // first: instance_id_ stage_id table_id query_id
7134
    // second: keys to be deleted
7135
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7136
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7137
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7138
    // which can together uniquely identifies different tasks for tracing log
7139
    uint64_t& batch_count_;
7140
    TxnKv* txn_kv_;
7141
};
7142
7143
13
int InstanceRecycler::recycle_copy_jobs() {
7144
13
    int64_t num_scanned = 0;
7145
13
    int64_t num_finished = 0;
7146
13
    int64_t num_expired = 0;
7147
13
    int64_t num_recycled = 0;
7148
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7149
13
    uint64_t batch_count = 0;
7150
13
    const std::string task_name = "recycle_copy_jobs";
7151
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7152
7153
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7154
7155
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7156
13
    register_recycle_task(task_name, start_time);
7157
7158
13
    DORIS_CLOUD_DEFER {
7159
13
        unregister_recycle_task(task_name);
7160
13
        int64_t cost =
7161
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7162
13
        metrics_context.finish_report();
7163
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7164
13
                .tag("instance_id", instance_id_)
7165
13
                .tag("num_scanned", num_scanned)
7166
13
                .tag("num_finished", num_finished)
7167
13
                .tag("num_expired", num_expired)
7168
13
                .tag("num_recycled", num_recycled);
7169
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7158
13
    DORIS_CLOUD_DEFER {
7159
13
        unregister_recycle_task(task_name);
7160
13
        int64_t cost =
7161
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7162
13
        metrics_context.finish_report();
7163
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7164
13
                .tag("instance_id", instance_id_)
7165
13
                .tag("num_scanned", num_scanned)
7166
13
                .tag("num_finished", num_finished)
7167
13
                .tag("num_expired", num_expired)
7168
13
                .tag("num_recycled", num_recycled);
7169
13
    };
7170
7171
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7172
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7173
13
    std::string key0;
7174
13
    std::string key1;
7175
13
    copy_job_key(key_info0, &key0);
7176
13
    copy_job_key(key_info1, &key1);
7177
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7178
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7179
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7180
16
                         this](std::string_view k, std::string_view v) -> int {
7181
16
        ++num_scanned;
7182
16
        CopyJobPB copy_job;
7183
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7184
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7185
0
            return -1;
7186
0
        }
7187
7188
        // decode copy job key
7189
16
        auto k1 = k;
7190
16
        k1.remove_prefix(1);
7191
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7192
16
        decode_key(&k1, &out);
7193
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7194
        // -> CopyJobPB
7195
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7196
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7197
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7198
7199
16
        bool check_storage = true;
7200
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7201
12
            ++num_finished;
7202
7203
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7204
7
                auto it = stage_accessor_map.find(stage_id);
7205
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7206
7
                std::string_view path;
7207
7
                if (it != stage_accessor_map.end()) {
7208
2
                    accessor = it->second;
7209
5
                } else {
7210
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7211
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7212
5
                                                      &inner_accessor);
7213
5
                    if (ret < 0) { // error
7214
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7215
0
                        return -1;
7216
5
                    } else if (ret == 0) {
7217
3
                        path = inner_accessor->uri();
7218
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7219
3
                                inner_accessor, batch_count, txn_kv_.get());
7220
3
                        stage_accessor_map.emplace(stage_id, accessor);
7221
3
                    } else { // stage not found, skip check storage
7222
2
                        check_storage = false;
7223
2
                    }
7224
5
                }
7225
7
                if (check_storage) {
7226
                    // TODO delete objects with key and etag is not supported
7227
5
                    accessor->add(std::move(copy_job), std::string(k),
7228
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7229
5
                    return 0;
7230
5
                }
7231
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7232
5
                int64_t current_time =
7233
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7234
5
                if (copy_job.finish_time_ms() > 0) {
7235
2
                    if (!config::force_immediate_recycle &&
7236
2
                        current_time < copy_job.finish_time_ms() +
7237
2
                                               config::copy_job_max_retention_second * 1000) {
7238
1
                        return 0;
7239
1
                    }
7240
3
                } else {
7241
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7242
3
                    if (!config::force_immediate_recycle &&
7243
3
                        current_time < copy_job.start_time_ms() +
7244
3
                                               config::copy_job_max_retention_second * 1000) {
7245
1
                        return 0;
7246
1
                    }
7247
3
                }
7248
5
            }
7249
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7250
4
            int64_t current_time =
7251
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7252
            // if copy job is timeout: delete all copy file kvs and copy job kv
7253
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7254
2
                return 0;
7255
2
            }
7256
2
            ++num_expired;
7257
2
        }
7258
7259
        // delete all copy files
7260
7
        std::vector<std::string> copy_file_keys;
7261
70
        for (auto& file : copy_job.object_files()) {
7262
70
            copy_file_keys.push_back(copy_file_key(
7263
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7264
70
        }
7265
7
        std::unique_ptr<Transaction> txn;
7266
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7267
0
            LOG(WARNING) << "failed to create txn";
7268
0
            return -1;
7269
0
        }
7270
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7271
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7272
        // limited, should not cause the txn commit failed.
7273
70
        for (const auto& key : copy_file_keys) {
7274
70
            txn->remove(key);
7275
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7276
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7277
70
                      << ", query_id=" << copy_id;
7278
70
        }
7279
7
        txn->remove(k);
7280
7
        TxnErrorCode err = txn->commit();
7281
7
        if (err != TxnErrorCode::TXN_OK) {
7282
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7283
0
            return -1;
7284
0
        }
7285
7286
7
        metrics_context.total_recycled_num = ++num_recycled;
7287
7
        metrics_context.report();
7288
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7289
7
        return 0;
7290
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
7180
16
                         this](std::string_view k, std::string_view v) -> int {
7181
16
        ++num_scanned;
7182
16
        CopyJobPB copy_job;
7183
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7184
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7185
0
            return -1;
7186
0
        }
7187
7188
        // decode copy job key
7189
16
        auto k1 = k;
7190
16
        k1.remove_prefix(1);
7191
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7192
16
        decode_key(&k1, &out);
7193
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7194
        // -> CopyJobPB
7195
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7196
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7197
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7198
7199
16
        bool check_storage = true;
7200
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7201
12
            ++num_finished;
7202
7203
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7204
7
                auto it = stage_accessor_map.find(stage_id);
7205
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7206
7
                std::string_view path;
7207
7
                if (it != stage_accessor_map.end()) {
7208
2
                    accessor = it->second;
7209
5
                } else {
7210
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7211
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7212
5
                                                      &inner_accessor);
7213
5
                    if (ret < 0) { // error
7214
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7215
0
                        return -1;
7216
5
                    } else if (ret == 0) {
7217
3
                        path = inner_accessor->uri();
7218
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7219
3
                                inner_accessor, batch_count, txn_kv_.get());
7220
3
                        stage_accessor_map.emplace(stage_id, accessor);
7221
3
                    } else { // stage not found, skip check storage
7222
2
                        check_storage = false;
7223
2
                    }
7224
5
                }
7225
7
                if (check_storage) {
7226
                    // TODO delete objects with key and etag is not supported
7227
5
                    accessor->add(std::move(copy_job), std::string(k),
7228
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7229
5
                    return 0;
7230
5
                }
7231
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7232
5
                int64_t current_time =
7233
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7234
5
                if (copy_job.finish_time_ms() > 0) {
7235
2
                    if (!config::force_immediate_recycle &&
7236
2
                        current_time < copy_job.finish_time_ms() +
7237
2
                                               config::copy_job_max_retention_second * 1000) {
7238
1
                        return 0;
7239
1
                    }
7240
3
                } else {
7241
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7242
3
                    if (!config::force_immediate_recycle &&
7243
3
                        current_time < copy_job.start_time_ms() +
7244
3
                                               config::copy_job_max_retention_second * 1000) {
7245
1
                        return 0;
7246
1
                    }
7247
3
                }
7248
5
            }
7249
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7250
4
            int64_t current_time =
7251
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7252
            // if copy job is timeout: delete all copy file kvs and copy job kv
7253
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7254
2
                return 0;
7255
2
            }
7256
2
            ++num_expired;
7257
2
        }
7258
7259
        // delete all copy files
7260
7
        std::vector<std::string> copy_file_keys;
7261
70
        for (auto& file : copy_job.object_files()) {
7262
70
            copy_file_keys.push_back(copy_file_key(
7263
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7264
70
        }
7265
7
        std::unique_ptr<Transaction> txn;
7266
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7267
0
            LOG(WARNING) << "failed to create txn";
7268
0
            return -1;
7269
0
        }
7270
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7271
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7272
        // limited, should not cause the txn commit failed.
7273
70
        for (const auto& key : copy_file_keys) {
7274
70
            txn->remove(key);
7275
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7276
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7277
70
                      << ", query_id=" << copy_id;
7278
70
        }
7279
7
        txn->remove(k);
7280
7
        TxnErrorCode err = txn->commit();
7281
7
        if (err != TxnErrorCode::TXN_OK) {
7282
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7283
0
            return -1;
7284
0
        }
7285
7286
7
        metrics_context.total_recycled_num = ++num_recycled;
7287
7
        metrics_context.report();
7288
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7289
7
        return 0;
7290
7
    };
7291
7292
13
    if (config::enable_recycler_stats_metrics) {
7293
0
        scan_and_statistics_copy_jobs();
7294
0
    }
7295
    // recycle_func and loop_done for scan and recycle
7296
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7297
13
}
7298
7299
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7300
                                             const StagePB::StageType& stage_type,
7301
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7302
5
#ifdef UNIT_TEST
7303
    // In unit test, external use the same accessor as the internal stage
7304
5
    auto it = accessor_map_.find(stage_id);
7305
5
    if (it != accessor_map_.end()) {
7306
3
        *accessor = it->second;
7307
3
    } else {
7308
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7309
2
        return 1;
7310
2
    }
7311
#else
7312
    // init s3 accessor and add to accessor map
7313
    auto stage_it =
7314
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7315
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7316
7317
    if (stage_it == instance_info_.stages().end()) {
7318
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7319
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7320
        return 1;
7321
    }
7322
7323
    const auto& object_store_info = stage_it->obj_info();
7324
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7325
7326
    S3Conf s3_conf;
7327
    if (stage_type == StagePB::EXTERNAL) {
7328
        if (stage_access_type == StagePB::AKSK) {
7329
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7330
            if (!conf) {
7331
                return -1;
7332
            }
7333
7334
            s3_conf = std::move(*conf);
7335
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7336
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7337
            if (!conf) {
7338
                return -1;
7339
            }
7340
7341
            s3_conf = std::move(*conf);
7342
            if (instance_info_.ram_user().has_encryption_info()) {
7343
                AkSkPair plain_ak_sk_pair;
7344
                int ret = decrypt_ak_sk_helper(
7345
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7346
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7347
                if (ret != 0) {
7348
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7349
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7350
                    return -1;
7351
                }
7352
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7353
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7354
            } else {
7355
                s3_conf.ak = instance_info_.ram_user().ak();
7356
                s3_conf.sk = instance_info_.ram_user().sk();
7357
            }
7358
        } else {
7359
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7360
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7361
            return -1;
7362
        }
7363
    } else if (stage_type == StagePB::INTERNAL) {
7364
        int idx = stoi(object_store_info.id());
7365
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7366
            LOG(WARNING) << "invalid idx: " << idx;
7367
            return -1;
7368
        }
7369
7370
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7371
        auto conf = S3Conf::from_obj_store_info(old_obj);
7372
        if (!conf) {
7373
            return -1;
7374
        }
7375
7376
        s3_conf = std::move(*conf);
7377
        s3_conf.prefix = object_store_info.prefix();
7378
    } else {
7379
        LOG(WARNING) << "unknown stage type " << stage_type;
7380
        return -1;
7381
    }
7382
7383
    std::shared_ptr<S3Accessor> s3_accessor;
7384
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7385
    if (ret != 0) {
7386
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7387
        return -1;
7388
    }
7389
7390
    *accessor = std::move(s3_accessor);
7391
#endif
7392
3
    return 0;
7393
5
}
7394
7395
11
int InstanceRecycler::recycle_stage() {
7396
11
    int64_t num_scanned = 0;
7397
11
    int64_t num_recycled = 0;
7398
11
    const std::string task_name = "recycle_stage";
7399
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7400
7401
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7402
7403
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7404
11
    register_recycle_task(task_name, start_time);
7405
7406
11
    DORIS_CLOUD_DEFER {
7407
11
        unregister_recycle_task(task_name);
7408
11
        int64_t cost =
7409
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7410
11
        metrics_context.finish_report();
7411
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7412
11
                .tag("instance_id", instance_id_)
7413
11
                .tag("num_scanned", num_scanned)
7414
11
                .tag("num_recycled", num_recycled);
7415
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7406
11
    DORIS_CLOUD_DEFER {
7407
11
        unregister_recycle_task(task_name);
7408
11
        int64_t cost =
7409
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7410
11
        metrics_context.finish_report();
7411
        LOG_WARNING("recycle stage, cost={}s", cost)
7412
11
                .tag("instance_id", instance_id_)
7413
11
                .tag("num_scanned", num_scanned)
7414
11
                .tag("num_recycled", num_recycled);
7415
11
    };
7416
7417
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7418
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7419
11
    std::string key0 = recycle_stage_key(key_info0);
7420
11
    std::string key1 = recycle_stage_key(key_info1);
7421
7422
11
    std::vector<std::string_view> stage_keys;
7423
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7424
11
                         this](std::string_view k, std::string_view v) -> int {
7425
1
        ++num_scanned;
7426
1
        RecycleStagePB recycle_stage;
7427
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7428
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7429
0
            return -1;
7430
0
        }
7431
7432
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7433
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7434
0
            LOG(WARNING) << "invalid idx: " << idx;
7435
0
            return -1;
7436
0
        }
7437
7438
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7439
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7440
1
                [&] {
7441
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7442
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7443
1
                    if (!s3_conf) {
7444
1
                        return -1;
7445
1
                    }
7446
7447
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7448
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7449
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7450
1
                    if (ret != 0) {
7451
1
                        return -1;
7452
1
                    }
7453
7454
1
                    accessor = std::move(s3_accessor);
7455
1
                    return 0;
7456
1
                }(),
7457
1
                "recycle_stage:get_accessor", &accessor);
7458
7459
1
        if (ret != 0) {
7460
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7461
0
            return ret;
7462
0
        }
7463
7464
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7465
1
                .tag("instance_id", instance_id_)
7466
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7467
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7468
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7469
1
                .tag("obj_info_id", idx)
7470
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7471
1
        ret = accessor->delete_all();
7472
1
        if (ret != 0) {
7473
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7474
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7475
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7476
0
                         << ", ret=" << ret;
7477
0
            return -1;
7478
0
        }
7479
1
        metrics_context.total_recycled_num = ++num_recycled;
7480
1
        metrics_context.report();
7481
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7482
1
        stage_keys.push_back(k);
7483
1
        return 0;
7484
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7424
1
                         this](std::string_view k, std::string_view v) -> int {
7425
1
        ++num_scanned;
7426
1
        RecycleStagePB recycle_stage;
7427
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7428
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7429
0
            return -1;
7430
0
        }
7431
7432
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7433
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7434
0
            LOG(WARNING) << "invalid idx: " << idx;
7435
0
            return -1;
7436
0
        }
7437
7438
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7439
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7440
1
                [&] {
7441
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7442
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7443
1
                    if (!s3_conf) {
7444
1
                        return -1;
7445
1
                    }
7446
7447
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7448
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7449
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7450
1
                    if (ret != 0) {
7451
1
                        return -1;
7452
1
                    }
7453
7454
1
                    accessor = std::move(s3_accessor);
7455
1
                    return 0;
7456
1
                }(),
7457
1
                "recycle_stage:get_accessor", &accessor);
7458
7459
1
        if (ret != 0) {
7460
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7461
0
            return ret;
7462
0
        }
7463
7464
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7465
1
                .tag("instance_id", instance_id_)
7466
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7467
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7468
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7469
1
                .tag("obj_info_id", idx)
7470
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7471
1
        ret = accessor->delete_all();
7472
1
        if (ret != 0) {
7473
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7474
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7475
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7476
0
                         << ", ret=" << ret;
7477
0
            return -1;
7478
0
        }
7479
1
        metrics_context.total_recycled_num = ++num_recycled;
7480
1
        metrics_context.report();
7481
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7482
1
        stage_keys.push_back(k);
7483
1
        return 0;
7484
1
    };
7485
7486
11
    auto loop_done = [&stage_keys, this]() -> int {
7487
1
        if (stage_keys.empty()) return 0;
7488
1
        DORIS_CLOUD_DEFER {
7489
1
            stage_keys.clear();
7490
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7488
1
        DORIS_CLOUD_DEFER {
7489
1
            stage_keys.clear();
7490
1
        };
7491
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7492
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7493
0
            return -1;
7494
0
        }
7495
1
        return 0;
7496
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7486
1
    auto loop_done = [&stage_keys, this]() -> int {
7487
1
        if (stage_keys.empty()) return 0;
7488
1
        DORIS_CLOUD_DEFER {
7489
1
            stage_keys.clear();
7490
1
        };
7491
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7492
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7493
0
            return -1;
7494
0
        }
7495
1
        return 0;
7496
1
    };
7497
11
    if (config::enable_recycler_stats_metrics) {
7498
0
        scan_and_statistics_stage();
7499
0
    }
7500
    // recycle_func and loop_done for scan and recycle
7501
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7502
11
}
7503
7504
10
int InstanceRecycler::recycle_expired_stage_objects() {
7505
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7506
7507
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7508
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7509
7510
10
    DORIS_CLOUD_DEFER {
7511
10
        int64_t cost =
7512
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7513
10
        metrics_context.finish_report();
7514
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7515
10
                .tag("instance_id", instance_id_);
7516
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7510
10
    DORIS_CLOUD_DEFER {
7511
10
        int64_t cost =
7512
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7513
10
        metrics_context.finish_report();
7514
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7515
10
                .tag("instance_id", instance_id_);
7516
10
    };
7517
7518
10
    int ret = 0;
7519
7520
10
    if (config::enable_recycler_stats_metrics) {
7521
0
        scan_and_statistics_expired_stage_objects();
7522
0
    }
7523
7524
10
    for (const auto& stage : instance_info_.stages()) {
7525
0
        std::stringstream ss;
7526
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7527
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7528
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7529
0
           << ", prefix=" << stage.obj_info().prefix();
7530
7531
0
        if (stopped()) {
7532
0
            break;
7533
0
        }
7534
0
        if (stage.type() == StagePB::EXTERNAL) {
7535
0
            continue;
7536
0
        }
7537
0
        int idx = stoi(stage.obj_info().id());
7538
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7539
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7540
0
            continue;
7541
0
        }
7542
7543
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7544
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7545
0
        if (!s3_conf) {
7546
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7547
0
            continue;
7548
0
        }
7549
7550
0
        s3_conf->prefix = stage.obj_info().prefix();
7551
0
        std::shared_ptr<S3Accessor> accessor;
7552
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7553
0
        if (ret1 != 0) {
7554
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7555
0
            ret = -1;
7556
0
            continue;
7557
0
        }
7558
7559
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7560
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7561
0
            ret = -1;
7562
0
            continue;
7563
0
        }
7564
7565
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7566
0
        int64_t expiration_time =
7567
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7568
0
                config::internal_stage_objects_expire_time_second;
7569
0
        if (config::force_immediate_recycle) {
7570
0
            expiration_time = INT64_MAX;
7571
0
        }
7572
0
        ret1 = accessor->delete_all(expiration_time);
7573
0
        if (ret1 != 0) {
7574
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7575
0
                         << ss.str();
7576
0
            ret = -1;
7577
0
            continue;
7578
0
        }
7579
0
        metrics_context.total_recycled_num++;
7580
0
        metrics_context.report();
7581
0
    }
7582
10
    return ret;
7583
10
}
7584
7585
234
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7586
234
    std::lock_guard lock(recycle_tasks_mutex);
7587
234
    running_recycle_tasks[task_name] = start_time;
7588
234
}
7589
7590
234
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7591
234
    std::lock_guard lock(recycle_tasks_mutex);
7592
234
    DCHECK(running_recycle_tasks[task_name] > 0);
7593
234
    running_recycle_tasks.erase(task_name);
7594
234
}
7595
7596
21
bool InstanceRecycler::check_recycle_tasks() {
7597
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7598
21
    {
7599
21
        std::lock_guard lock(recycle_tasks_mutex);
7600
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7601
21
    }
7602
7603
21
    bool found = false;
7604
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7605
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7606
20
        int64_t cost = now - start_time;
7607
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7608
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7609
20
                    .tag("instance_id", instance_id_)
7610
20
                    .tag("task", task_name);
7611
20
            found = true;
7612
20
        }
7613
20
    }
7614
7615
21
    return found;
7616
21
}
7617
7618
// Scan and statistics indexes that need to be recycled
7619
0
int InstanceRecycler::scan_and_statistics_indexes() {
7620
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7621
7622
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7623
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7624
0
    std::string index_key0;
7625
0
    std::string index_key1;
7626
0
    recycle_index_key(index_key_info0, &index_key0);
7627
0
    recycle_index_key(index_key_info1, &index_key1);
7628
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7629
7630
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7631
0
        RecycleIndexPB index_pb;
7632
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7633
0
            return 0;
7634
0
        }
7635
0
        int64_t current_time = ::time(nullptr);
7636
0
        if (current_time <
7637
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7638
0
            return 0;
7639
0
        }
7640
        // decode index_id
7641
0
        auto k1 = k;
7642
0
        k1.remove_prefix(1);
7643
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7644
0
        decode_key(&k1, &out);
7645
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7646
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7647
0
        std::unique_ptr<Transaction> txn;
7648
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7649
0
        if (err != TxnErrorCode::TXN_OK) {
7650
0
            return 0;
7651
0
        }
7652
0
        std::string val;
7653
0
        err = txn->get(k, &val);
7654
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7655
0
            return 0;
7656
0
        }
7657
0
        if (err != TxnErrorCode::TXN_OK) {
7658
0
            return 0;
7659
0
        }
7660
0
        index_pb.Clear();
7661
0
        if (!index_pb.ParseFromString(val)) {
7662
0
            return 0;
7663
0
        }
7664
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7665
0
            return 0;
7666
0
        }
7667
0
        metrics_context.total_need_recycle_num++;
7668
0
        return 0;
7669
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_
7670
7671
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7672
0
    metrics_context.report(true);
7673
0
    segment_metrics_context_.report(true);
7674
0
    tablet_metrics_context_.report(true);
7675
0
    return ret;
7676
0
}
7677
7678
// Scan and statistics partitions that need to be recycled
7679
0
int InstanceRecycler::scan_and_statistics_partitions() {
7680
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7681
7682
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7683
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7684
0
    std::string part_key0;
7685
0
    std::string part_key1;
7686
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7687
7688
0
    recycle_partition_key(part_key_info0, &part_key0);
7689
0
    recycle_partition_key(part_key_info1, &part_key1);
7690
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7691
0
        RecyclePartitionPB part_pb;
7692
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7693
0
            return 0;
7694
0
        }
7695
0
        int64_t current_time = ::time(nullptr);
7696
0
        if (current_time <
7697
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7698
0
            return 0;
7699
0
        }
7700
        // decode partition_id
7701
0
        auto k1 = k;
7702
0
        k1.remove_prefix(1);
7703
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7704
0
        decode_key(&k1, &out);
7705
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7706
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7707
        // Change state to RECYCLING
7708
0
        std::unique_ptr<Transaction> txn;
7709
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7710
0
        if (err != TxnErrorCode::TXN_OK) {
7711
0
            return 0;
7712
0
        }
7713
0
        std::string val;
7714
0
        err = txn->get(k, &val);
7715
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7716
0
            return 0;
7717
0
        }
7718
0
        if (err != TxnErrorCode::TXN_OK) {
7719
0
            return 0;
7720
0
        }
7721
0
        part_pb.Clear();
7722
0
        if (!part_pb.ParseFromString(val)) {
7723
0
            return 0;
7724
0
        }
7725
        // Partitions with PREPARED state MUST have no data
7726
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7727
0
        int ret = 0;
7728
0
        for (int64_t index_id : part_pb.index_id()) {
7729
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7730
0
                                            partition_id, is_empty_tablet) != 0) {
7731
0
                ret = 0;
7732
0
            }
7733
0
        }
7734
0
        metrics_context.total_need_recycle_num++;
7735
0
        return ret;
7736
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_
7737
7738
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7739
0
    metrics_context.report(true);
7740
0
    segment_metrics_context_.report(true);
7741
0
    tablet_metrics_context_.report(true);
7742
0
    return ret;
7743
0
}
7744
7745
// Scan and statistics rowsets that need to be recycled
7746
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7747
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7748
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7749
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7750
0
    std::string recyc_rs_key0;
7751
0
    std::string recyc_rs_key1;
7752
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7753
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7754
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7755
7756
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7757
0
        RecycleRowsetPB rowset;
7758
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7759
0
            return 0;
7760
0
        }
7761
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7762
0
        int64_t current_time = ::time(nullptr);
7763
0
        if (current_time <
7764
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7765
0
            return 0;
7766
0
        }
7767
7768
0
        if (!rowset.has_type()) {
7769
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7770
0
                return 0;
7771
0
            }
7772
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7773
0
                return 0;
7774
0
            }
7775
0
            metrics_context.total_need_recycle_num++;
7776
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7777
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7778
0
            segment_metrics_context_.total_need_recycle_data_size +=
7779
0
                    rowset.rowset_meta().total_disk_size();
7780
0
            return 0;
7781
0
        }
7782
7783
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7784
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7785
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7786
0
            return 0;
7787
0
        }
7788
7789
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7790
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7791
0
                return 0;
7792
0
            }
7793
0
        }
7794
0
        metrics_context.total_need_recycle_num++;
7795
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7796
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7797
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7798
0
        return 0;
7799
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_
7800
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7801
0
    metrics_context.report(true);
7802
0
    segment_metrics_context_.report(true);
7803
0
    return ret;
7804
0
}
7805
7806
// Scan and statistics tmp_rowsets that need to be recycled
7807
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7808
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7809
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7810
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7811
0
    std::string tmp_rs_key0;
7812
0
    std::string tmp_rs_key1;
7813
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7814
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7815
7816
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7817
7818
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7819
0
        doris::RowsetMetaCloudPB rowset;
7820
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7821
0
            return 0;
7822
0
        }
7823
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7824
0
        int64_t current_time = ::time(nullptr);
7825
0
        if (current_time < expiration) {
7826
0
            return 0;
7827
0
        }
7828
7829
0
        DCHECK_GT(rowset.txn_id(), 0)
7830
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7831
7832
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
7833
0
            return 0;
7834
0
        }
7835
7836
0
        if (!rowset.has_resource_id()) {
7837
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7838
0
                return 0;
7839
0
            }
7840
0
            return 0;
7841
0
        }
7842
7843
0
        metrics_context.total_need_recycle_num++;
7844
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7845
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7846
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7847
0
        return 0;
7848
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_
7849
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7850
0
    metrics_context.report(true);
7851
0
    segment_metrics_context_.report(true);
7852
0
    return ret;
7853
0
}
7854
7855
// Scan and statistics abort_timeout_txn that need to be recycled
7856
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7857
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7858
7859
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7860
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7861
0
    std::string begin_txn_running_key;
7862
0
    std::string end_txn_running_key;
7863
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7864
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7865
7866
0
    int64_t current_time =
7867
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7868
7869
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7870
0
                                               std::string_view k, std::string_view v) -> int {
7871
0
        std::unique_ptr<Transaction> txn;
7872
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7873
0
        if (err != TxnErrorCode::TXN_OK) {
7874
0
            return 0;
7875
0
        }
7876
0
        std::string_view k1 = k;
7877
0
        k1.remove_prefix(1);
7878
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7879
0
        if (decode_key(&k1, &out) != 0) {
7880
0
            return 0;
7881
0
        }
7882
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7883
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7884
        // Update txn_info
7885
0
        std::string txn_inf_key, txn_inf_val;
7886
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7887
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7888
0
        if (err != TxnErrorCode::TXN_OK) {
7889
0
            return 0;
7890
0
        }
7891
0
        TxnInfoPB txn_info;
7892
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7893
0
            return 0;
7894
0
        }
7895
7896
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7897
0
            TxnRunningPB txn_running_pb;
7898
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7899
0
                return 0;
7900
0
            }
7901
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7902
0
                return 0;
7903
0
            }
7904
0
            metrics_context.total_need_recycle_num++;
7905
0
        }
7906
0
        return 0;
7907
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_
7908
7909
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7910
0
                               std::move(handle_abort_timeout_txn_kv));
7911
0
    metrics_context.report(true);
7912
0
    return ret;
7913
0
}
7914
7915
// Scan and statistics expired_txn_label that need to be recycled
7916
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7917
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7918
7919
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7920
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7921
0
    std::string begin_recycle_txn_key;
7922
0
    std::string end_recycle_txn_key;
7923
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7924
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7925
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7926
0
    int64_t current_time_ms =
7927
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7928
7929
    // for calculate the total num or bytes of recyled objects
7930
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7931
0
        RecycleTxnPB recycle_txn_pb;
7932
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7933
0
            return 0;
7934
0
        }
7935
0
        if ((config::force_immediate_recycle) ||
7936
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7937
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7938
0
             current_time_ms)) {
7939
0
            metrics_context.total_need_recycle_num++;
7940
0
        }
7941
0
        return 0;
7942
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_
7943
7944
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7945
0
                               std::move(handle_expired_txn_label_kv));
7946
0
    metrics_context.report(true);
7947
0
    return ret;
7948
0
}
7949
7950
// Scan and statistics copy_jobs that need to be recycled
7951
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7952
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7953
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7954
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7955
0
    std::string key0;
7956
0
    std::string key1;
7957
0
    copy_job_key(key_info0, &key0);
7958
0
    copy_job_key(key_info1, &key1);
7959
7960
    // for calculate the total num or bytes of recyled objects
7961
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7962
0
        CopyJobPB copy_job;
7963
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7964
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7965
0
            return 0;
7966
0
        }
7967
7968
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7969
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7970
0
                int64_t current_time =
7971
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7972
0
                if (copy_job.finish_time_ms() > 0) {
7973
0
                    if (!config::force_immediate_recycle &&
7974
0
                        current_time < copy_job.finish_time_ms() +
7975
0
                                               config::copy_job_max_retention_second * 1000) {
7976
0
                        return 0;
7977
0
                    }
7978
0
                } else {
7979
0
                    if (!config::force_immediate_recycle &&
7980
0
                        current_time < copy_job.start_time_ms() +
7981
0
                                               config::copy_job_max_retention_second * 1000) {
7982
0
                        return 0;
7983
0
                    }
7984
0
                }
7985
0
            }
7986
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7987
0
            int64_t current_time =
7988
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7989
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7990
0
                return 0;
7991
0
            }
7992
0
        }
7993
0
        metrics_context.total_need_recycle_num++;
7994
0
        return 0;
7995
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_
7996
7997
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7998
0
    metrics_context.report(true);
7999
0
    return ret;
8000
0
}
8001
8002
// Scan and statistics stage that need to be recycled
8003
0
int InstanceRecycler::scan_and_statistics_stage() {
8004
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8005
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8006
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8007
0
    std::string key0 = recycle_stage_key(key_info0);
8008
0
    std::string key1 = recycle_stage_key(key_info1);
8009
8010
    // for calculate the total num or bytes of recyled objects
8011
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8012
0
                                                        std::string_view v) -> int {
8013
0
        RecycleStagePB recycle_stage;
8014
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8015
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8016
0
            return 0;
8017
0
        }
8018
8019
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8020
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8021
0
            LOG(WARNING) << "invalid idx: " << idx;
8022
0
            return 0;
8023
0
        }
8024
8025
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8026
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8027
0
                [&] {
8028
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8029
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8030
0
                    if (!s3_conf) {
8031
0
                        return 0;
8032
0
                    }
8033
8034
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8035
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8036
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8037
0
                    if (ret != 0) {
8038
0
                        return 0;
8039
0
                    }
8040
8041
0
                    accessor = std::move(s3_accessor);
8042
0
                    return 0;
8043
0
                }(),
8044
0
                "recycle_stage:get_accessor", &accessor);
8045
8046
0
        if (ret != 0) {
8047
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8048
0
            return 0;
8049
0
        }
8050
8051
0
        metrics_context.total_need_recycle_num++;
8052
0
        return 0;
8053
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_
8054
8055
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8056
0
    metrics_context.report(true);
8057
0
    return ret;
8058
0
}
8059
8060
// Scan and statistics expired_stage_objects that need to be recycled
8061
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8062
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8063
8064
    // for calculate the total num or bytes of recyled objects
8065
0
    auto scan_and_statistics = [&metrics_context, this]() {
8066
0
        for (const auto& stage : instance_info_.stages()) {
8067
0
            if (stopped()) {
8068
0
                break;
8069
0
            }
8070
0
            if (stage.type() == StagePB::EXTERNAL) {
8071
0
                continue;
8072
0
            }
8073
0
            int idx = stoi(stage.obj_info().id());
8074
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8075
0
                continue;
8076
0
            }
8077
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8078
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8079
0
            if (!s3_conf) {
8080
0
                continue;
8081
0
            }
8082
0
            s3_conf->prefix = stage.obj_info().prefix();
8083
0
            std::shared_ptr<S3Accessor> accessor;
8084
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8085
0
            if (ret1 != 0) {
8086
0
                continue;
8087
0
            }
8088
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8089
0
                continue;
8090
0
            }
8091
0
            metrics_context.total_need_recycle_num++;
8092
0
        }
8093
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8094
8095
0
    scan_and_statistics();
8096
0
    metrics_context.report(true);
8097
0
    return 0;
8098
0
}
8099
8100
// Scan and statistics versions that need to be recycled
8101
0
int InstanceRecycler::scan_and_statistics_versions() {
8102
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8103
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8104
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8105
8106
0
    int64_t last_scanned_table_id = 0;
8107
0
    bool is_recycled = false; // Is last scanned kv recycled
8108
    // for calculate the total num or bytes of recyled objects
8109
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8110
0
                                       std::string_view k, std::string_view) {
8111
0
        auto k1 = k;
8112
0
        k1.remove_prefix(1);
8113
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8114
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8115
0
        decode_key(&k1, &out);
8116
0
        DCHECK_EQ(out.size(), 6) << k;
8117
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8118
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8119
0
            metrics_context.total_need_recycle_num +=
8120
0
                    is_recycled; // Version kv of this table has been recycled
8121
0
            return 0;
8122
0
        }
8123
0
        last_scanned_table_id = table_id;
8124
0
        is_recycled = false;
8125
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8126
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8127
0
        std::unique_ptr<Transaction> txn;
8128
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8129
0
        if (err != TxnErrorCode::TXN_OK) {
8130
0
            return 0;
8131
0
        }
8132
0
        std::unique_ptr<RangeGetIterator> iter;
8133
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8134
0
        if (err != TxnErrorCode::TXN_OK) {
8135
0
            return 0;
8136
0
        }
8137
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8138
0
            return 0;
8139
0
        }
8140
0
        metrics_context.total_need_recycle_num++;
8141
0
        is_recycled = true;
8142
0
        return 0;
8143
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_
8144
8145
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8146
0
    metrics_context.report(true);
8147
0
    return ret;
8148
0
}
8149
8150
// Scan and statistics restore jobs that need to be recycled
8151
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8152
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8153
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8154
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8155
0
    std::string restore_job_key0;
8156
0
    std::string restore_job_key1;
8157
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8158
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8159
8160
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8161
8162
    // for calculate the total num or bytes of recyled objects
8163
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8164
0
        RestoreJobCloudPB restore_job_pb;
8165
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8166
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8167
0
            return 0;
8168
0
        }
8169
0
        int64_t expiration =
8170
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8171
0
        int64_t current_time = ::time(nullptr);
8172
0
        if (current_time < expiration) { // not expired
8173
0
            return 0;
8174
0
        }
8175
0
        metrics_context.total_need_recycle_num++;
8176
0
        if (restore_job_pb.need_recycle_data()) {
8177
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8178
0
        }
8179
0
        return 0;
8180
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_
8181
8182
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8183
0
    metrics_context.report(true);
8184
0
    return ret;
8185
0
}
8186
8187
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8188
3
    if (!should_recycle_versioned_keys()) {
8189
0
        return;
8190
0
    }
8191
8192
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8193
8194
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8195
3
    if (recycle_checker.init() != 0) {
8196
0
        return;
8197
0
    }
8198
8199
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8200
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8201
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8202
8203
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8204
8
    for (; iter->valid(); iter->next()) {
8205
5
        OperationLogPB operation_log;
8206
5
        if (!iter->parse_value(&operation_log)) {
8207
0
            continue;
8208
0
        }
8209
8210
5
        std::string_view key = iter->key();
8211
5
        Versionstamp log_versionstamp;
8212
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8213
0
            continue;
8214
0
        }
8215
8216
5
        OperationLogReferenceInfo ref_info;
8217
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8218
5
                                        &ref_info)) {
8219
4
            metrics_context.total_need_recycle_num++;
8220
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8221
4
        }
8222
5
    }
8223
8224
3
    metrics_context.report(true);
8225
3
}
8226
8227
int InstanceRecycler::classify_rowset_task_by_ref_count(
8228
61
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8229
61
    constexpr int MAX_RETRY = 10;
8230
61
    const auto& rowset_meta = task.rowset_meta;
8231
61
    int64_t tablet_id = rowset_meta.tablet_id();
8232
61
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8233
61
    std::string_view reference_instance_id = instance_id_;
8234
61
    if (rowset_meta.has_reference_instance_id()) {
8235
5
        reference_instance_id = rowset_meta.reference_instance_id();
8236
5
    }
8237
8238
62
    for (int i = 0; i < MAX_RETRY; ++i) {
8239
62
        std::unique_ptr<Transaction> txn;
8240
62
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8241
62
        if (err != TxnErrorCode::TXN_OK) {
8242
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8243
0
                    .tag("instance_id", instance_id_)
8244
0
                    .tag("tablet_id", tablet_id)
8245
0
                    .tag("rowset_id", rowset_id)
8246
0
                    .tag("err", err);
8247
0
            return -1;
8248
0
        }
8249
8250
62
        std::string rowset_ref_count_key =
8251
62
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8252
62
        task.rowset_ref_count_key = rowset_ref_count_key;
8253
8254
62
        int64_t ref_count = 0;
8255
62
        {
8256
62
            std::string value;
8257
62
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8258
62
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8259
0
                ref_count = 1;
8260
62
            } else if (err != TxnErrorCode::TXN_OK) {
8261
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8262
0
                        .tag("instance_id", instance_id_)
8263
0
                        .tag("tablet_id", tablet_id)
8264
0
                        .tag("rowset_id", rowset_id)
8265
0
                        .tag("err", err);
8266
0
                return -1;
8267
62
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8268
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8269
0
                        .tag("instance_id", instance_id_)
8270
0
                        .tag("tablet_id", tablet_id)
8271
0
                        .tag("rowset_id", rowset_id)
8272
0
                        .tag("value", hex(value));
8273
0
                return -1;
8274
0
            }
8275
62
        }
8276
8277
62
        if (ref_count > 1) {
8278
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8279
12
            txn->atomic_add(rowset_ref_count_key, -1);
8280
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8281
12
                    .tag("instance_id", instance_id_)
8282
12
                    .tag("tablet_id", tablet_id)
8283
12
                    .tag("rowset_id", rowset_id)
8284
12
                    .tag("ref_count", ref_count - 1)
8285
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8286
8287
12
            if (!task.recycle_rowset_key.empty()) {
8288
0
                txn->remove(task.recycle_rowset_key);
8289
0
                LOG_INFO("remove recycle rowset key in classification phase")
8290
0
                        .tag("key", hex(task.recycle_rowset_key));
8291
0
            }
8292
12
            if (!task.non_versioned_rowset_key.empty()) {
8293
12
                txn->remove(task.non_versioned_rowset_key);
8294
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8295
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8296
12
            }
8297
8298
12
            err = txn->commit();
8299
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8300
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8301
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8302
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8303
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8304
1
                continue;
8305
11
            } else if (err != TxnErrorCode::TXN_OK) {
8306
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8307
0
                        .tag("instance_id", instance_id_)
8308
0
                        .tag("tablet_id", tablet_id)
8309
0
                        .tag("rowset_id", rowset_id)
8310
0
                        .tag("err", err);
8311
0
                return -1;
8312
0
            }
8313
11
            return 1; // handled, not added to batch delete
8314
50
        } else {
8315
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8316
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8317
50
            LOG_INFO("add rowset to batch delete plan")
8318
50
                    .tag("instance_id", instance_id_)
8319
50
                    .tag("tablet_id", tablet_id)
8320
50
                    .tag("rowset_id", rowset_id)
8321
50
                    .tag("resource_id", rowset_meta.resource_id())
8322
50
                    .tag("ref_count", ref_count);
8323
8324
50
            batch_delete_tasks.push_back(std::move(task));
8325
50
            return 0; // added to batch delete
8326
50
        }
8327
62
    }
8328
8329
0
    LOG_WARNING("failed to classify rowset task after retry")
8330
0
            .tag("instance_id", instance_id_)
8331
0
            .tag("tablet_id", tablet_id)
8332
0
            .tag("rowset_id", rowset_id)
8333
0
            .tag("retry", MAX_RETRY);
8334
0
    return -1;
8335
61
}
8336
8337
11
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8338
11
    int ret = 0;
8339
50
    for (const auto& task : tasks) {
8340
50
        int64_t tablet_id = task.rowset_meta.tablet_id();
8341
50
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8342
8343
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8344
        // so we don't need to call it again here.
8345
8346
        // Remove all metadata keys in one transaction
8347
50
        std::unique_ptr<Transaction> txn;
8348
50
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8349
50
        if (err != TxnErrorCode::TXN_OK) {
8350
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8351
0
                    .tag("instance_id", instance_id_)
8352
0
                    .tag("tablet_id", tablet_id)
8353
0
                    .tag("rowset_id", rowset_id)
8354
0
                    .tag("err", err);
8355
0
            ret = -1;
8356
0
            continue;
8357
0
        }
8358
8359
50
        std::string_view reference_instance_id = instance_id_;
8360
50
        if (task.rowset_meta.has_reference_instance_id()) {
8361
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
8362
5
        }
8363
8364
50
        txn->remove(task.rowset_ref_count_key);
8365
50
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8366
50
                .tag("instance_id", instance_id_)
8367
50
                .tag("tablet_id", tablet_id)
8368
50
                .tag("rowset_id", rowset_id)
8369
50
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8370
8371
50
        std::string dbm_start_key =
8372
50
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8373
50
        std::string dbm_end_key = meta_delete_bitmap_key(
8374
50
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8375
50
                 std::numeric_limits<int64_t>::max()});
8376
50
        txn->remove(dbm_start_key, dbm_end_key);
8377
50
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8378
50
                .tag("instance_id", instance_id_)
8379
50
                .tag("tablet_id", tablet_id)
8380
50
                .tag("rowset_id", rowset_id)
8381
50
                .tag("begin", hex(dbm_start_key))
8382
50
                .tag("end", hex(dbm_end_key));
8383
8384
50
        std::string versioned_dbm_start_key =
8385
50
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8386
50
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8387
50
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8388
50
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8389
50
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8390
50
                .tag("instance_id", instance_id_)
8391
50
                .tag("tablet_id", tablet_id)
8392
50
                .tag("rowset_id", rowset_id)
8393
50
                .tag("begin", hex(versioned_dbm_start_key))
8394
50
                .tag("end", hex(versioned_dbm_end_key));
8395
8396
        // Remove versioned meta rowset key
8397
50
        if (!task.versioned_rowset_key.empty()) {
8398
50
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8399
50
                                                          task.versionstamp);
8400
50
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8401
50
                    .tag("instance_id", instance_id_)
8402
50
                    .tag("tablet_id", tablet_id)
8403
50
                    .tag("rowset_id", rowset_id)
8404
50
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8405
50
        }
8406
8407
50
        if (!task.non_versioned_rowset_key.empty()) {
8408
50
            txn->remove(task.non_versioned_rowset_key);
8409
50
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8410
50
                    .tag("instance_id", instance_id_)
8411
50
                    .tag("tablet_id", tablet_id)
8412
50
                    .tag("rowset_id", rowset_id)
8413
50
                    .tag("key", hex(task.non_versioned_rowset_key));
8414
50
        }
8415
8416
        // Remove recycle_rowset_key last to ensure retry safety:
8417
        // if cleanup fails, this key remains and triggers next round retry.
8418
50
        if (!task.recycle_rowset_key.empty()) {
8419
0
            txn->remove(task.recycle_rowset_key);
8420
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8421
0
                    .tag("instance_id", instance_id_)
8422
0
                    .tag("tablet_id", tablet_id)
8423
0
                    .tag("rowset_id", rowset_id)
8424
0
                    .tag("key", hex(task.recycle_rowset_key));
8425
0
        }
8426
8427
50
        err = txn->commit();
8428
50
        if (err != TxnErrorCode::TXN_OK) {
8429
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8430
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8431
0
                    .tag("instance_id", instance_id_)
8432
0
                    .tag("tablet_id", tablet_id)
8433
0
                    .tag("rowset_id", rowset_id)
8434
0
                    .tag("err", err);
8435
0
            ret = -1;
8436
0
            continue;
8437
0
        }
8438
8439
50
        LOG_INFO("cleanup rowset metadata success")
8440
50
                .tag("instance_id", instance_id_)
8441
50
                .tag("tablet_id", tablet_id)
8442
50
                .tag("rowset_id", rowset_id);
8443
50
    }
8444
11
    return ret;
8445
11
}
8446
8447
} // namespace doris::cloud