Coverage Report

Created: 2026-10-14 19:35

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