Coverage Report

Created: 2026-10-28 17:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <utility>
46
#include <variant>
47
48
#include "common/defer.h"
49
#include "common/stopwatch.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_helper.h"
52
#include "meta-service/meta_service_schema.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/meta_reader.h"
55
#include "meta-store/txn_kv.h"
56
#include "meta-store/txn_kv_error.h"
57
#include "meta-store/versioned_value.h"
58
#include "recycler/checker.h"
59
#ifdef ENABLE_HDFS_STORAGE_VAULT
60
#include "recycler/hdfs_accessor.h"
61
#endif
62
#include "recycler/s3_accessor.h"
63
#include "recycler/storage_vault_accessor.h"
64
#ifdef UNIT_TEST
65
#include "../test/mock_accessor.h"
66
#endif
67
#include "common/bvars.h"
68
#include "common/config.h"
69
#include "common/encryption_util.h"
70
#include "common/logging.h"
71
#include "common/simple_thread_pool.h"
72
#include "common/util.h"
73
#include "cpp/sync_point.h"
74
#include "meta-store/codec.h"
75
#include "meta-store/document_message.h"
76
#include "meta-store/keys.h"
77
#include "recycler/recycler_service.h"
78
#include "recycler/sync_executor.h"
79
#include "recycler/util.h"
80
#include "snapshot/snapshot_manager_factory.h"
81
82
namespace doris::cloud {
83
84
using namespace std::chrono;
85
86
namespace {
87
88
constexpr size_t kRowsetBatchGetSize = 256;
89
90
0
int64_t packed_file_retry_sleep_ms() {
91
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
92
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
93
0
    thread_local std::mt19937_64 gen(std::random_device {}());
94
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
95
0
    return dist(gen);
96
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
97
98
0
void sleep_for_packed_file_retry() {
99
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
100
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
101
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
102
37
bool filter_out_instance(const std::string& instance_id) {
103
37
    if (config::recycle_whitelist.empty()) {
104
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
105
35
               config::recycle_blacklist.end();
106
35
    }
107
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
108
2
           config::recycle_whitelist.end();
109
37
}
110
111
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
948k
    const auto& locations = rowset.packed_slice_locations();
113
948k
    auto it = locations.find(path);
114
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
948k
           !it->second.packed_file_path().empty();
116
948k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
7
    const auto& locations = rowset.packed_slice_locations();
113
7
    auto it = locations.find(path);
114
7
    return it != locations.end() && it->second.has_packed_file_path() &&
115
7
           !it->second.packed_file_path().empty();
116
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
111
948k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
112
948k
    const auto& locations = rowset.packed_slice_locations();
113
948k
    auto it = locations.find(path);
114
948k
    return it != locations.end() && it->second.has_packed_file_path() &&
115
948k
           !it->second.packed_file_path().empty();
116
948k
}
117
118
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
119
                                      const std::string& path,
120
949k
                                      std::vector<std::string>* file_paths) {
121
949k
    if (!is_packed_slice_path(rowset, path)) {
122
920k
        file_paths->push_back(path);
123
920k
    }
124
949k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
7
                                      std::vector<std::string>* file_paths) {
121
7
    if (!is_packed_slice_path(rowset, path)) {
122
7
        file_paths->push_back(path);
123
7
    }
124
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
120
949k
                                      std::vector<std::string>* file_paths) {
121
949k
    if (!is_packed_slice_path(rowset, path)) {
122
920k
        file_paths->push_back(path);
123
920k
    }
124
949k
}
125
126
} // namespace
127
128
// return 0 for success get a key, 1 for key not found, negative for error
129
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
687
                   std::unique_ptr<RangeGetIterator>& it) {
148
687
    std::unique_ptr<Transaction> txn;
149
687
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
687
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
687
    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
687
    };
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
656
                   std::unique_ptr<RangeGetIterator>& it) {
148
656
    std::unique_ptr<Transaction> txn;
149
656
    TxnErrorCode err = txn_kv->create_txn(&txn);
150
656
    if (err != TxnErrorCode::TXN_OK) {
151
0
        return -1;
152
0
    }
153
656
    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
656
    };
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
742
    while (!stopped()) {
329
737
        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
733
        } else {
352
733
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
353
733
        }
354
737
        {
355
737
            std::unique_lock lock(mtx_);
356
737
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
357
1.47k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
357
1.47k
                               [&]() { return stopped(); });
358
737
        }
359
737
    }
360
5
}
361
362
9
void Recycler::recycle_callback() {
363
40
    while (!stopped()) {
364
37
        InstanceInfoPB instance;
365
37
        {
366
37
            std::unique_lock lock(mtx_);
367
37
            pending_instance_cond_.wait(
368
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
368
49
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
369
37
            if (stopped()) {
370
6
                return;
371
6
            }
372
31
            instance = std::move(pending_instance_queue_.front());
373
31
            pending_instance_queue_.pop_front();
374
31
            pending_instance_set_.erase(instance.instance_id());
375
31
        }
376
0
        auto& instance_id = instance.instance_id();
377
31
        {
378
31
            std::lock_guard lock(mtx_);
379
            // skip instance in recycling
380
31
            if (recycling_instance_map_.count(instance_id)) continue;
381
31
        }
382
31
        if (!config::enable_recycler) {
383
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
384
1
                         << " since enable_recycler is false";
385
1
            continue;
386
1
        }
387
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
388
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
389
390
30
        if (int r = instance_recycler->init(); r != 0) {
391
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
392
0
                         << " ret=" << r;
393
0
            continue;
394
0
        }
395
30
        std::string recycle_job_key;
396
30
        job_recycle_key({instance_id}, &recycle_job_key);
397
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
398
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
399
30
        if (ret != 0) { // Prepare failed
400
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
401
20
                         << " ret=" << ret;
402
20
            continue;
403
20
        } else {
404
10
            std::lock_guard lock(mtx_);
405
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
406
10
        }
407
10
        if (stopped()) return;
408
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
409
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
410
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
411
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
412
10
        ret = instance_recycler->do_recycle();
413
        // If instance recycler has been aborted, don't finish this job
414
415
10
        if (!instance_recycler->stopped()) {
416
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
417
10
                                        ret == 0, ctime_ms);
418
10
        }
419
10
        if (instance_recycler->stopped() || ret != 0) {
420
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
421
0
        }
422
10
        {
423
10
            std::lock_guard lock(mtx_);
424
10
            recycling_instance_map_.erase(instance_id);
425
10
        }
426
427
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
428
10
        auto elpased_ms = now - ctime_ms;
429
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
430
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
431
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
432
10
                                             now + config::recycle_interval_seconds * 1000);
433
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
434
10
        LOG(INFO) << "recycle instance done, "
435
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
436
10
                  << " now: " << now;
437
438
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
439
440
10
        LOG_WARNING("finish recycle instance")
441
10
                .tag("instance_id", instance_id)
442
10
                .tag("cost_ms", elpased_ms);
443
10
    }
444
9
}
445
446
4
void Recycler::lease_recycle_jobs() {
447
54
    while (!stopped()) {
448
50
        std::vector<std::string> instances;
449
50
        instances.reserve(recycling_instance_map_.size());
450
50
        {
451
50
            std::lock_guard lock(mtx_);
452
50
            for (auto& [id, _] : recycling_instance_map_) {
453
30
                instances.push_back(id);
454
30
            }
455
50
        }
456
50
        for (auto& i : instances) {
457
30
            std::string recycle_job_key;
458
30
            job_recycle_key({i}, &recycle_job_key);
459
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
460
30
            if (ret == 1) {
461
0
                std::lock_guard lock(mtx_);
462
0
                if (auto it = recycling_instance_map_.find(i);
463
0
                    it != recycling_instance_map_.end()) {
464
0
                    it->second->stop();
465
0
                }
466
0
            }
467
30
        }
468
50
        {
469
50
            std::unique_lock lock(mtx_);
470
50
            notifier_.wait_for(lock,
471
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
472
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
472
100
                               [&]() { return stopped(); });
473
50
        }
474
50
    }
475
4
}
476
477
4
void Recycler::check_recycle_tasks() {
478
7
    while (!stopped()) {
479
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
480
3
        {
481
3
            std::lock_guard lock(mtx_);
482
3
            recycling_instance_map = recycling_instance_map_;
483
3
        }
484
3
        for (auto& entry : recycling_instance_map) {
485
0
            entry.second->check_recycle_tasks();
486
0
        }
487
488
3
        std::unique_lock lock(mtx_);
489
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
490
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
490
6
                           [&]() { return stopped(); });
491
3
    }
492
4
}
493
494
4
int Recycler::start(brpc::Server* server) {
495
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
496
4
    S3Environment::getInstance();
497
498
4
    if (config::enable_checker) {
499
0
        checker_ = std::make_unique<Checker>(txn_kv_);
500
0
        int ret = checker_->start();
501
0
        std::string msg;
502
0
        if (ret != 0) {
503
0
            msg = "failed to start checker";
504
0
            LOG(ERROR) << msg;
505
0
            std::cerr << msg << std::endl;
506
0
            return ret;
507
0
        }
508
0
        msg = "checker started";
509
0
        LOG(INFO) << msg;
510
0
        std::cout << msg << std::endl;
511
0
    }
512
513
4
    if (server) {
514
        // Add service
515
1
        auto recycler_service =
516
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
517
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
518
1
    }
519
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
520
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
521
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
522
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
522
8
        workers_.emplace_back([this] { recycle_callback(); });
523
8
    }
524
525
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
526
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
527
528
4
    if (config::enable_snapshot_data_migrator) {
529
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
530
0
        int ret = snapshot_data_migrator_->start();
531
0
        if (ret != 0) {
532
0
            LOG(ERROR) << "failed to start snapshot data migrator";
533
0
            return ret;
534
0
        }
535
0
        LOG(INFO) << "snapshot data migrator started";
536
0
    }
537
538
4
    if (config::enable_snapshot_chain_compactor) {
539
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
540
0
        int ret = snapshot_chain_compactor_->start();
541
0
        if (ret != 0) {
542
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
543
0
            return ret;
544
0
        }
545
0
        LOG(INFO) << "snapshot chain compactor started";
546
0
    }
547
548
4
    return 0;
549
4
}
550
551
4
void Recycler::stop() {
552
4
    stopped_ = true;
553
4
    notifier_.notify_all();
554
4
    pending_instance_cond_.notify_all();
555
4
    {
556
4
        std::lock_guard lock(mtx_);
557
4
        for (auto& [_, recycler] : recycling_instance_map_) {
558
0
            recycler->stop();
559
0
        }
560
4
    }
561
20
    for (auto& w : workers_) {
562
20
        if (w.joinable()) w.join();
563
20
    }
564
4
    if (checker_) {
565
0
        checker_->stop();
566
0
    }
567
4
    if (snapshot_data_migrator_) {
568
0
        snapshot_data_migrator_->stop();
569
0
    }
570
4
    if (snapshot_chain_compactor_) {
571
0
        snapshot_chain_compactor_->stop();
572
0
    }
573
4
}
574
575
class InstanceRecycler::InvertedIndexIdCache {
576
public:
577
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
578
172
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
579
580
    // Return 0 if success, 1 if schema kv not found, negative for error
581
    // For the same index_id, schema_version, res, since `get` is not completely atomic
582
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
583
    // resulting in repeated addition and inaccuracy.
584
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
585
    // repeated addition does not affect correctness.
586
68.3k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
587
68.3k
        {
588
68.3k
            std::lock_guard lock(mtx_);
589
68.3k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
590
4.67k
                return 0;
591
4.67k
            }
592
63.6k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
593
63.6k
                it != inverted_index_id_map_.end()) {
594
53.1k
                res = it->second;
595
53.1k
                return 0;
596
53.1k
            }
597
63.6k
        }
598
        // Get schema from kv
599
        // TODO(plat1ko): Single flight
600
10.4k
        std::unique_ptr<Transaction> txn;
601
10.4k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
602
10.4k
        if (err != TxnErrorCode::TXN_OK) {
603
0
            LOG(WARNING) << "failed to create txn, err=" << err;
604
0
            return -1;
605
0
        }
606
10.4k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
607
10.4k
        ValueBuf val_buf;
608
10.4k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
609
10.4k
        if (err != TxnErrorCode::TXN_OK) {
610
5.50k
            LOG(WARNING) << "failed to get schema, err=" << err;
611
5.50k
            return static_cast<int>(err);
612
5.50k
        }
613
4.96k
        doris::TabletSchemaCloudPB schema;
614
4.96k
        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.96k
        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.96k
        insert(index_id, schema_version, res);
632
4.96k
        return 0;
633
4.96k
    }
634
635
    // Empty `ids` means this schema has no inverted index
636
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
637
5.04k
        if (index_info.second.empty()) {
638
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
639
1.02k
            std::lock_guard lock(mtx_);
640
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
641
4.01k
        } else {
642
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
643
4.01k
            std::lock_guard lock(mtx_);
644
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
645
4.01k
        }
646
5.04k
    }
647
648
private:
649
    std::string instance_id_;
650
    std::shared_ptr<TxnKv> txn_kv_;
651
652
    std::mutex mtx_;
653
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
654
    struct HashOfKey {
655
137k
        size_t operator()(const Key& key) const {
656
137k
            size_t seed = 0;
657
137k
            seed = std::hash<int64_t> {}(key.first);
658
137k
            seed = std::hash<int32_t> {}(key.second);
659
137k
            return seed;
660
137k
        }
661
    };
662
    // <index_id, schema_version> -> inverted_index_ids
663
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
664
    // Store <index_id, schema_version> of schema which doesn't have inverted index
665
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
666
};
667
668
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
669
                                   RecyclerThreadPoolGroup thread_pool_group,
670
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
671
172
        : txn_kv_(std::move(txn_kv)),
672
172
          instance_id_(instance.instance_id()),
673
172
          instance_info_(instance),
674
172
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
675
172
          _thread_pool_group(std::move(thread_pool_group)),
676
172
          txn_lazy_committer_(std::move(txn_lazy_committer)),
677
172
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
678
172
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
679
172
    delete_bitmap_lock_white_list_->init();
680
172
    resource_mgr_->init();
681
682
172
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
683
684
    // Since the recycler's resource manager could not be notified when instance info changes,
685
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
686
172
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
687
172
};
688
689
172
InstanceRecycler::~InstanceRecycler() = default;
690
691
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
148
int InstanceRecycler::init_storage_vault_accessors() {
717
148
    if (instance_info_.resource_ids().empty()) {
718
141
        return 0;
719
141
    }
720
721
7
    FullRangeGetOptions opts(txn_kv_);
722
7
    opts.prefetch = true;
723
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
724
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
725
726
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
727
18
        auto [k, v] = *kv;
728
18
        StorageVaultPB vault;
729
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
730
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
731
0
            return -1;
732
0
        }
733
18
        std::string recycler_storage_vault_white_list = accumulate(
734
18
                config::recycler_storage_vault_white_list.begin(),
735
18
                config::recycler_storage_vault_white_list.end(), std::string(),
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
736
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
737
18
        LOG_INFO("config::recycler_storage_vault_white_list")
738
18
                .tag("", recycler_storage_vault_white_list);
739
18
        if (!config::recycler_storage_vault_white_list.empty()) {
740
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
741
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
742
8
                it == config::recycler_storage_vault_white_list.end()) {
743
2
                LOG_WARNING(
744
2
                        "failed to init accessor for vault because this vault is not in "
745
2
                        "config::recycler_storage_vault_white_list. ")
746
2
                        .tag(" vault name:", vault.name())
747
2
                        .tag(" config::recycler_storage_vault_white_list:",
748
2
                             recycler_storage_vault_white_list);
749
2
                continue;
750
2
            }
751
8
        }
752
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
753
16
                                 &accessor_map_, &vault);
754
16
        if (vault.has_hdfs_info()) {
755
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
756
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
757
9
            int ret = accessor->init();
758
9
            if (ret != 0) {
759
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
760
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
761
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
762
4
                continue;
763
4
            }
764
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
765
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
766
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
767
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
768
#else
769
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
770
                       << "but HDFS storage vaults were detected";
771
#endif
772
7
        } else if (vault.has_obj_info()) {
773
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
774
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
775
7
            if (!s3_conf) {
776
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
777
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
778
1
                continue;
779
1
            }
780
781
6
            std::shared_ptr<S3Accessor> accessor;
782
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
783
6
            if (ret != 0) {
784
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
785
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
786
0
                             << " ret=" << ret
787
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
788
0
                continue;
789
0
            }
790
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
791
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
792
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
793
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
794
6
        }
795
16
    }
796
797
7
    if (!it->is_valid()) {
798
0
        LOG_WARNING("failed to get storage vault kv");
799
0
        return -1;
800
0
    }
801
802
7
    if (accessor_map_.empty()) {
803
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
804
1
        return -2;
805
1
    }
806
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
807
6
             instance_id_);
808
809
6
    return 0;
810
7
}
811
812
148
int InstanceRecycler::init() {
813
148
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
814
148
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
815
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
816
1
        return 0;
817
1
    }
818
819
147
    int ret = init_obj_store_accessors();
820
147
    if (ret != 0) {
821
0
        return ret;
822
0
    }
823
824
147
    return init_storage_vault_accessors();
825
147
}
826
827
template <typename... Func>
828
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
120
    return [funcs...]() {
830
120
        return [](std::initializer_list<int> ret_vals) {
831
120
            int i = 0;
832
140
            for (int ret : ret_vals) {
833
140
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
140
            }
837
120
            return i;
838
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
20
            for (int ret : ret_vals) {
833
20
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
20
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
20
            for (int ret : ret_vals) {
833
20
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
20
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
0
                    i = ret;
835
0
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
828
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
829
10
    return [funcs...]() {
830
10
        return [](std::initializer_list<int> ret_vals) {
831
10
            int i = 0;
832
10
            for (int ret : ret_vals) {
833
10
                if (ret != 0) {
834
10
                    i = ret;
835
10
                }
836
10
            }
837
10
            return i;
838
10
        }({funcs()...});
839
10
    };
840
10
}
841
842
11
int InstanceRecycler::do_recycle() {
843
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
844
11
    tablet_metrics_context_.reset();
845
11
    segment_metrics_context_.reset();
846
11
    DORIS_CLOUD_DEFER {
847
11
        tablet_metrics_context_.finish_report();
848
11
        segment_metrics_context_.finish_report();
849
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
846
11
    DORIS_CLOUD_DEFER {
847
11
        tablet_metrics_context_.finish_report();
848
11
        segment_metrics_context_.finish_report();
849
11
    };
850
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
851
1
        int res = recycle_cluster_snapshots();
852
1
        if (res != 0) {
853
0
            return -1;
854
0
        }
855
1
        return recycle_deleted_instance();
856
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
857
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
858
10
                                        fmt::format("instance id {}", instance_id_),
859
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
859
120
                                        [](int r) { return r != 0; });
860
10
        sync_executor
861
10
                .add(task_wrapper(
862
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
862
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
863
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
863
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
864
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
865
                                   // becase they may both recycle the same set of tablets
866
                        // recycle dropped table or idexes(mv, rollup)
867
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
867
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
868
                        // recycle dropped partitions
869
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
869
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
870
10
                .add(task_wrapper(
871
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
871
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
872
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
872
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
873
10
                .add(task_wrapper(
874
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
874
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
876
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
877
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
877
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
878
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
879
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
879
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
880
10
                .add(task_wrapper(
881
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
881
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
882
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
883
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
883
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
884
10
        bool finished = true;
885
10
        std::vector<int> rets = sync_executor.when_all(&finished);
886
120
        for (int ret : rets) {
887
120
            if (ret != 0) {
888
0
                return ret;
889
0
            }
890
120
        }
891
10
        return finished ? 0 : -1;
892
10
    } else {
893
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
894
0
                     << " instance_id=" << instance_id_;
895
0
        return -1;
896
0
    }
897
11
}
898
899
/**
900
* 1. delete all remote data
901
* 2. delete all kv
902
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
903
*/
904
13
int InstanceRecycler::recycle_deleted_instance() {
905
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
906
907
13
    int ret = 0;
908
13
    auto start_time = steady_clock::now();
909
13
    const auto recycle_state = instance_info_.recycle_state();
910
911
13
    if (config::retain_deleted_instance_tombstone &&
912
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
913
4
        return 0;
914
4
    }
915
916
9
    DORIS_CLOUD_DEFER {
917
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
918
9
        if (ret != 0) {
919
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
920
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
921
0
                         << "s, instance_id=" << instance_id_;
922
9
        } else if (recycle_state ==
923
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
924
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
925
0
                      << "s, instance_id=" << instance_id_;
926
9
        } else {
927
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
928
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
929
9
                      << "s, instance_id=" << instance_id_;
930
9
        }
931
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
916
9
    DORIS_CLOUD_DEFER {
917
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
918
9
        if (ret != 0) {
919
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
920
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
921
0
                         << "s, instance_id=" << instance_id_;
922
9
        } else if (recycle_state ==
923
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
924
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
925
0
                      << "s, instance_id=" << instance_id_;
926
9
        } else {
927
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
928
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
929
9
                      << "s, instance_id=" << instance_id_;
930
9
        }
931
9
    };
932
933
9
    switch (recycle_state) {
934
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
935
6
        ret = recycle_deleted_instance_data();
936
6
        break;
937
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
938
3
        ret = recycle_deleted_instance_metadata();
939
3
        break;
940
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
941
0
        ret = remove_instance_key();
942
0
        break;
943
0
    default:
944
0
        LOG_WARNING("invalid instance recycle state")
945
0
                .tag("instance_id", instance_id_)
946
0
                .tag("recycle_state", instance_info_.recycle_state());
947
0
        ret = -1;
948
0
        break;
949
9
    }
950
951
9
    return ret;
952
9
}
953
954
6
int InstanceRecycler::recycle_deleted_instance_data() {
955
6
    int ret = 0;
956
957
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
958
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
959
6
        int res = recycle_tmp_rowsets();
960
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
961
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
962
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
963
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
964
            // and cannot be recycled.
965
0
            res = recycle_tmp_rowsets();
966
0
        }
967
6
        return res;
968
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
958
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
959
6
        int res = recycle_tmp_rowsets();
960
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
961
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
962
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
963
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
964
            // and cannot be recycled.
965
0
            res = recycle_tmp_rowsets();
966
0
        }
967
6
        return res;
968
6
    };
969
970
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
971
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
972
0
        return -1;
973
0
    }
974
975
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
976
6
    if (recycle_versioned_rowsets() != 0) {
977
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
978
0
        return -1;
979
0
    }
980
981
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
982
6
    if (recycle_operation_logs() != 0) {
983
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
984
0
        return -1;
985
0
    }
986
987
    // Step 4: Check if there are still cluster snapshots
988
6
    bool has_snapshots = false;
989
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
990
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
991
0
        return -1;
992
6
    } else if (has_snapshots) {
993
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
994
1
        return 0;
995
1
    }
996
997
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
998
5
                            instance_info().snapshot_switch_status() !=
999
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1000
5
    if (snapshot_enabled) {
1001
1
        bool has_unrecycled_rowsets = false;
1002
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1003
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1004
0
            return -1;
1005
1
        } else if (has_unrecycled_rowsets) {
1006
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1007
0
                    .tag("instance_id", instance_id_);
1008
0
            return ret;
1009
0
        }
1010
4
    } else { // delete all remote data if snapshot is disabled
1011
4
        for (auto& [_, accessor] : accessor_map_) {
1012
4
            if (stopped()) {
1013
0
                return ret;
1014
0
            }
1015
1016
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1017
4
            int del_ret = accessor->delete_all();
1018
4
            if (del_ret == 0) {
1019
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1020
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1021
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1022
                // so the recycling has been successful.
1023
0
                ret = -1;
1024
0
            }
1025
4
        }
1026
1027
4
        if (ret != 0) {
1028
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1029
0
            return ret;
1030
0
        }
1031
4
    }
1032
1033
5
    if (update_instance_recycle_state(
1034
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1035
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1036
0
        return -1;
1037
0
    }
1038
1039
5
    return 0;
1040
5
}
1041
1042
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1043
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1044
7
    if (instance_info_.has_successor_instance_id() &&
1045
7
        !instance_info_.successor_instance_id().empty()) {
1046
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1047
4
        std::unique_ptr<Transaction> txn;
1048
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1049
4
        if (err != TxnErrorCode::TXN_OK) {
1050
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1051
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1052
0
                         << " err=" << err;
1053
0
            return -1;
1054
0
        }
1055
1056
4
        InstanceInfoPB successor_instance;
1057
4
        std::string value;
1058
4
        err = txn->get(key, &value);
1059
4
        if (err == TxnErrorCode::TXN_OK) {
1060
3
            InstanceInfoPB successor_instance;
1061
3
            if (!successor_instance.ParseFromString(value)) {
1062
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1063
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1064
0
                return -1;
1065
0
            }
1066
3
            if (!successor_instance.has_recycle_state() ||
1067
3
                successor_instance.recycle_state() !=
1068
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1069
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1070
2
                          << " instance_id=" << instance_id_
1071
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1072
2
                          << " successor_status=" << successor_instance.status()
1073
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1074
2
                return 0;
1075
2
            }
1076
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1077
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1078
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1079
0
                         << " err=" << err;
1080
0
            return -1;
1081
0
        }
1082
4
    }
1083
1084
    // delete all kv
1085
5
    std::unique_ptr<Transaction> txn;
1086
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1087
5
    if (err != TxnErrorCode::TXN_OK) {
1088
0
        LOG(WARNING) << "failed to create txn";
1089
0
        return -1;
1090
0
    }
1091
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1092
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1093
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1094
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1095
5
    txn->remove(start_txn_key, end_txn_key);
1096
5
    std::string start_version_key = version_key_prefix(instance_id_);
1097
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1098
5
    txn->remove(start_version_key, end_version_key);
1099
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1100
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1101
5
    txn->remove(start_meta_key, end_meta_key);
1102
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1103
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1104
5
    txn->remove(start_recycle_key, end_recycle_key);
1105
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1106
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1107
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1108
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1109
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1110
5
    txn->remove(start_copy_key, end_copy_key);
1111
    // should not remove job key range, because we need to reserve job recycle kv
1112
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1113
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1114
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1115
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1116
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1117
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1118
5
    std::string start_vault_key = storage_vault_key(key_info0);
1119
5
    std::string end_vault_key = storage_vault_key(key_info1);
1120
5
    txn->remove(start_vault_key, end_vault_key);
1121
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1122
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1123
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1124
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1125
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1126
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1127
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1128
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1129
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1130
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1131
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1132
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1133
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1134
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1135
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1136
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1137
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1138
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1139
1140
    // Updating the recycle state also commits this transaction, making the metadata deletions
1141
    // and state transition atomic.
1142
5
    if (update_instance_recycle_state(
1143
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1144
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1145
0
        return -1;
1146
0
    }
1147
1148
5
    return 0;
1149
5
}
1150
1151
0
int InstanceRecycler::remove_instance_key() {
1152
0
    std::unique_ptr<Transaction> txn;
1153
0
    std::string key = instance_key(instance_info_.instance_id());
1154
0
    std::string value;
1155
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1156
0
    if (err != TxnErrorCode::TXN_OK) {
1157
0
        LOG(WARNING) << "failed to create txn";
1158
0
        return -1;
1159
0
    }
1160
1161
0
    err = txn->get(key, &value);
1162
0
    if (err != TxnErrorCode::TXN_OK) {
1163
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1164
0
                     << ", err=" << err;
1165
0
        return -1;
1166
0
    }
1167
1168
0
    InstanceInfoPB instance;
1169
0
    if (!instance.ParseFromString(value)) {
1170
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1171
0
        return -1;
1172
0
    }
1173
1174
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1175
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1176
0
                     << instance_id_ << ", status=" << instance.status();
1177
0
        return -1;
1178
0
    }
1179
1180
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1181
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1182
0
                     << instance_id_
1183
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1184
0
                     << ", expected_state="
1185
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1186
0
        return -1;
1187
0
    }
1188
1189
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1190
0
    txn->remove(key);
1191
0
    err = txn->commit();
1192
0
    if (err != TxnErrorCode::TXN_OK) {
1193
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1194
0
                     << " err=" << err;
1195
0
        return -1;
1196
0
    }
1197
0
    return 0;
1198
0
}
1199
1200
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1201
7
                                                    InstanceRecycleState target_state) {
1202
7
    std::unique_ptr<Transaction> txn;
1203
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1204
7
    if (err != TxnErrorCode::TXN_OK) {
1205
0
        LOG(WARNING) << "failed to create txn";
1206
0
        return -1;
1207
0
    }
1208
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1209
7
}
1210
1211
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1212
                                                    InstanceRecycleState target_state,
1213
12
                                                    Transaction* txn) {
1214
12
    const bool valid_transition =
1215
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1216
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1217
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1218
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1219
1220
12
    if (!valid_transition) {
1221
1
        LOG_WARNING("invalid instance recycled state transition")
1222
1
                .tag("instance_id", instance_id_)
1223
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1224
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1225
1
        return -1;
1226
1
    }
1227
1228
11
    std::string key = instance_key({instance_id_});
1229
11
    std::string value;
1230
11
    TxnErrorCode err = txn->get(key, &value);
1231
11
    if (err != TxnErrorCode::TXN_OK) {
1232
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1233
0
                .tag("instance_id", instance_id_)
1234
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1235
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1236
0
                .tag("err", err);
1237
0
        return -1;
1238
0
    }
1239
1240
11
    InstanceInfoPB instance;
1241
11
    if (!instance.ParseFromString(value)) {
1242
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1243
0
                .tag("instance_id", instance_id_)
1244
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1245
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1246
0
        return -1;
1247
0
    }
1248
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1249
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1250
0
                .tag("instance_id", instance_id_)
1251
0
                .tag("status", instance.status())
1252
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1253
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1254
0
        return -1;
1255
0
    }
1256
11
    if (instance.recycle_state() != current_state) {
1257
1
        LOG_WARNING("instance recycled state changed before update")
1258
1
                .tag("instance_id", instance_id_)
1259
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1260
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1261
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1262
1
        return -1;
1263
1
    }
1264
1265
10
    instance.set_recycle_state(target_state);
1266
10
    instance.set_recycle_state_update_time_ms(
1267
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1268
10
    if (!instance.SerializeToString(&value)) {
1269
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1270
0
                .tag("instance_id", instance_id_)
1271
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1272
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1273
0
        return -1;
1274
0
    }
1275
1276
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1277
10
    txn->put(key, value);
1278
10
    err = txn->commit();
1279
10
    if (err != TxnErrorCode::TXN_OK) {
1280
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1281
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1282
0
        return -1;
1283
0
    }
1284
1285
10
    instance_info_.Swap(&instance);
1286
10
    LOG_INFO("updated instance recycled state")
1287
10
            .tag("instance_id", instance_id_)
1288
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1289
10
    return 0;
1290
10
}
1291
1292
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1293
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1294
9
    if (exists == nullptr) {
1295
0
        return -1;
1296
0
    }
1297
9
    *exists = false;
1298
1299
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1300
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1301
9
    std::string scan_begin = begin;
1302
1303
9
    while (true) {
1304
9
        std::unique_ptr<RangeGetIterator> it_range;
1305
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1306
9
        if (get_ret < 0) {
1307
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1308
0
                    .tag("instance_id", instance_id_)
1309
0
                    .tag("tablet_id", tablet_id)
1310
0
                    .tag("ret", get_ret);
1311
0
            return -1;
1312
0
        }
1313
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1314
6
            return 0;
1315
6
        }
1316
1317
3
        std::string last_key;
1318
3
        while (it_range->has_next()) {
1319
3
            auto [k, v] = it_range->next();
1320
3
            last_key.assign(k.data(), k.size());
1321
3
            doris::RowsetMetaCloudPB rowset_meta;
1322
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1323
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1324
0
                        .tag("instance_id", instance_id_)
1325
0
                        .tag("tablet_id", tablet_id)
1326
0
                        .tag("key", hex(k));
1327
0
                continue;
1328
0
            }
1329
3
            if (stats) {
1330
3
                ++stats->rowset_scan_count;
1331
3
            }
1332
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1333
3
                *exists = true;
1334
3
                return 0;
1335
3
            }
1336
3
        }
1337
1338
0
        if (!it_range->more()) {
1339
0
            return 0;
1340
0
        }
1341
1342
        // Continue scanning from the next key to keep each transaction short.
1343
0
        scan_begin = std::move(last_key);
1344
0
        scan_begin.push_back('\x00');
1345
0
    }
1346
9
}
1347
1348
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1349
                                                          const std::string& rowset_id,
1350
                                                          int64_t txn_id, bool* recycle_exists,
1351
11
                                                          bool* tmp_exists) {
1352
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1353
0
        return -1;
1354
0
    }
1355
11
    *recycle_exists = false;
1356
11
    *tmp_exists = false;
1357
1358
11
    if (txn_id <= 0) {
1359
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1360
0
                .tag("instance_id", instance_id_)
1361
0
                .tag("tablet_id", tablet_id)
1362
0
                .tag("rowset_id", rowset_id)
1363
0
                .tag("txn_id", txn_id);
1364
0
        return -1;
1365
0
    }
1366
1367
11
    std::unique_ptr<Transaction> txn;
1368
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1369
11
    if (err != TxnErrorCode::TXN_OK) {
1370
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1371
0
                .tag("instance_id", instance_id_)
1372
0
                .tag("tablet_id", tablet_id)
1373
0
                .tag("rowset_id", rowset_id)
1374
0
                .tag("txn_id", txn_id)
1375
0
                .tag("err", err);
1376
0
        return -1;
1377
0
    }
1378
1379
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1380
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1381
11
    if (ret == TxnErrorCode::TXN_OK) {
1382
1
        *recycle_exists = true;
1383
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1384
0
        LOG_WARNING("failed to check recycle rowset existence")
1385
0
                .tag("instance_id", instance_id_)
1386
0
                .tag("tablet_id", tablet_id)
1387
0
                .tag("rowset_id", rowset_id)
1388
0
                .tag("key", hex(recycle_key))
1389
0
                .tag("err", ret);
1390
0
        return -1;
1391
0
    }
1392
1393
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1394
11
    ret = key_exists(txn.get(), tmp_key, true);
1395
11
    if (ret == TxnErrorCode::TXN_OK) {
1396
1
        *tmp_exists = true;
1397
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1398
0
        LOG_WARNING("failed to check tmp rowset existence")
1399
0
                .tag("instance_id", instance_id_)
1400
0
                .tag("tablet_id", tablet_id)
1401
0
                .tag("txn_id", txn_id)
1402
0
                .tag("key", hex(tmp_key))
1403
0
                .tag("err", ret);
1404
0
        return -1;
1405
0
    }
1406
1407
11
    return 0;
1408
11
}
1409
1410
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1411
7.49k
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1412
7.49k
    if (!hint.empty()) {
1413
7.49k
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1414
7.47k
            return {hint, it->second};
1415
7.47k
        }
1416
7.49k
    }
1417
1418
16
    return {"", nullptr};
1419
7.49k
}
1420
1421
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1422
                                               const std::string& packed_file_path,
1423
3
                                               PackedFileRecycleStats* stats) {
1424
3
    bool local_changed = false;
1425
3
    int64_t left_num = 0;
1426
3
    int64_t left_bytes = 0;
1427
3
    bool all_small_files_confirmed = true;
1428
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1429
1430
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1431
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1432
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1433
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1434
14
        LOG_INFO("packed slice correction status")
1435
14
                .tag("instance_id", instance_id_)
1436
14
                .tag("packed_file_path", packed_file_path)
1437
14
                .tag("small_file_path", file.path())
1438
14
                .tag("tablet_id", tablet_id)
1439
14
                .tag("rowset_id", rowset_id)
1440
14
                .tag("txn_id", txn_id)
1441
14
                .tag("size", file.size())
1442
14
                .tag("deleted", file.deleted())
1443
14
                .tag("corrected", file.corrected())
1444
14
                .tag("confirmed_this_round", confirmed_this_round);
1445
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1430
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1431
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1432
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1433
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1434
        LOG_INFO("packed slice correction status")
1435
14
                .tag("instance_id", instance_id_)
1436
14
                .tag("packed_file_path", packed_file_path)
1437
14
                .tag("small_file_path", file.path())
1438
14
                .tag("tablet_id", tablet_id)
1439
14
                .tag("rowset_id", rowset_id)
1440
14
                .tag("txn_id", txn_id)
1441
14
                .tag("size", file.size())
1442
14
                .tag("deleted", file.deleted())
1443
14
                .tag("corrected", file.corrected())
1444
14
                .tag("confirmed_this_round", confirmed_this_round);
1445
14
    };
1446
1447
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1448
14
        auto* small_file = packed_info->mutable_slices(i);
1449
14
        if (small_file->deleted()) {
1450
3
            log_small_file_status(*small_file, small_file->corrected());
1451
3
            continue;
1452
3
        }
1453
1454
11
        if (small_file->corrected()) {
1455
0
            left_num++;
1456
0
            left_bytes += small_file->size();
1457
0
            log_small_file_status(*small_file, true);
1458
0
            continue;
1459
0
        }
1460
1461
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1462
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1463
0
                    .tag("instance_id", instance_id_)
1464
0
                    .tag("small_file_path", small_file->path())
1465
0
                    .tag("index", i);
1466
0
            return -1;
1467
0
        }
1468
1469
11
        int64_t tablet_id = small_file->tablet_id();
1470
11
        const std::string& rowset_id = small_file->rowset_id();
1471
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1472
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1473
0
                    .tag("instance_id", instance_id_)
1474
0
                    .tag("small_file_path", small_file->path())
1475
0
                    .tag("index", i)
1476
0
                    .tag("tablet_id", tablet_id)
1477
0
                    .tag("rowset_id", rowset_id)
1478
0
                    .tag("has_txn_id", small_file->has_txn_id())
1479
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1480
0
            return -1;
1481
0
        }
1482
11
        int64_t txn_id = small_file->txn_id();
1483
11
        bool recycle_exists = false;
1484
11
        bool tmp_exists = false;
1485
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1486
11
                                                &tmp_exists) != 0) {
1487
0
            return -1;
1488
0
        }
1489
1490
11
        bool small_file_confirmed = false;
1491
11
        if (tmp_exists) {
1492
1
            left_num++;
1493
1
            left_bytes += small_file->size();
1494
1
            small_file_confirmed = true;
1495
10
        } else if (recycle_exists) {
1496
1
            left_num++;
1497
1
            left_bytes += small_file->size();
1498
            // keep small_file_confirmed=false so the packed file remains uncorrected
1499
9
        } else {
1500
9
            bool rowset_exists = false;
1501
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1502
0
                return -1;
1503
0
            }
1504
1505
9
            if (!rowset_exists) {
1506
6
                if (!small_file->deleted()) {
1507
6
                    small_file->set_deleted(true);
1508
6
                    local_changed = true;
1509
6
                }
1510
6
                if (!small_file->corrected()) {
1511
6
                    small_file->set_corrected(true);
1512
6
                    local_changed = true;
1513
6
                }
1514
6
                small_file_confirmed = true;
1515
6
            } else {
1516
3
                left_num++;
1517
3
                left_bytes += small_file->size();
1518
3
                small_file_confirmed = true;
1519
3
            }
1520
9
        }
1521
1522
11
        if (!small_file_confirmed) {
1523
1
            all_small_files_confirmed = false;
1524
1
        }
1525
1526
11
        if (small_file->corrected() != small_file_confirmed) {
1527
4
            small_file->set_corrected(small_file_confirmed);
1528
4
            local_changed = true;
1529
4
        }
1530
1531
11
        log_small_file_status(*small_file, small_file_confirmed);
1532
11
    }
1533
1534
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1535
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1536
3
        local_changed = true;
1537
3
    }
1538
3
    if (packed_info->ref_cnt() != left_num) {
1539
3
        auto old_ref_cnt = packed_info->ref_cnt();
1540
3
        packed_info->set_ref_cnt(left_num);
1541
3
        LOG_INFO("corrected packed file ref count")
1542
3
                .tag("instance_id", instance_id_)
1543
3
                .tag("resource_id", packed_info->resource_id())
1544
3
                .tag("packed_file_path", packed_file_path)
1545
3
                .tag("old_ref_cnt", old_ref_cnt)
1546
3
                .tag("new_ref_cnt", left_num);
1547
3
        local_changed = true;
1548
3
    }
1549
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1550
2
        packed_info->set_corrected(all_small_files_confirmed);
1551
2
        local_changed = true;
1552
2
    }
1553
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1554
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1555
1
        local_changed = true;
1556
1
    }
1557
1558
3
    if (changed != nullptr) {
1559
3
        *changed = local_changed;
1560
3
    }
1561
3
    return 0;
1562
3
}
1563
1564
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1565
                                                 const std::string& packed_file_path,
1566
4
                                                 PackedFileRecycleStats* stats) {
1567
4
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1568
4
    bool correction_ok = false;
1569
4
    cloud::PackedFileInfoPB packed_info;
1570
1571
4
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1572
4
        if (stopped()) {
1573
0
            LOG_WARNING("recycler stopped before processing packed file")
1574
0
                    .tag("instance_id", instance_id_)
1575
0
                    .tag("packed_file_path", packed_file_path)
1576
0
                    .tag("attempt", attempt);
1577
0
            return -1;
1578
0
        }
1579
1580
4
        std::unique_ptr<Transaction> txn;
1581
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1582
4
        if (err != TxnErrorCode::TXN_OK) {
1583
0
            LOG_WARNING("failed to create txn when processing packed file")
1584
0
                    .tag("instance_id", instance_id_)
1585
0
                    .tag("packed_file_path", packed_file_path)
1586
0
                    .tag("attempt", attempt)
1587
0
                    .tag("err", err);
1588
0
            return -1;
1589
0
        }
1590
1591
4
        std::string packed_val;
1592
4
        err = txn->get(packed_key, &packed_val);
1593
4
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1594
0
            return 0;
1595
0
        }
1596
4
        if (err != TxnErrorCode::TXN_OK) {
1597
0
            LOG_WARNING("failed to get packed file kv")
1598
0
                    .tag("instance_id", instance_id_)
1599
0
                    .tag("packed_file_path", packed_file_path)
1600
0
                    .tag("attempt", attempt)
1601
0
                    .tag("err", err);
1602
0
            return -1;
1603
0
        }
1604
1605
4
        if (!packed_info.ParseFromString(packed_val)) {
1606
0
            LOG_WARNING("failed to parse packed file info")
1607
0
                    .tag("instance_id", instance_id_)
1608
0
                    .tag("packed_file_path", packed_file_path)
1609
0
                    .tag("attempt", attempt);
1610
0
            return -1;
1611
0
        }
1612
1613
4
        int64_t now_sec = ::time(nullptr);
1614
4
        bool corrected = packed_info.corrected();
1615
4
        bool due = config::force_immediate_recycle ||
1616
4
                   now_sec - packed_info.created_at_sec() >=
1617
4
                           config::packed_file_correction_delay_seconds;
1618
1619
4
        if (!corrected && due) {
1620
3
            bool changed = false;
1621
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1622
0
                LOG_WARNING("correct_packed_file_info failed")
1623
0
                        .tag("instance_id", instance_id_)
1624
0
                        .tag("packed_file_path", packed_file_path)
1625
0
                        .tag("attempt", attempt);
1626
0
                return -1;
1627
0
            }
1628
3
            if (changed) {
1629
3
                std::string updated;
1630
3
                if (!packed_info.SerializeToString(&updated)) {
1631
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1632
0
                            .tag("instance_id", instance_id_)
1633
0
                            .tag("packed_file_path", packed_file_path)
1634
0
                            .tag("attempt", attempt);
1635
0
                    return -1;
1636
0
                }
1637
3
                txn->put(packed_key, updated);
1638
3
                err = txn->commit();
1639
3
                if (err == TxnErrorCode::TXN_OK) {
1640
3
                    if (stats) {
1641
3
                        ++stats->num_corrected;
1642
3
                    }
1643
3
                } else {
1644
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1645
0
                        LOG_WARNING(
1646
0
                                "failed to commit correction for packed file due to conflict, "
1647
0
                                "retrying")
1648
0
                                .tag("instance_id", instance_id_)
1649
0
                                .tag("packed_file_path", packed_file_path)
1650
0
                                .tag("attempt", attempt);
1651
0
                        sleep_for_packed_file_retry();
1652
0
                        packed_info.Clear();
1653
0
                        continue;
1654
0
                    }
1655
0
                    LOG_WARNING("failed to commit correction for packed file")
1656
0
                            .tag("instance_id", instance_id_)
1657
0
                            .tag("packed_file_path", packed_file_path)
1658
0
                            .tag("attempt", attempt)
1659
0
                            .tag("err", err);
1660
0
                    return -1;
1661
0
                }
1662
3
            }
1663
3
        }
1664
1665
4
        correction_ok = true;
1666
4
        break;
1667
4
    }
1668
1669
4
    if (!correction_ok) {
1670
0
        return -1;
1671
0
    }
1672
1673
4
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1674
4
          packed_info.ref_cnt() == 0)) {
1675
3
        return 0;
1676
3
    }
1677
1678
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1679
0
        LOG_WARNING("packed file missing resource id when recycling")
1680
0
                .tag("instance_id", instance_id_)
1681
0
                .tag("packed_file_path", packed_file_path);
1682
0
        return -1;
1683
0
    }
1684
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1685
1
    if (!accessor) {
1686
0
        LOG_WARNING("no accessor available to delete packed file")
1687
0
                .tag("instance_id", instance_id_)
1688
0
                .tag("packed_file_path", packed_file_path)
1689
0
                .tag("resource_id", packed_info.resource_id());
1690
0
        return -1;
1691
0
    }
1692
1
    int del_ret = accessor->delete_file(packed_file_path);
1693
1
    if (del_ret != 0 && del_ret != 1) {
1694
0
        LOG_WARNING("failed to delete packed file")
1695
0
                .tag("instance_id", instance_id_)
1696
0
                .tag("packed_file_path", packed_file_path)
1697
0
                .tag("resource_id", resource_id)
1698
0
                .tag("ret", del_ret);
1699
0
        return -1;
1700
0
    }
1701
1
    if (del_ret == 1) {
1702
0
        LOG_INFO("packed file already removed")
1703
0
                .tag("instance_id", instance_id_)
1704
0
                .tag("packed_file_path", packed_file_path)
1705
0
                .tag("resource_id", resource_id);
1706
1
    } else {
1707
1
        LOG_INFO("deleted packed file")
1708
1
                .tag("instance_id", instance_id_)
1709
1
                .tag("packed_file_path", packed_file_path)
1710
1
                .tag("resource_id", resource_id);
1711
1
    }
1712
1713
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1714
1
        std::unique_ptr<Transaction> del_txn;
1715
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1716
1
        if (err != TxnErrorCode::TXN_OK) {
1717
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1718
0
                    .tag("instance_id", instance_id_)
1719
0
                    .tag("packed_file_path", packed_file_path)
1720
0
                    .tag("del_attempt", del_attempt)
1721
0
                    .tag("err", err);
1722
0
            return -1;
1723
0
        }
1724
1725
1
        std::string latest_val;
1726
1
        err = del_txn->get(packed_key, &latest_val);
1727
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1728
0
            return 0;
1729
0
        }
1730
1
        if (err != TxnErrorCode::TXN_OK) {
1731
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1732
0
                    .tag("instance_id", instance_id_)
1733
0
                    .tag("packed_file_path", packed_file_path)
1734
0
                    .tag("del_attempt", del_attempt)
1735
0
                    .tag("err", err);
1736
0
            return -1;
1737
0
        }
1738
1739
1
        cloud::PackedFileInfoPB latest_info;
1740
1
        if (!latest_info.ParseFromString(latest_val)) {
1741
0
            LOG_WARNING("failed to parse packed file info before removal")
1742
0
                    .tag("instance_id", instance_id_)
1743
0
                    .tag("packed_file_path", packed_file_path)
1744
0
                    .tag("del_attempt", del_attempt);
1745
0
            return -1;
1746
0
        }
1747
1748
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1749
1
              latest_info.ref_cnt() == 0)) {
1750
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1751
0
                    .tag("instance_id", instance_id_)
1752
0
                    .tag("packed_file_path", packed_file_path)
1753
0
                    .tag("del_attempt", del_attempt);
1754
0
            return 0;
1755
0
        }
1756
1757
1
        del_txn->remove(packed_key);
1758
1
        err = del_txn->commit();
1759
1
        if (err == TxnErrorCode::TXN_OK) {
1760
1
            if (stats) {
1761
1
                ++stats->num_deleted;
1762
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1763
1
                                        static_cast<int64_t>(latest_val.size());
1764
1
                if (del_ret == 0 || del_ret == 1) {
1765
1
                    ++stats->num_object_deleted;
1766
1
                    int64_t object_size = latest_info.total_slice_bytes();
1767
1
                    if (object_size <= 0) {
1768
0
                        object_size = packed_info.total_slice_bytes();
1769
0
                    }
1770
1
                    stats->bytes_object_deleted += object_size;
1771
1
                }
1772
1
            }
1773
1
            LOG_INFO("removed packed file metadata")
1774
1
                    .tag("instance_id", instance_id_)
1775
1
                    .tag("packed_file_path", packed_file_path);
1776
1
            return 0;
1777
1
        }
1778
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1779
0
            if (del_attempt >= max_retry_times) {
1780
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1781
0
                        .tag("instance_id", instance_id_)
1782
0
                        .tag("packed_file_path", packed_file_path)
1783
0
                        .tag("del_attempt", del_attempt);
1784
0
                return -1;
1785
0
            }
1786
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1787
0
                    .tag("instance_id", instance_id_)
1788
0
                    .tag("packed_file_path", packed_file_path)
1789
0
                    .tag("del_attempt", del_attempt);
1790
0
            sleep_for_packed_file_retry();
1791
0
            continue;
1792
0
        }
1793
0
        LOG_WARNING("failed to remove packed file kv")
1794
0
                .tag("instance_id", instance_id_)
1795
0
                .tag("packed_file_path", packed_file_path)
1796
0
                .tag("del_attempt", del_attempt)
1797
0
                .tag("err", err);
1798
0
        return -1;
1799
0
    }
1800
1801
0
    return -1;
1802
1
}
1803
1804
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view /*value*/,
1805
4
                                            PackedFileRecycleStats* stats, int* ret) {
1806
4
    if (stats) {
1807
4
        ++stats->num_scanned;
1808
4
    }
1809
4
    std::string packed_file_path;
1810
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1811
0
        LOG_WARNING("failed to decode packed file key")
1812
0
                .tag("instance_id", instance_id_)
1813
0
                .tag("key", hex(key));
1814
0
        if (stats) {
1815
0
            ++stats->num_failed;
1816
0
        }
1817
0
        if (ret) {
1818
0
            *ret = -1;
1819
0
        }
1820
0
        return 0;
1821
0
    }
1822
1823
4
    std::string packed_key(key);
1824
4
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1825
4
    if (process_ret != 0) {
1826
0
        if (stats) {
1827
0
            ++stats->num_failed;
1828
0
        }
1829
0
        if (ret) {
1830
0
            *ret = -1;
1831
0
        }
1832
0
    }
1833
4
    return 0;
1834
4
}
1835
1836
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1837
126k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1838
126k
    if (config::force_immediate_recycle) {
1839
120k
        return 0L;
1840
120k
    }
1841
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1842
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1843
6.00k
    int64_t retention_seconds = config::retention_seconds;
1844
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1845
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1846
4.70k
    }
1847
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1848
6.00k
    if (*earlest_ts > final_expiration) {
1849
6
        *earlest_ts = final_expiration;
1850
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1851
6
    }
1852
6.00k
    return final_expiration;
1853
126k
}
1854
1855
int64_t calculate_partition_expired_time(
1856
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1857
9
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1858
9
    if (config::force_immediate_recycle) {
1859
3
        return 0L;
1860
3
    }
1861
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1862
6
                                                            : partition_meta_pb.creation_time();
1863
6
    int64_t retention_seconds = config::retention_seconds;
1864
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1865
6
        retention_seconds =
1866
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1867
6
    }
1868
6
    int64_t final_expiration = expiration + retention_seconds;
1869
6
    if (*earlest_ts > final_expiration) {
1870
2
        *earlest_ts = final_expiration;
1871
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1872
2
    }
1873
6
    return final_expiration;
1874
9
}
1875
1876
int64_t calculate_index_expired_time(const std::string& instance_id_,
1877
                                     const RecycleIndexPB& index_meta_pb,
1878
10
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1879
10
    if (config::force_immediate_recycle) {
1880
4
        return 0L;
1881
4
    }
1882
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1883
6
                                                        : index_meta_pb.creation_time();
1884
6
    int64_t retention_seconds = config::retention_seconds;
1885
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1886
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1887
6
    }
1888
6
    int64_t final_expiration = expiration + retention_seconds;
1889
6
    if (*earlest_ts > final_expiration) {
1890
2
        *earlest_ts = final_expiration;
1891
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1892
2
    }
1893
6
    return final_expiration;
1894
10
}
1895
1896
int64_t calculate_tmp_rowset_expired_time(
1897
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1898
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1899
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1900
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1901
    //  duration or timeout always < `retention_time` in practice.
1902
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1903
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1904
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1905
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1906
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1907
53.2k
    if (*earlest_ts > final_expiration) {
1908
20
        *earlest_ts = final_expiration;
1909
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1910
20
    }
1911
53.2k
    return final_expiration;
1912
53.2k
}
1913
1914
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1915
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1916
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1917
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1918
11
        *earlest_ts = final_expiration / 1000;
1919
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1920
11
    }
1921
50.0k
    return final_expiration;
1922
50.0k
}
1923
1924
int64_t calculate_restore_job_expired_time(
1925
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1926
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1927
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1928
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1929
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1930
        // final state, recycle immediately
1931
41
        return 0L;
1932
41
    }
1933
    // not final state, wait much longer than the FE's timeout(1 day)
1934
0
    int64_t last_modified_s =
1935
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1936
0
    int64_t expiration = restore_job.expired_at_s() > 0
1937
0
                                 ? last_modified_s + restore_job.expired_at_s()
1938
0
                                 : last_modified_s;
1939
0
    int64_t final_expiration = expiration + config::retention_seconds;
1940
0
    if (*earlest_ts > final_expiration) {
1941
0
        *earlest_ts = final_expiration;
1942
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1943
0
    }
1944
0
    return final_expiration;
1945
41
}
1946
1947
10.5k
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1948
10.5k
    AbortTxnRequest req;
1949
10.5k
    TxnInfoPB txn_info;
1950
10.5k
    MetaServiceCode code = MetaServiceCode::OK;
1951
10.5k
    std::string msg;
1952
10.5k
    std::stringstream ss;
1953
10.5k
    std::unique_ptr<Transaction> txn;
1954
10.5k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1955
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1956
0
        LOG_WARNING("failed to create txn").tag("err", err);
1957
0
        return -1;
1958
0
    }
1959
1960
    // get txn index
1961
10.5k
    TxnIndexPB txn_idx_pb;
1962
10.5k
    auto index_key = txn_index_key({instance_id_, txn_id});
1963
10.5k
    std::string index_val;
1964
10.5k
    err = txn->get(index_key, &index_val);
1965
10.5k
    if (err != TxnErrorCode::TXN_OK) {
1966
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1967
            // maybe recycled
1968
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1969
2
                    .tag("key", hex(index_key))
1970
2
                    .tag("txn_id", txn_id);
1971
2
            return 0;
1972
2
        }
1973
0
        LOG_WARNING("failed to get txn index")
1974
0
                .tag("err", err)
1975
0
                .tag("key", hex(index_key))
1976
0
                .tag("txn_id", txn_id);
1977
0
        return -1;
1978
2
    }
1979
10.5k
    if (!txn_idx_pb.ParseFromString(index_val)) {
1980
1
        LOG_WARNING("failed to parse txn index")
1981
1
                .tag("err", err)
1982
1
                .tag("key", hex(index_key))
1983
1
                .tag("txn_id", txn_id);
1984
1
        return -1;
1985
1
    }
1986
10.5k
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
1987
10.5k
        txn_idx_pb.tablet_index().db_id() <= 0) {
1988
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
1989
3
                .tag("key", hex(index_key))
1990
3
                .tag("txn_id", txn_id)
1991
3
                .tag("db_id",
1992
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
1993
3
        return -1;
1994
3
    }
1995
1996
10.5k
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
1997
10.5k
    const int64_t owner_txn_id =
1998
10.5k
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
1999
10.5k
    if (owner_txn_id <= 0) {
2000
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2001
1
                .tag("key", hex(index_key))
2002
1
                .tag("txn_id", txn_id)
2003
1
                .tag("owner_txn_id", owner_txn_id);
2004
1
        return -1;
2005
1
    }
2006
2007
10.5k
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2008
10.5k
    std::string info_val;
2009
10.5k
    err = txn->get(info_key, &info_val);
2010
10.5k
    if (err != TxnErrorCode::TXN_OK) {
2011
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2012
            // maybe recycled
2013
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2014
1
                        owner_txn_id, instance_id_)
2015
1
                    .tag("key", hex(info_key))
2016
1
                    .tag("txn_id", txn_id)
2017
1
                    .tag("owner_txn_id", owner_txn_id);
2018
1
            return 0;
2019
1
        }
2020
0
        LOG_WARNING("failed to get txn info")
2021
0
                .tag("err", err)
2022
0
                .tag("key", hex(info_key))
2023
0
                .tag("txn_id", txn_id)
2024
0
                .tag("owner_txn_id", owner_txn_id);
2025
0
        return -1;
2026
1
    }
2027
10.5k
    if (!txn_info.ParseFromString(info_val)) {
2028
1
        LOG_WARNING("failed to parse txn info")
2029
1
                .tag("err", err)
2030
1
                .tag("key", hex(info_key))
2031
1
                .tag("txn_id", txn_id)
2032
1
                .tag("owner_txn_id", owner_txn_id);
2033
1
        return -1;
2034
1
    }
2035
10.5k
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2036
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2037
1
                .tag("key", hex(info_key))
2038
1
                .tag("txn_id", txn_id)
2039
1
                .tag("owner_txn_id", owner_txn_id)
2040
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2041
1
        return -1;
2042
1
    }
2043
2044
10.5k
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2045
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2046
514
                .tag("key", hex(info_key))
2047
514
                .tag("txn_id", txn_id)
2048
514
                .tag("owner_txn_id", owner_txn_id);
2049
514
        return 0;
2050
514
    }
2051
9.98k
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2052
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2053
4
                    owner_txn_id, txn_info.status())
2054
4
                .tag("key", hex(info_key))
2055
4
                .tag("txn_id", txn_id)
2056
4
                .tag("owner_txn_id", owner_txn_id);
2057
4
        return -1;
2058
4
    }
2059
2060
9.98k
    req.set_txn_id(owner_txn_id);
2061
9.98k
    req.set_db_id(db_id);
2062
2063
9.98k
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2064
9.98k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2065
9.98k
                 << " txn_info=" << txn_info.ShortDebugString();
2066
2067
9.98k
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2068
9.98k
    if (code != MetaServiceCode::OK) {
2069
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2070
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2071
0
                     << " code=" << code << " msg=" << msg;
2072
0
        return -1;
2073
0
    }
2074
2075
9.98k
    err = txn->commit();
2076
9.98k
    if (err != TxnErrorCode::TXN_OK) {
2077
0
        code = cast_as<ErrCategory::COMMIT>(err);
2078
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2079
0
        msg = ss.str();
2080
0
        return -1;
2081
0
    }
2082
2083
9.98k
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2084
9.98k
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2085
9.98k
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2086
9.98k
                 << " msg=" << msg;
2087
2088
9.98k
    return 0;
2089
9.98k
}
2090
2091
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2092
11
                                                   const std::string& job_id) {
2093
11
    FinishTabletJobRequest req;
2094
11
    FinishTabletJobResponse res;
2095
11
    req.set_action(FinishTabletJobRequest::ABORT);
2096
11
    MetaServiceCode code = MetaServiceCode::OK;
2097
11
    std::string msg;
2098
11
    std::stringstream ss;
2099
2100
11
    TabletIndexPB tablet_idx;
2101
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2102
11
    if (ret == 1) {
2103
        // tablet maybe recycled, directly return 0
2104
1
        return 0;
2105
10
    } else if (ret != 0) {
2106
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2107
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2108
0
        return ret;
2109
0
    }
2110
2111
10
    std::unique_ptr<Transaction> txn;
2112
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2113
10
    if (err != TxnErrorCode::TXN_OK) {
2114
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2115
0
        return -1;
2116
0
    }
2117
2118
10
    std::string job_key =
2119
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2120
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2121
10
    std::string job_val;
2122
10
    err = txn->get(job_key, &job_val);
2123
10
    if (err != TxnErrorCode::TXN_OK) {
2124
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2125
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2126
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2127
            // A previous recycler round may have aborted the job. The caller must recheck the
2128
            // recycle key before deleting object data.
2129
1
            return 0;
2130
1
        }
2131
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2132
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2133
0
                     << " key=" << hex(job_key);
2134
0
        return -1;
2135
1
    }
2136
2137
9
    TabletJobInfoPB job_pb;
2138
9
    if (!job_pb.ParseFromString(job_val)) {
2139
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2140
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2141
0
        return -1;
2142
0
    }
2143
2144
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2145
9
    for (const auto& compaction : job_pb.compaction()) {
2146
9
        if (compaction.id() == job_id) {
2147
5
            matched_compaction = &compaction;
2148
5
            break;
2149
5
        }
2150
9
    }
2151
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2152
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2153
9
        job_pb.schema_change().id() == job_id) {
2154
3
        matched_schema_change = &job_pb.schema_change();
2155
3
    }
2156
2157
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2158
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2159
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2160
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2161
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2162
        // both the base and mirrored schema-change records.
2163
8
        if (matched_compaction != nullptr) {
2164
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2165
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2166
5
        } else {
2167
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2168
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2169
3
        }
2170
8
        req.set_action(FinishTabletJobRequest::ABORT);
2171
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2172
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2173
8
                           ss);
2174
8
        if (code != MetaServiceCode::OK) {
2175
            // These two codes mean that the job cannot be aborted anymore.
2176
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2177
            // There is no running job that still owns the PREPARE rowset, so the caller may
2178
            // recheck the recycle key.
2179
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2180
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2181
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2182
            // job again and continue recycling only when the target job id no longer exists.
2183
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2184
0
                std::unique_ptr<Transaction> check_txn;
2185
0
                err = txn_kv_->create_txn(&check_txn);
2186
0
                if (err != TxnErrorCode::TXN_OK) {
2187
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2188
0
                                 << instance_id_ << " err=" << err;
2189
0
                    return -1;
2190
0
                }
2191
2192
0
                const auto& idx = req.job().idx();
2193
0
                std::string current_job_key =
2194
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2195
0
                                        idx.partition_id(), idx.tablet_id()});
2196
0
                std::string current_job_val;
2197
0
                err = check_txn->get(current_job_key, &current_job_val);
2198
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2199
0
                    no_job_to_abort = true;
2200
0
                } else if (err != TxnErrorCode::TXN_OK) {
2201
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2202
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2203
0
                                 << " key=" << hex(current_job_key);
2204
0
                    return -1;
2205
0
                } else {
2206
0
                    TabletJobInfoPB current_job;
2207
0
                    if (!current_job.ParseFromString(current_job_val)) {
2208
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2209
0
                                     << " tablet_id=" << idx.tablet_id()
2210
0
                                     << " key=" << hex(current_job_key);
2211
0
                        return -1;
2212
0
                    }
2213
0
                    if (matched_compaction != nullptr) {
2214
0
                        no_job_to_abort = true;
2215
0
                        for (const auto& compaction : current_job.compaction()) {
2216
0
                            if (compaction.id() == job_id) {
2217
0
                                no_job_to_abort = false;
2218
0
                                break;
2219
0
                            }
2220
0
                        }
2221
0
                    } else {
2222
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2223
0
                                          current_job.schema_change().id() != job_id;
2224
0
                    }
2225
0
                }
2226
0
            }
2227
0
            if (no_job_to_abort) {
2228
0
                return 0;
2229
0
            }
2230
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2231
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2232
0
                         << " msg=" << msg;
2233
0
            return -1;
2234
0
        }
2235
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2236
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2237
8
                     << " code=" << code << " msg=" << msg;
2238
8
    } else {
2239
        // clang-format off
2240
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2241
1
                  << ", instance_id=" << instance_id_ 
2242
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2243
1
                  << ", job_id=" << job_id
2244
1
                  << ", rowset_id=" << rowset_id;
2245
        // clang-format on
2246
1
    }
2247
2248
9
    return 0;
2249
9
}
2250
2251
template <typename T>
2252
19.8k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
19.8k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2255
19.8k
    } else {
2256
9
        return &rowset_meta_pb;
2257
9
    }
2258
19.8k
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2252
19.8k
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
19.8k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
19.8k
        return rowset_meta_pb.mutable_rowset_meta();
2255
    } else {
2256
        return &rowset_meta_pb;
2257
    }
2258
19.8k
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2252
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2253
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2254
        return rowset_meta_pb.mutable_rowset_meta();
2255
9
    } else {
2256
9
        return &rowset_meta_pb;
2257
9
    }
2258
9
}
2259
2260
template <typename T>
2261
81.5k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
81.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
80.7k
        return rowset_meta_pb.rowset_meta();
2264
80.7k
    } else {
2265
799
        return rowset_meta_pb;
2266
799
    }
2267
81.5k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2261
80.7k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
80.7k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
80.7k
        return rowset_meta_pb.rowset_meta();
2264
    } else {
2265
        return rowset_meta_pb;
2266
    }
2267
80.7k
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2261
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2262
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2263
        return rowset_meta_pb.rowset_meta();
2264
799
    } else {
2265
799
        return rowset_meta_pb;
2266
799
    }
2267
799
}
2268
2269
template <typename T>
2270
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2271
41.0k
        const T& rowset_meta_pb) {
2272
41.0k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
0
            return std::nullopt;
2275
0
        }
2276
40.5k
    }
2277
2278
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
41.0k
    RelatedTxnOrJobAbortTask task;
2280
41.0k
    task.tablet_id = rs_meta.tablet_id();
2281
41.0k
    task.start_version = rs_meta.start_version();
2282
41.0k
    task.end_version = rs_meta.end_version();
2283
41.0k
    task.rowset_id = rs_meta.rowset_id_v2();
2284
41.0k
    if (rs_meta.has_load_id()) {
2285
21.0k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
21.0k
        task.txn_id = rs_meta.txn_id();
2287
21.0k
        return task;
2288
21.0k
    }
2289
20.0k
    if (rs_meta.has_job_id()) {
2290
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
14
        task.job_id = rs_meta.job_id();
2292
14
        return task;
2293
14
    }
2294
20.0k
    return std::nullopt;
2295
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2271
40.5k
        const T& rowset_meta_pb) {
2272
40.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
40.5k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
0
            return std::nullopt;
2275
0
        }
2276
40.5k
    }
2277
2278
40.5k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
40.5k
    RelatedTxnOrJobAbortTask task;
2280
40.5k
    task.tablet_id = rs_meta.tablet_id();
2281
40.5k
    task.start_version = rs_meta.start_version();
2282
40.5k
    task.end_version = rs_meta.end_version();
2283
40.5k
    task.rowset_id = rs_meta.rowset_id_v2();
2284
40.5k
    if (rs_meta.has_load_id()) {
2285
20.5k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
20.5k
        task.txn_id = rs_meta.txn_id();
2287
20.5k
        return task;
2288
20.5k
    }
2289
20.0k
    if (rs_meta.has_job_id()) {
2290
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
10
        task.job_id = rs_meta.job_id();
2292
10
        return task;
2293
10
    }
2294
20.0k
    return std::nullopt;
2295
20.0k
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2271
526
        const T& rowset_meta_pb) {
2272
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2273
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2274
            return std::nullopt;
2275
        }
2276
    }
2277
2278
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2279
526
    RelatedTxnOrJobAbortTask task;
2280
526
    task.tablet_id = rs_meta.tablet_id();
2281
526
    task.start_version = rs_meta.start_version();
2282
526
    task.end_version = rs_meta.end_version();
2283
526
    task.rowset_id = rs_meta.rowset_id_v2();
2284
526
    if (rs_meta.has_load_id()) {
2285
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2286
518
        task.txn_id = rs_meta.txn_id();
2287
518
        return task;
2288
518
    }
2289
8
    if (rs_meta.has_job_id()) {
2290
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2291
4
        task.job_id = rs_meta.job_id();
2292
4
        return task;
2293
4
    }
2294
4
    return std::nullopt;
2295
8
}
2296
2297
template <typename T>
2298
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2299
10.5k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
10.5k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
0
            return false;
2303
0
        }
2304
10.2k
    }
2305
2306
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
10.5k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
10.5k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
10.5k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
10.5k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
10.5k
    }
2314
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
10.5k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2299
10.2k
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
10.2k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
10.2k
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
0
            return false;
2303
0
        }
2304
10.2k
    }
2305
2306
10.2k
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
10.2k
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
10.2k
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
10.2k
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
10.2k
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
10.2k
    }
2314
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
10.2k
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2299
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2300
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2301
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2302
            return false;
2303
        }
2304
    }
2305
2306
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2307
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2308
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2309
0
        return false;
2310
0
    }
2311
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2312
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2313
259
    }
2314
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2315
261
}
2316
2317
79.8k
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2318
79.8k
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2319
79.8k
}
2320
2321
template <typename T>
2322
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2323
76
                                   const std::vector<std::string>& keys) {
2324
204
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
129
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
129
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
129
        std::unique_ptr<Transaction> txn;
2328
129
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
129
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
129
        std::vector<std::optional<std::string>> values;
2334
129
        err = txn->batch_get(&values, batch_keys);
2335
129
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
129
        DCHECK_EQ(values.size(), batch_keys.size());
2341
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
19.9k
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
19.9k
            const auto& key = batch_keys[i];
2347
19.9k
            auto val = values[i].value();
2348
19.9k
            T rowset_meta_pb;
2349
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
19.9k
            }
2362
19.9k
            val.clear();
2363
19.9k
            rowset_meta_pb.SerializeToString(&val);
2364
19.9k
            txn->put(key, val);
2365
19.9k
        }
2366
129
        err = txn->commit();
2367
129
        if (err != TxnErrorCode::TXN_OK) {
2368
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
1
            return -1;
2370
1
        }
2371
129
    }
2372
2373
75
    return 0;
2374
76
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2323
69
                                   const std::vector<std::string>& keys) {
2324
190
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
122
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
122
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
122
        std::unique_ptr<Transaction> txn;
2328
122
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
122
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
122
        std::vector<std::optional<std::string>> values;
2334
122
        err = txn->batch_get(&values, batch_keys);
2335
122
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
122
        DCHECK_EQ(values.size(), batch_keys.size());
2341
20.0k
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
19.9k
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
19.9k
            const auto& key = batch_keys[i];
2347
19.9k
            auto val = values[i].value();
2348
19.9k
            T rowset_meta_pb;
2349
19.9k
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
19.9k
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
19.9k
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
19.9k
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
19.9k
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
19.9k
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
19.9k
            }
2362
19.9k
            val.clear();
2363
19.9k
            rowset_meta_pb.SerializeToString(&val);
2364
19.9k
            txn->put(key, val);
2365
19.9k
        }
2366
122
        err = txn->commit();
2367
122
        if (err != TxnErrorCode::TXN_OK) {
2368
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
1
            return -1;
2370
1
        }
2371
122
    }
2372
2373
68
    return 0;
2374
69
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2323
7
                                   const std::vector<std::string>& keys) {
2324
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2325
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2326
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2327
7
        std::unique_ptr<Transaction> txn;
2328
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2329
7
        if (err != TxnErrorCode::TXN_OK) {
2330
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2331
0
            return -1;
2332
0
        }
2333
7
        std::vector<std::optional<std::string>> values;
2334
7
        err = txn->batch_get(&values, batch_keys);
2335
7
        if (err != TxnErrorCode::TXN_OK) {
2336
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2337
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2338
0
            return -1;
2339
0
        }
2340
7
        DCHECK_EQ(values.size(), batch_keys.size());
2341
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2342
9
            if (!values[i].has_value()) {
2343
                // has already been removed by commit_rowset
2344
0
                continue;
2345
0
            }
2346
9
            const auto& key = batch_keys[i];
2347
9
            auto val = values[i].value();
2348
9
            T rowset_meta_pb;
2349
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2350
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2351
0
                             << " key=" << hex(key);
2352
0
                return -1;
2353
0
            }
2354
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2355
0
                continue;
2356
0
            }
2357
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2358
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2359
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2360
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2361
            }
2362
9
            val.clear();
2363
9
            rowset_meta_pb.SerializeToString(&val);
2364
9
            txn->put(key, val);
2365
9
        }
2366
7
        err = txn->commit();
2367
7
        if (err != TxnErrorCode::TXN_OK) {
2368
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2369
0
            return -1;
2370
0
        }
2371
7
    }
2372
2373
7
    return 0;
2374
7
}
2375
2376
template <typename T>
2377
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2378
76
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
76
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
76
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
1
        }
2384
76
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2379
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
1
        }
2384
69
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2379
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
0
        }
2384
7
    });
2385
76
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2378
69
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
69
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
69
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
69
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
69
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
69
        }
2384
69
    });
2385
69
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2378
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2379
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2380
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2381
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2382
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2383
7
        }
2384
7
    });
2385
7
}
2386
2387
template <typename T>
2388
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2389
                                 const std::vector<std::string>& keys,
2390
51
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
132
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
81
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
81
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
81
        std::unique_ptr<Transaction> txn;
2395
81
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
81
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
81
        std::vector<std::optional<std::string>> values;
2401
81
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
81
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
81
        DCHECK_EQ(values.size(), batch_keys.size());
2408
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
10.5k
            const std::string& key = batch_keys[idx];
2410
10.5k
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
10.5k
            T rowset_meta_pb;
2415
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
10.5k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
10.5k
                abort_task.has_value()) {
2422
10.5k
                abort_task->key = key;
2423
10.5k
                abort_tasks->emplace_back(std::move(*abort_task));
2424
10.5k
            }
2425
10.5k
        }
2426
81
    }
2427
51
    return 0;
2428
51
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2390
46
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
121
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
75
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
75
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
75
        std::unique_ptr<Transaction> txn;
2395
75
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
75
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
75
        std::vector<std::optional<std::string>> values;
2401
75
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
75
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
75
        DCHECK_EQ(values.size(), batch_keys.size());
2408
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
10.2k
            const std::string& key = batch_keys[idx];
2410
10.2k
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
10.2k
            T rowset_meta_pb;
2415
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
10.2k
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
10.2k
                abort_task.has_value()) {
2422
10.2k
                abort_task->key = key;
2423
10.2k
                abort_tasks->emplace_back(std::move(*abort_task));
2424
10.2k
            }
2425
10.2k
        }
2426
75
    }
2427
46
    return 0;
2428
46
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2390
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2391
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2392
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2393
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2394
6
        std::unique_ptr<Transaction> txn;
2395
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2396
6
        if (err != TxnErrorCode::TXN_OK) {
2397
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2398
0
            return -1;
2399
0
        }
2400
6
        std::vector<std::optional<std::string>> values;
2401
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2402
6
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2404
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2405
0
            return -1;
2406
0
        }
2407
6
        DCHECK_EQ(values.size(), batch_keys.size());
2408
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2409
261
            const std::string& key = batch_keys[idx];
2410
261
            if (!values[idx].has_value()) {
2411
                // has already been removed
2412
0
                continue;
2413
0
            }
2414
261
            T rowset_meta_pb;
2415
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2416
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2417
0
                             << " key=" << hex(key);
2418
0
                return -1;
2419
0
            }
2420
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2421
261
                abort_task.has_value()) {
2422
261
                abort_task->key = key;
2423
261
                abort_tasks->emplace_back(std::move(*abort_task));
2424
261
            }
2425
261
        }
2426
6
    }
2427
5
    return 0;
2428
5
}
2429
2430
template <typename T>
2431
int batch_recheck_rowsets_after_abort(
2432
        TxnKv* txn_kv, const std::string& instance_id,
2433
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2434
49
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
49
    int ret = 0;
2436
128
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
79
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
79
        std::vector<std::string> batch_keys;
2439
79
        batch_keys.reserve(limit - offset);
2440
10.6k
        for (size_t idx = offset; idx < limit; ++idx) {
2441
10.5k
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
10.5k
        }
2443
2444
79
        std::unique_ptr<Transaction> txn;
2445
79
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
79
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
79
        std::vector<std::optional<std::string>> values;
2454
79
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
79
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
79
        DCHECK_EQ(values.size(), batch_keys.size());
2462
79
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
79
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
79
                                 &batch_size);
2465
2466
10.6k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
10.5k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
10.5k
            if (!values[idx].has_value()) {
2469
1
                continue;
2470
1
            }
2471
2472
10.5k
            T rowset_meta_pb;
2473
10.5k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
10.5k
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
10.5k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
10.5k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
1
                             << instance_id << " key=" << hex(key);
2488
1
                continue;
2489
1
            }
2490
10.5k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
10.5k
        }
2492
79
    }
2493
49
    return ret;
2494
49
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2434
44
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
44
    int ret = 0;
2436
117
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
73
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
73
        std::vector<std::string> batch_keys;
2439
73
        batch_keys.reserve(limit - offset);
2440
10.3k
        for (size_t idx = offset; idx < limit; ++idx) {
2441
10.2k
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
10.2k
        }
2443
2444
73
        std::unique_ptr<Transaction> txn;
2445
73
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
73
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
73
        std::vector<std::optional<std::string>> values;
2454
73
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
73
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
73
        DCHECK_EQ(values.size(), batch_keys.size());
2462
73
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
73
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
73
                                 &batch_size);
2465
2466
10.3k
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
10.2k
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
10.2k
            if (!values[idx].has_value()) {
2469
1
                continue;
2470
1
            }
2471
2472
10.2k
            T rowset_meta_pb;
2473
10.2k
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
10.2k
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
10.2k
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
10.2k
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
1
                             << instance_id << " key=" << hex(key);
2488
1
                continue;
2489
1
            }
2490
10.2k
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
10.2k
        }
2492
73
    }
2493
44
    return ret;
2494
44
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2434
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2435
5
    int ret = 0;
2436
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2437
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2438
6
        std::vector<std::string> batch_keys;
2439
6
        batch_keys.reserve(limit - offset);
2440
267
        for (size_t idx = offset; idx < limit; ++idx) {
2441
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2442
261
        }
2443
2444
6
        std::unique_ptr<Transaction> txn;
2445
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2446
6
        if (err != TxnErrorCode::TXN_OK) {
2447
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2448
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2449
0
            ret = -1;
2450
0
            continue;
2451
0
        }
2452
2453
6
        std::vector<std::optional<std::string>> values;
2454
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2455
6
        if (err != TxnErrorCode::TXN_OK) {
2456
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2457
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2458
0
            ret = -1;
2459
0
            continue;
2460
0
        }
2461
6
        DCHECK_EQ(values.size(), batch_keys.size());
2462
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2463
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2464
6
                                 &batch_size);
2465
2466
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2467
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2468
261
            if (!values[idx].has_value()) {
2469
0
                continue;
2470
0
            }
2471
2472
261
            T rowset_meta_pb;
2473
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2474
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2475
0
                             << instance_id << " key=" << hex(key);
2476
0
                ret = -1;
2477
0
                continue;
2478
0
            }
2479
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2480
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2481
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2482
0
                             << instance_id << " key=" << hex(key);
2483
0
                continue;
2484
0
            }
2485
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2486
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2487
0
                             << instance_id << " key=" << hex(key);
2488
0
                continue;
2489
0
            }
2490
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2491
261
        }
2492
6
    }
2493
5
    return ret;
2494
5
}
2495
2496
template <typename T>
2497
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2498
        const std::vector<std::string>& keys,
2499
51
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
51
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
51
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
51
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
51
    int ret = 0;
2507
10.4k
    for (const auto& abort_task : abort_tasks) {
2508
10.4k
        int abort_ret = 0;
2509
10.5k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
10.5k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
18.4E
        } else {
2512
18.4E
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
18.4E
                                                     abort_task.job_id);
2514
18.4E
        }
2515
10.4k
        if (abort_ret != 0) {
2516
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
3
            ret = abort_ret;
2520
3
            continue;
2521
3
        }
2522
10.4k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
10.4k
    }
2524
51
    return ret;
2525
51
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2499
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
46
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
46
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
46
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
46
    int ret = 0;
2507
10.2k
    for (const auto& abort_task : abort_tasks) {
2508
10.2k
        int abort_ret = 0;
2509
10.2k
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
10.2k
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
18.4E
        } else {
2512
18.4E
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
18.4E
                                                     abort_task.job_id);
2514
18.4E
        }
2515
10.2k
        if (abort_ret != 0) {
2516
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
3
            ret = abort_ret;
2520
3
            continue;
2521
3
        }
2522
10.2k
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
10.2k
    }
2524
46
    return ret;
2525
46
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2499
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2500
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2501
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2502
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2503
0
        return -1;
2504
0
    }
2505
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2506
5
    int ret = 0;
2507
261
    for (const auto& abort_task : abort_tasks) {
2508
261
        int abort_ret = 0;
2509
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2510
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2511
259
        } else {
2512
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2513
2
                                                     abort_task.job_id);
2514
2
        }
2515
261
        if (abort_ret != 0) {
2516
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2517
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2518
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2519
0
            ret = abort_ret;
2520
0
            continue;
2521
0
        }
2522
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2523
261
    }
2524
5
    return ret;
2525
5
}
2526
2527
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2528
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2529
46
        std::atomic_long* num_recycled) {
2530
46
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2531
46
                                  num_recycled]() mutable {
2532
46
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
46
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
46
                                                                            keys_to_recheck);
2535
46
        if (abort_ret != 0) {
2536
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
2
                            "instance_id="
2538
2
                         << instance_id_;
2539
2
        }
2540
46
        if (keys_to_recheck.empty()) {
2541
2
            return;
2542
2
        }
2543
2544
44
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
44
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
44
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
44
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2553
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2555
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
1
                continue;
2557
1
            }
2558
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
10.2k
                                                   current_meta.tablet_id(),
2560
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
10.2k
            std::vector<std::string> keys {key};
2564
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
10.2k
        }
2570
44
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2531
2
                                  num_recycled]() mutable {
2532
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
2
                                                                            keys_to_recheck);
2535
2
        if (abort_ret != 0) {
2536
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
0
                            "instance_id="
2538
0
                         << instance_id_;
2539
0
        }
2540
2
        if (keys_to_recheck.empty()) {
2541
0
            return;
2542
0
        }
2543
2544
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
2
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
2
            const auto& current_meta = current_rowset.rowset_meta();
2553
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
2
                                   current_meta.rowset_id_v2()) != 0) {
2555
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
0
                continue;
2557
0
            }
2558
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
2
                                                   current_meta.tablet_id(),
2560
2
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
2
            std::vector<std::string> keys {key};
2564
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
2
        }
2570
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2531
44
                                  num_recycled]() mutable {
2532
44
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2533
44
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2534
44
                                                                            keys_to_recheck);
2535
44
        if (abort_ret != 0) {
2536
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2537
2
                            "instance_id="
2538
2
                         << instance_id_;
2539
2
        }
2540
44
        if (keys_to_recheck.empty()) {
2541
2
            return;
2542
2
        }
2543
2544
42
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2545
42
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2546
42
                                                            keys_to_recheck, &rowsets_to_recycle);
2547
42
        if (recheck_ret != 0) {
2548
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2549
0
                         << instance_id_;
2550
0
        }
2551
10.2k
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2552
10.2k
            const auto& current_meta = current_rowset.rowset_meta();
2553
10.2k
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2554
10.2k
                                   current_meta.rowset_id_v2()) != 0) {
2555
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2556
1
                continue;
2557
1
            }
2558
10.2k
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2559
10.2k
                                                   current_meta.tablet_id(),
2560
10.2k
                                                   current_meta.rowset_id_v2()) != 0) {
2561
0
                continue;
2562
0
            }
2563
10.2k
            std::vector<std::string> keys {key};
2564
10.2k
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2565
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2566
0
                continue;
2567
0
            }
2568
10.2k
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2569
10.2k
        }
2570
42
    });
2571
46
    if (ret != 0) {
2572
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2573
0
    }
2574
46
}
2575
2576
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2577
                                                      std::vector<std::string> rowset_keys_to_abort,
2578
                                                      std::atomic_long* num_recycled,
2579
5
                                                      RecyclerMetricsContext* metrics_context) {
2580
5
    if (rowset_keys_to_abort.empty()) {
2581
0
        return;
2582
0
    }
2583
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2584
5
                        metrics_context]() mutable {
2585
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
5
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
5
        std::vector<std::string> keys_to_delete;
2596
5
        std::vector<std::string> ref_count_keys_to_delete;
2597
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
5
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
261
            keys_to_delete.push_back(key);
2606
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
261
        }
2610
2611
5
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
5
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
261
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
261
        }
2628
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2584
3
                        metrics_context]() mutable {
2585
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
3
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
3
        std::vector<std::string> keys_to_delete;
2596
3
        std::vector<std::string> ref_count_keys_to_delete;
2597
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
3
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
3
            keys_to_delete.push_back(key);
2606
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
3
        }
2610
2611
3
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
3
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
3
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
3
        }
2628
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2584
2
                        metrics_context]() mutable {
2585
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2586
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2587
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2588
2
        if (abort_ret != 0) {
2589
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2590
0
                            "instance_id="
2591
0
                         << instance_id_;
2592
0
        }
2593
2594
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2595
2
        std::vector<std::string> keys_to_delete;
2596
2
        std::vector<std::string> ref_count_keys_to_delete;
2597
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2598
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2599
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2600
2
        if (recheck_ret != 0) {
2601
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2602
0
                         << instance_id_;
2603
0
        }
2604
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2605
258
            keys_to_delete.push_back(key);
2606
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2607
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2608
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2609
258
        }
2610
2611
2
        if (keys_to_delete.empty()) {
2612
0
            return;
2613
0
        }
2614
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2615
2
                               *metrics_context) != 0) {
2616
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2617
0
            return;
2618
0
        }
2619
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2620
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2621
258
                                                   rowset.rowset_id_v2()) != 0) {
2622
0
                return;
2623
0
            }
2624
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2625
0
                return;
2626
0
            }
2627
258
        }
2628
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2629
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2630
0
            return;
2631
0
        }
2632
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2633
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2634
0
                         << instance_id_;
2635
0
            return;
2636
0
        }
2637
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2638
2
    });
2639
5
}
2640
2641
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2642
1
    const std::string task_name = "recycle_ref_rowsets";
2643
1
    *has_unrecycled_rowsets = false;
2644
2645
1
    std::string data_rowset_ref_count_key_start =
2646
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2647
1
    std::string data_rowset_ref_count_key_end =
2648
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2649
2650
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2651
2652
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2653
1
    register_recycle_task(task_name, start_time);
2654
2655
1
    DORIS_CLOUD_DEFER {
2656
1
        unregister_recycle_task(task_name);
2657
1
        int64_t cost =
2658
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2660
1
                .tag("instance_id", instance_id_);
2661
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2655
1
    DORIS_CLOUD_DEFER {
2656
1
        unregister_recycle_task(task_name);
2657
1
        int64_t cost =
2658
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2659
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2660
1
                .tag("instance_id", instance_id_);
2661
1
    };
2662
2663
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2664
1
    std::set<int64_t> tablets_with_refs;
2665
1
    int64_t num_scanned = 0;
2666
2667
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2668
0
        ++num_scanned;
2669
0
        int64_t tablet_id;
2670
0
        std::string rowset_id;
2671
0
        std::string_view key(k);
2672
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2673
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2674
0
            return 0; // Continue scanning
2675
0
        }
2676
2677
0
        tablets_with_refs.insert(tablet_id);
2678
0
        return 0;
2679
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2680
2681
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2682
1
                         std::move(scan_func)) != 0) {
2683
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2684
0
        return -1;
2685
0
    }
2686
2687
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2688
1
             tablets_with_refs.size(), num_scanned)
2689
1
            .tag("instance_id", instance_id_);
2690
2691
    // Phase 2: Recycle each tablet
2692
1
    int64_t num_recycled_tablets = 0;
2693
1
    for (int64_t tablet_id : tablets_with_refs) {
2694
0
        if (stopped()) {
2695
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2696
0
                    .tag("instance_id", instance_id_)
2697
0
                    .tag("tablets_processed", num_recycled_tablets)
2698
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2699
0
            break;
2700
0
        }
2701
2702
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2703
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2704
0
            LOG_WARNING("failed to recycle tablet")
2705
0
                    .tag("instance_id", instance_id_)
2706
0
                    .tag("tablet_id", tablet_id);
2707
0
            return -1;
2708
0
        }
2709
0
        ++num_recycled_tablets;
2710
0
    }
2711
2712
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2713
1
            .tag("instance_id", instance_id_)
2714
1
            .tag("total_tablets", tablets_with_refs.size());
2715
2716
    // Phase 3: Scan again to check if any ref count keys still exist
2717
1
    std::unique_ptr<Transaction> txn;
2718
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2719
1
    if (err != TxnErrorCode::TXN_OK) {
2720
0
        LOG_WARNING("failed to create txn for final check")
2721
0
                .tag("instance_id", instance_id_)
2722
0
                .tag("err", err);
2723
0
        return -1;
2724
0
    }
2725
2726
1
    std::unique_ptr<RangeGetIterator> iter;
2727
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2728
1
    if (err != TxnErrorCode::TXN_OK) {
2729
0
        LOG_WARNING("failed to create range iterator for final check")
2730
0
                .tag("instance_id", instance_id_)
2731
0
                .tag("err", err);
2732
0
        return -1;
2733
0
    }
2734
2735
1
    *has_unrecycled_rowsets = iter->has_next();
2736
1
    if (*has_unrecycled_rowsets) {
2737
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2738
0
                .tag("instance_id", instance_id_);
2739
0
    }
2740
2741
1
    return 0;
2742
1
}
2743
2744
17
int InstanceRecycler::recycle_indexes() {
2745
17
    const std::string task_name = "recycle_indexes";
2746
17
    int64_t num_scanned = 0;
2747
17
    int64_t num_expired = 0;
2748
17
    int64_t num_recycled = 0;
2749
17
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2750
2751
17
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2752
17
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2753
17
    std::string index_key0;
2754
17
    std::string index_key1;
2755
17
    recycle_index_key(index_key_info0, &index_key0);
2756
17
    recycle_index_key(index_key_info1, &index_key1);
2757
2758
17
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2759
2760
17
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2761
17
    register_recycle_task(task_name, start_time);
2762
2763
17
    DORIS_CLOUD_DEFER {
2764
17
        unregister_recycle_task(task_name);
2765
17
        int64_t cost =
2766
17
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
17
        metrics_context.finish_report();
2768
17
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
17
                .tag("instance_id", instance_id_)
2770
17
                .tag("num_scanned", num_scanned)
2771
17
                .tag("num_expired", num_expired)
2772
17
                .tag("num_recycled", num_recycled);
2773
17
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2763
2
    DORIS_CLOUD_DEFER {
2764
2
        unregister_recycle_task(task_name);
2765
2
        int64_t cost =
2766
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
2
        metrics_context.finish_report();
2768
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
2
                .tag("instance_id", instance_id_)
2770
2
                .tag("num_scanned", num_scanned)
2771
2
                .tag("num_expired", num_expired)
2772
2
                .tag("num_recycled", num_recycled);
2773
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2763
15
    DORIS_CLOUD_DEFER {
2764
15
        unregister_recycle_task(task_name);
2765
15
        int64_t cost =
2766
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2767
15
        metrics_context.finish_report();
2768
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2769
15
                .tag("instance_id", instance_id_)
2770
15
                .tag("num_scanned", num_scanned)
2771
15
                .tag("num_expired", num_expired)
2772
15
                .tag("num_recycled", num_recycled);
2773
15
    };
2774
2775
17
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2776
2777
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2778
17
    std::vector<std::string_view> index_keys;
2779
17
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
10
        ++num_scanned;
2781
10
        RecycleIndexPB index_pb;
2782
10
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
10
        int64_t current_time = ::time(nullptr);
2787
10
        if (current_time <
2788
10
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
10
        ++num_expired;
2792
        // decode index_id
2793
10
        auto k1 = k;
2794
10
        k1.remove_prefix(1);
2795
10
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
10
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
10
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
10
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
10
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
10
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
10
        std::unique_ptr<Transaction> txn;
2804
10
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
10
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
10
        std::string val;
2810
10
        err = txn->get(k, &val);
2811
10
        if (err ==
2812
10
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
10
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
10
        index_pb.Clear();
2821
10
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
10
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
9
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
9
            txn->put(k, index_pb.SerializeAsString());
2828
9
            err = txn->commit();
2829
9
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
9
        }
2834
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
1
            LOG_WARNING("failed to recycle tablets under index")
2836
1
                    .tag("table_id", index_pb.table_id())
2837
1
                    .tag("instance_id", instance_id_)
2838
1
                    .tag("index_id", index_id);
2839
1
            return -1;
2840
1
        }
2841
2842
9
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
3
            std::unique_ptr<Transaction> txn;
2845
3
            err = txn_kv_->create_txn(&txn);
2846
3
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
3
            std::string index_inverted_key = versioned::index_inverted_key(
2853
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
3
            versioned_remove_all(txn.get(), meta_key);
2855
3
            txn->remove(index_key);
2856
3
            txn->remove(index_inverted_key);
2857
3
            err = txn->commit();
2858
3
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
3
        }
2863
2864
9
        metrics_context.total_recycled_num = ++num_recycled;
2865
9
        metrics_context.report();
2866
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
9
        index_keys.push_back(k);
2868
9
        return 0;
2869
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2779
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
2
        ++num_scanned;
2781
2
        RecycleIndexPB index_pb;
2782
2
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
2
        int64_t current_time = ::time(nullptr);
2787
2
        if (current_time <
2788
2
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
2
        ++num_expired;
2792
        // decode index_id
2793
2
        auto k1 = k;
2794
2
        k1.remove_prefix(1);
2795
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
2
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
2
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
2
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
2
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
2
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
2
        std::unique_ptr<Transaction> txn;
2804
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
2
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
2
        std::string val;
2810
2
        err = txn->get(k, &val);
2811
2
        if (err ==
2812
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
2
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
2
        index_pb.Clear();
2821
2
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
2
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
1
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
1
            txn->put(k, index_pb.SerializeAsString());
2828
1
            err = txn->commit();
2829
1
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
1
        }
2834
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
1
            LOG_WARNING("failed to recycle tablets under index")
2836
1
                    .tag("table_id", index_pb.table_id())
2837
1
                    .tag("instance_id", instance_id_)
2838
1
                    .tag("index_id", index_id);
2839
1
            return -1;
2840
1
        }
2841
2842
1
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
1
            std::unique_ptr<Transaction> txn;
2845
1
            err = txn_kv_->create_txn(&txn);
2846
1
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
1
            std::string index_inverted_key = versioned::index_inverted_key(
2853
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
1
            versioned_remove_all(txn.get(), meta_key);
2855
1
            txn->remove(index_key);
2856
1
            txn->remove(index_inverted_key);
2857
1
            err = txn->commit();
2858
1
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
1
        }
2863
2864
1
        metrics_context.total_recycled_num = ++num_recycled;
2865
1
        metrics_context.report();
2866
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
1
        index_keys.push_back(k);
2868
1
        return 0;
2869
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2779
8
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2780
8
        ++num_scanned;
2781
8
        RecycleIndexPB index_pb;
2782
8
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2783
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2784
0
            return -1;
2785
0
        }
2786
8
        int64_t current_time = ::time(nullptr);
2787
8
        if (current_time <
2788
8
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2789
0
            return 0;
2790
0
        }
2791
8
        ++num_expired;
2792
        // decode index_id
2793
8
        auto k1 = k;
2794
8
        k1.remove_prefix(1);
2795
8
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2796
8
        decode_key(&k1, &out);
2797
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2798
8
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2799
8
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2800
8
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2801
8
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2802
        // Change state to RECYCLING
2803
8
        std::unique_ptr<Transaction> txn;
2804
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2805
8
        if (err != TxnErrorCode::TXN_OK) {
2806
0
            LOG_WARNING("failed to create txn").tag("err", err);
2807
0
            return -1;
2808
0
        }
2809
8
        std::string val;
2810
8
        err = txn->get(k, &val);
2811
8
        if (err ==
2812
8
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
2813
0
            LOG_INFO("index {} has been recycled or committed", index_id);
2814
0
            return 0;
2815
0
        }
2816
8
        if (err != TxnErrorCode::TXN_OK) {
2817
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
2818
0
            return -1;
2819
0
        }
2820
8
        index_pb.Clear();
2821
8
        if (!index_pb.ParseFromString(val)) {
2822
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2823
0
            return -1;
2824
0
        }
2825
8
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
2826
8
            index_pb.set_state(RecycleIndexPB::RECYCLING);
2827
8
            txn->put(k, index_pb.SerializeAsString());
2828
8
            err = txn->commit();
2829
8
            if (err != TxnErrorCode::TXN_OK) {
2830
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2831
0
                return -1;
2832
0
            }
2833
8
        }
2834
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
2835
0
            LOG_WARNING("failed to recycle tablets under index")
2836
0
                    .tag("table_id", index_pb.table_id())
2837
0
                    .tag("instance_id", instance_id_)
2838
0
                    .tag("index_id", index_id);
2839
0
            return -1;
2840
0
        }
2841
2842
8
        if (index_pb.has_db_id()) {
2843
            // Recycle the versioned keys
2844
2
            std::unique_ptr<Transaction> txn;
2845
2
            err = txn_kv_->create_txn(&txn);
2846
2
            if (err != TxnErrorCode::TXN_OK) {
2847
0
                LOG_WARNING("failed to create txn").tag("err", err);
2848
0
                return -1;
2849
0
            }
2850
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
2851
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
2852
2
            std::string index_inverted_key = versioned::index_inverted_key(
2853
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
2854
2
            versioned_remove_all(txn.get(), meta_key);
2855
2
            txn->remove(index_key);
2856
2
            txn->remove(index_inverted_key);
2857
2
            err = txn->commit();
2858
2
            if (err != TxnErrorCode::TXN_OK) {
2859
0
                LOG_WARNING("failed to commit txn").tag("err", err);
2860
0
                return -1;
2861
0
            }
2862
2
        }
2863
2864
8
        metrics_context.total_recycled_num = ++num_recycled;
2865
8
        metrics_context.report();
2866
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
2867
8
        index_keys.push_back(k);
2868
8
        return 0;
2869
8
    };
2870
2871
17
    auto loop_done = [&index_keys, this]() -> int {
2872
6
        if (index_keys.empty()) return 0;
2873
5
        DORIS_CLOUD_DEFER {
2874
5
            index_keys.clear();
2875
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2873
1
        DORIS_CLOUD_DEFER {
2874
1
            index_keys.clear();
2875
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
2873
4
        DORIS_CLOUD_DEFER {
2874
4
            index_keys.clear();
2875
4
        };
2876
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
5
        return 0;
2881
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2871
2
    auto loop_done = [&index_keys, this]() -> int {
2872
2
        if (index_keys.empty()) return 0;
2873
1
        DORIS_CLOUD_DEFER {
2874
1
            index_keys.clear();
2875
1
        };
2876
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
1
        return 0;
2881
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
2871
4
    auto loop_done = [&index_keys, this]() -> int {
2872
4
        if (index_keys.empty()) return 0;
2873
4
        DORIS_CLOUD_DEFER {
2874
4
            index_keys.clear();
2875
4
        };
2876
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
2877
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
2878
0
            return -1;
2879
0
        }
2880
4
        return 0;
2881
4
    };
2882
2883
17
    if (config::enable_recycler_stats_metrics) {
2884
0
        scan_and_statistics_indexes();
2885
0
    }
2886
    // recycle_func and loop_done for scan and recycle
2887
17
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
2888
17
}
2889
2890
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
2891
8.25k
                             int64_t tablet_id) {
2892
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
2893
2894
8.25k
    std::unique_ptr<Transaction> txn;
2895
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
2896
8.25k
    if (err != TxnErrorCode::TXN_OK) {
2897
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
2898
0
                     << " tablet_id=" << tablet_id << " err=" << err;
2899
0
        return false;
2900
0
    }
2901
2902
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
2903
8.25k
    std::string tablet_idx_val;
2904
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2905
8.25k
    if (TxnErrorCode::TXN_OK != err) {
2906
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
2907
0
                     << " tablet_id=" << tablet_id << " err=" << err
2908
0
                     << " key=" << hex(tablet_idx_key);
2909
0
        return false;
2910
0
    }
2911
2912
8.25k
    TabletIndexPB tablet_idx_pb;
2913
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
2914
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
2915
0
                     << " tablet_id=" << tablet_id;
2916
0
        return false;
2917
0
    }
2918
2919
8.25k
    if (!tablet_idx_pb.has_db_id()) {
2920
        // In the previous version, the db_id was not set in the index_pb.
2921
        // If updating to the version which enable txn lazy commit, the db_id will be set.
2922
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
2923
0
                  << " instance_id=" << instance_id
2924
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
2925
0
        return true;
2926
0
    }
2927
2928
8.25k
    std::string ver_val;
2929
8.25k
    std::string ver_key =
2930
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
2931
8.25k
                                   tablet_idx_pb.partition_id()});
2932
8.25k
    err = txn->get(ver_key, &ver_val);
2933
2934
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
2935
216
        LOG(INFO) << ""
2936
216
                     "partition version not found, instance_id="
2937
216
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
2938
216
                  << " table_id=" << tablet_idx_pb.table_id()
2939
216
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
2940
216
                  << " key=" << hex(ver_key);
2941
216
        return true;
2942
216
    }
2943
2944
8.03k
    if (TxnErrorCode::TXN_OK != err) {
2945
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
2946
0
                     << " db_id=" << tablet_idx_pb.db_id()
2947
0
                     << " table_id=" << tablet_idx_pb.table_id()
2948
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2949
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
2950
0
        return false;
2951
0
    }
2952
2953
8.03k
    VersionPB version_pb;
2954
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
2955
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
2956
0
                     << " db_id=" << tablet_idx_pb.db_id()
2957
0
                     << " table_id=" << tablet_idx_pb.table_id()
2958
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
2959
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
2960
0
        return false;
2961
0
    }
2962
2963
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
2964
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
2965
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
2966
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
2967
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
2968
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
2969
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
2970
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
2971
4.00k
                     << " key=" << hex(ver_key);
2972
4.00k
        return false;
2973
4.00k
    }
2974
4.03k
    return true;
2975
8.03k
}
2976
2977
15
int InstanceRecycler::recycle_partitions() {
2978
15
    const std::string task_name = "recycle_partitions";
2979
15
    int64_t num_scanned = 0;
2980
15
    int64_t num_expired = 0;
2981
15
    int64_t num_recycled = 0;
2982
15
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2983
2984
15
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
2985
15
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
2986
15
    std::string part_key0;
2987
15
    std::string part_key1;
2988
15
    recycle_partition_key(part_key_info0, &part_key0);
2989
15
    recycle_partition_key(part_key_info1, &part_key1);
2990
2991
15
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
2992
2993
15
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2994
15
    register_recycle_task(task_name, start_time);
2995
2996
15
    DORIS_CLOUD_DEFER {
2997
15
        unregister_recycle_task(task_name);
2998
15
        int64_t cost =
2999
15
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
15
        metrics_context.finish_report();
3001
15
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
15
                .tag("instance_id", instance_id_)
3003
15
                .tag("num_scanned", num_scanned)
3004
15
                .tag("num_expired", num_expired)
3005
15
                .tag("num_recycled", num_recycled);
3006
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2996
2
    DORIS_CLOUD_DEFER {
2997
2
        unregister_recycle_task(task_name);
2998
2
        int64_t cost =
2999
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
2
        metrics_context.finish_report();
3001
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
2
                .tag("instance_id", instance_id_)
3003
2
                .tag("num_scanned", num_scanned)
3004
2
                .tag("num_expired", num_expired)
3005
2
                .tag("num_recycled", num_recycled);
3006
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
2996
13
    DORIS_CLOUD_DEFER {
2997
13
        unregister_recycle_task(task_name);
2998
13
        int64_t cost =
2999
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3000
13
        metrics_context.finish_report();
3001
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3002
13
                .tag("instance_id", instance_id_)
3003
13
                .tag("num_scanned", num_scanned)
3004
13
                .tag("num_expired", num_expired)
3005
13
                .tag("num_recycled", num_recycled);
3006
13
    };
3007
3008
15
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3009
3010
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3011
15
    std::vector<std::string_view> partition_keys;
3012
15
    std::vector<std::string> partition_version_keys;
3013
15
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
9
        ++num_scanned;
3015
9
        RecyclePartitionPB part_pb;
3016
9
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
9
        int64_t current_time = ::time(nullptr);
3021
9
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
9
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
9
        ++num_expired;
3026
        // decode partition_id
3027
9
        auto k1 = k;
3028
9
        k1.remove_prefix(1);
3029
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
9
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
9
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
9
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
9
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
9
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
9
        std::unique_ptr<Transaction> txn;
3038
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
9
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
9
        std::string val;
3044
9
        err = txn->get(k, &val);
3045
9
        if (err ==
3046
9
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
9
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
9
        part_pb.Clear();
3055
9
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
9
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
8
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
8
            txn->put(k, part_pb.SerializeAsString());
3063
8
            err = txn->commit();
3064
8
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
8
        }
3069
3070
9
        int ret = 0;
3071
33
        for (int64_t index_id : part_pb.index_id()) {
3072
33
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
1
                LOG_WARNING("failed to recycle tablets under partition")
3074
1
                        .tag("table_id", part_pb.table_id())
3075
1
                        .tag("instance_id", instance_id_)
3076
1
                        .tag("index_id", index_id)
3077
1
                        .tag("partition_id", partition_id);
3078
1
                ret = -1;
3079
1
            }
3080
33
        }
3081
9
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
8
            std::unique_ptr<Transaction> txn;
3084
8
            err = txn_kv_->create_txn(&txn);
3085
8
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
8
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
8
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
8
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
8
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
8
            std::string partition_version_key =
3094
8
                    versioned::partition_version_key({instance_id_, partition_id});
3095
8
            versioned_remove_all(txn.get(), meta_key);
3096
8
            txn->remove(index_key);
3097
8
            txn->remove(inverted_index_key);
3098
8
            versioned_remove_all(txn.get(), partition_version_key);
3099
8
            err = txn->commit();
3100
8
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
8
        }
3105
3106
9
        if (ret == 0) {
3107
8
            ++num_recycled;
3108
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
8
            partition_keys.push_back(k);
3110
8
            if (part_pb.db_id() > 0) {
3111
8
                partition_version_keys.push_back(partition_version_key(
3112
8
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
8
            }
3114
8
            metrics_context.total_recycled_num = num_recycled;
3115
8
            metrics_context.report();
3116
8
        }
3117
9
        return ret;
3118
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3013
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
2
        ++num_scanned;
3015
2
        RecyclePartitionPB part_pb;
3016
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
2
        int64_t current_time = ::time(nullptr);
3021
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
2
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
2
        ++num_expired;
3026
        // decode partition_id
3027
2
        auto k1 = k;
3028
2
        k1.remove_prefix(1);
3029
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
2
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
2
        std::unique_ptr<Transaction> txn;
3038
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
2
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
2
        std::string val;
3044
2
        err = txn->get(k, &val);
3045
2
        if (err ==
3046
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
2
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
2
        part_pb.Clear();
3055
2
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
1
            txn->put(k, part_pb.SerializeAsString());
3063
1
            err = txn->commit();
3064
1
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
1
        }
3069
3070
2
        int ret = 0;
3071
2
        for (int64_t index_id : part_pb.index_id()) {
3072
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
1
                LOG_WARNING("failed to recycle tablets under partition")
3074
1
                        .tag("table_id", part_pb.table_id())
3075
1
                        .tag("instance_id", instance_id_)
3076
1
                        .tag("index_id", index_id)
3077
1
                        .tag("partition_id", partition_id);
3078
1
                ret = -1;
3079
1
            }
3080
2
        }
3081
2
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
1
            std::unique_ptr<Transaction> txn;
3084
1
            err = txn_kv_->create_txn(&txn);
3085
1
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
1
            std::string partition_version_key =
3094
1
                    versioned::partition_version_key({instance_id_, partition_id});
3095
1
            versioned_remove_all(txn.get(), meta_key);
3096
1
            txn->remove(index_key);
3097
1
            txn->remove(inverted_index_key);
3098
1
            versioned_remove_all(txn.get(), partition_version_key);
3099
1
            err = txn->commit();
3100
1
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
1
        }
3105
3106
2
        if (ret == 0) {
3107
1
            ++num_recycled;
3108
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
1
            partition_keys.push_back(k);
3110
1
            if (part_pb.db_id() > 0) {
3111
1
                partition_version_keys.push_back(partition_version_key(
3112
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
1
            }
3114
1
            metrics_context.total_recycled_num = num_recycled;
3115
1
            metrics_context.report();
3116
1
        }
3117
2
        return ret;
3118
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3013
7
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3014
7
        ++num_scanned;
3015
7
        RecyclePartitionPB part_pb;
3016
7
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3017
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3018
0
            return -1;
3019
0
        }
3020
7
        int64_t current_time = ::time(nullptr);
3021
7
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3022
7
                                                            &earlest_ts)) { // not expired
3023
0
            return 0;
3024
0
        }
3025
7
        ++num_expired;
3026
        // decode partition_id
3027
7
        auto k1 = k;
3028
7
        k1.remove_prefix(1);
3029
7
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3030
7
        decode_key(&k1, &out);
3031
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3032
7
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3033
7
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3034
7
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3035
7
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3036
        // Change state to RECYCLING
3037
7
        std::unique_ptr<Transaction> txn;
3038
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3039
7
        if (err != TxnErrorCode::TXN_OK) {
3040
0
            LOG_WARNING("failed to create txn").tag("err", err);
3041
0
            return -1;
3042
0
        }
3043
7
        std::string val;
3044
7
        err = txn->get(k, &val);
3045
7
        if (err ==
3046
7
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3047
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3048
0
            return 0;
3049
0
        }
3050
7
        if (err != TxnErrorCode::TXN_OK) {
3051
0
            LOG_WARNING("failed to get kv");
3052
0
            return -1;
3053
0
        }
3054
7
        part_pb.Clear();
3055
7
        if (!part_pb.ParseFromString(val)) {
3056
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3057
0
            return -1;
3058
0
        }
3059
        // Partitions with PREPARED state MUST have no data
3060
7
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3061
7
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3062
7
            txn->put(k, part_pb.SerializeAsString());
3063
7
            err = txn->commit();
3064
7
            if (err != TxnErrorCode::TXN_OK) {
3065
0
                LOG_WARNING("failed to commit txn: {}", err);
3066
0
                return -1;
3067
0
            }
3068
7
        }
3069
3070
7
        int ret = 0;
3071
31
        for (int64_t index_id : part_pb.index_id()) {
3072
31
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3073
0
                LOG_WARNING("failed to recycle tablets under partition")
3074
0
                        .tag("table_id", part_pb.table_id())
3075
0
                        .tag("instance_id", instance_id_)
3076
0
                        .tag("index_id", index_id)
3077
0
                        .tag("partition_id", partition_id);
3078
0
                ret = -1;
3079
0
            }
3080
31
        }
3081
7
        if (ret == 0 && part_pb.has_db_id()) {
3082
            // Recycle the versioned keys
3083
7
            std::unique_ptr<Transaction> txn;
3084
7
            err = txn_kv_->create_txn(&txn);
3085
7
            if (err != TxnErrorCode::TXN_OK) {
3086
0
                LOG_WARNING("failed to create txn").tag("err", err);
3087
0
                return -1;
3088
0
            }
3089
7
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3090
7
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3091
7
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3092
7
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3093
7
            std::string partition_version_key =
3094
7
                    versioned::partition_version_key({instance_id_, partition_id});
3095
7
            versioned_remove_all(txn.get(), meta_key);
3096
7
            txn->remove(index_key);
3097
7
            txn->remove(inverted_index_key);
3098
7
            versioned_remove_all(txn.get(), partition_version_key);
3099
7
            err = txn->commit();
3100
7
            if (err != TxnErrorCode::TXN_OK) {
3101
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3102
0
                return -1;
3103
0
            }
3104
7
        }
3105
3106
7
        if (ret == 0) {
3107
7
            ++num_recycled;
3108
7
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3109
7
            partition_keys.push_back(k);
3110
7
            if (part_pb.db_id() > 0) {
3111
7
                partition_version_keys.push_back(partition_version_key(
3112
7
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3113
7
            }
3114
7
            metrics_context.total_recycled_num = num_recycled;
3115
7
            metrics_context.report();
3116
7
        }
3117
7
        return ret;
3118
7
    };
3119
3120
15
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
5
        if (partition_keys.empty()) return 0;
3122
4
        DORIS_CLOUD_DEFER {
3123
4
            partition_keys.clear();
3124
4
            partition_version_keys.clear();
3125
4
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3122
1
        DORIS_CLOUD_DEFER {
3123
1
            partition_keys.clear();
3124
1
            partition_version_keys.clear();
3125
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3122
3
        DORIS_CLOUD_DEFER {
3123
3
            partition_keys.clear();
3124
3
            partition_version_keys.clear();
3125
3
        };
3126
4
        std::unique_ptr<Transaction> txn;
3127
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
4
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
8
        for (auto& k : partition_keys) {
3133
8
            txn->remove(k);
3134
8
        }
3135
8
        for (auto& k : partition_version_keys) {
3136
8
            txn->remove(k);
3137
8
        }
3138
4
        err = txn->commit();
3139
4
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
4
        return 0;
3145
4
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3120
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
2
        if (partition_keys.empty()) return 0;
3122
1
        DORIS_CLOUD_DEFER {
3123
1
            partition_keys.clear();
3124
1
            partition_version_keys.clear();
3125
1
        };
3126
1
        std::unique_ptr<Transaction> txn;
3127
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
1
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
1
        for (auto& k : partition_keys) {
3133
1
            txn->remove(k);
3134
1
        }
3135
1
        for (auto& k : partition_version_keys) {
3136
1
            txn->remove(k);
3137
1
        }
3138
1
        err = txn->commit();
3139
1
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
1
        return 0;
3145
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3120
3
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3121
3
        if (partition_keys.empty()) return 0;
3122
3
        DORIS_CLOUD_DEFER {
3123
3
            partition_keys.clear();
3124
3
            partition_version_keys.clear();
3125
3
        };
3126
3
        std::unique_ptr<Transaction> txn;
3127
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3128
3
        if (err != TxnErrorCode::TXN_OK) {
3129
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3130
0
            return -1;
3131
0
        }
3132
7
        for (auto& k : partition_keys) {
3133
7
            txn->remove(k);
3134
7
        }
3135
7
        for (auto& k : partition_version_keys) {
3136
7
            txn->remove(k);
3137
7
        }
3138
3
        err = txn->commit();
3139
3
        if (err != TxnErrorCode::TXN_OK) {
3140
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3141
0
                         << " err=" << err;
3142
0
            return -1;
3143
0
        }
3144
3
        return 0;
3145
3
    };
3146
3147
15
    if (config::enable_recycler_stats_metrics) {
3148
0
        scan_and_statistics_partitions();
3149
0
    }
3150
    // recycle_func and loop_done for scan and recycle
3151
15
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3152
15
}
3153
3154
14
int InstanceRecycler::recycle_versions() {
3155
14
    if (should_recycle_versioned_keys()) {
3156
2
        return recycle_orphan_partitions();
3157
2
    }
3158
3159
12
    int64_t num_scanned = 0;
3160
12
    int64_t num_recycled = 0;
3161
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3162
3163
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3164
3165
12
    auto start_time = steady_clock::now();
3166
3167
12
    DORIS_CLOUD_DEFER {
3168
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3169
12
        metrics_context.finish_report();
3170
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3171
12
                .tag("instance_id", instance_id_)
3172
12
                .tag("num_scanned", num_scanned)
3173
12
                .tag("num_recycled", num_recycled);
3174
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3167
12
    DORIS_CLOUD_DEFER {
3168
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3169
12
        metrics_context.finish_report();
3170
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3171
12
                .tag("instance_id", instance_id_)
3172
12
                .tag("num_scanned", num_scanned)
3173
12
                .tag("num_recycled", num_recycled);
3174
12
    };
3175
3176
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3177
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3178
12
    int64_t last_scanned_table_id = 0;
3179
12
    bool is_recycled = false; // Is last scanned kv recycled
3180
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3181
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3182
2
        ++num_scanned;
3183
2
        auto k1 = k;
3184
2
        k1.remove_prefix(1);
3185
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3186
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3187
2
        decode_key(&k1, &out);
3188
2
        DCHECK_EQ(out.size(), 6) << k;
3189
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3190
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3191
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3192
0
            return 0;
3193
0
        }
3194
2
        last_scanned_table_id = table_id;
3195
2
        is_recycled = false;
3196
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3197
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3198
2
        std::unique_ptr<Transaction> txn;
3199
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3200
2
        if (err != TxnErrorCode::TXN_OK) {
3201
0
            return -1;
3202
0
        }
3203
2
        std::unique_ptr<RangeGetIterator> iter;
3204
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3205
2
        if (err != TxnErrorCode::TXN_OK) {
3206
0
            return -1;
3207
0
        }
3208
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3209
1
            return 0;
3210
1
        }
3211
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3212
        // 1. Remove all partition version kvs of this table
3213
1
        auto partition_version_key_begin =
3214
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3215
1
        auto partition_version_key_end =
3216
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3217
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3218
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3219
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3220
1
                     << " table_id=" << table_id;
3221
        // 2. Remove the table version kv of this table
3222
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3223
1
        txn->remove(tbl_version_key);
3224
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3225
        // 3. Remove mow delete bitmap update lock and tablet job lock
3226
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3227
1
        txn->remove(lock_key);
3228
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3229
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3230
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3231
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3232
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3233
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3234
1
                     << " table_id=" << table_id;
3235
1
        err = txn->commit();
3236
1
        if (err != TxnErrorCode::TXN_OK) {
3237
0
            return -1;
3238
0
        }
3239
1
        metrics_context.total_recycled_num = ++num_recycled;
3240
1
        metrics_context.report();
3241
1
        is_recycled = true;
3242
1
        return 0;
3243
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3181
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3182
2
        ++num_scanned;
3183
2
        auto k1 = k;
3184
2
        k1.remove_prefix(1);
3185
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3186
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3187
2
        decode_key(&k1, &out);
3188
2
        DCHECK_EQ(out.size(), 6) << k;
3189
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3190
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3191
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3192
0
            return 0;
3193
0
        }
3194
2
        last_scanned_table_id = table_id;
3195
2
        is_recycled = false;
3196
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3197
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3198
2
        std::unique_ptr<Transaction> txn;
3199
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3200
2
        if (err != TxnErrorCode::TXN_OK) {
3201
0
            return -1;
3202
0
        }
3203
2
        std::unique_ptr<RangeGetIterator> iter;
3204
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3205
2
        if (err != TxnErrorCode::TXN_OK) {
3206
0
            return -1;
3207
0
        }
3208
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3209
1
            return 0;
3210
1
        }
3211
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3212
        // 1. Remove all partition version kvs of this table
3213
1
        auto partition_version_key_begin =
3214
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3215
1
        auto partition_version_key_end =
3216
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3217
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3218
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3219
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3220
1
                     << " table_id=" << table_id;
3221
        // 2. Remove the table version kv of this table
3222
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3223
1
        txn->remove(tbl_version_key);
3224
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3225
        // 3. Remove mow delete bitmap update lock and tablet job lock
3226
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3227
1
        txn->remove(lock_key);
3228
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3229
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3230
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3231
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3232
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3233
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3234
1
                     << " table_id=" << table_id;
3235
1
        err = txn->commit();
3236
1
        if (err != TxnErrorCode::TXN_OK) {
3237
0
            return -1;
3238
0
        }
3239
1
        metrics_context.total_recycled_num = ++num_recycled;
3240
1
        metrics_context.report();
3241
1
        is_recycled = true;
3242
1
        return 0;
3243
1
    };
3244
3245
12
    if (config::enable_recycler_stats_metrics) {
3246
0
        scan_and_statistics_versions();
3247
0
    }
3248
    // recycle_func and loop_done for scan and recycle
3249
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3250
14
}
3251
3252
3
int InstanceRecycler::recycle_orphan_partitions() {
3253
3
    int64_t num_scanned = 0;
3254
3
    int64_t num_recycled = 0;
3255
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3256
3257
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3258
3
            .tag("instance_id", instance_id_);
3259
3260
3
    auto start_time = steady_clock::now();
3261
3262
3
    DORIS_CLOUD_DEFER {
3263
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3264
3
        metrics_context.finish_report();
3265
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3266
3
                .tag("instance_id", instance_id_)
3267
3
                .tag("num_scanned", num_scanned)
3268
3
                .tag("num_recycled", num_recycled);
3269
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3262
3
    DORIS_CLOUD_DEFER {
3263
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3264
3
        metrics_context.finish_report();
3265
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3266
3
                .tag("instance_id", instance_id_)
3267
3
                .tag("num_scanned", num_scanned)
3268
3
                .tag("num_recycled", num_recycled);
3269
3
    };
3270
3271
3
    bool is_empty_table = false;        // whether the table has no indexes
3272
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3273
3
    int64_t current_table_id = 0;       // current scanning table id
3274
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3275
3
                         &current_table_id, &is_table_kvs_recycled,
3276
3
                         this](std::string_view k, std::string_view) {
3277
2
        ++num_scanned;
3278
3279
2
        std::string_view k1(k);
3280
2
        int64_t db_id, table_id, partition_id;
3281
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3282
2
                                                            &partition_id)) {
3283
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3284
0
            return -1;
3285
2
        } else if (table_id != current_table_id) {
3286
2
            current_table_id = table_id;
3287
2
            is_table_kvs_recycled = false;
3288
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3289
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3290
2
            if (err != TxnErrorCode::TXN_OK) {
3291
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3292
0
                             << " table_id=" << table_id << " err=" << err;
3293
0
                return -1;
3294
0
            }
3295
2
        }
3296
3297
2
        if (!is_empty_table) {
3298
            // table is not empty, skip recycle
3299
1
            return 0;
3300
1
        }
3301
3302
1
        std::unique_ptr<Transaction> txn;
3303
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3304
1
        if (err != TxnErrorCode::TXN_OK) {
3305
0
            return -1;
3306
0
        }
3307
3308
        // 1. Remove all partition related kvs
3309
1
        std::string partition_meta_key =
3310
1
                versioned::meta_partition_key({instance_id_, partition_id});
3311
1
        std::string partition_index_key =
3312
1
                versioned::partition_index_key({instance_id_, partition_id});
3313
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3314
1
                {instance_id_, db_id, table_id, partition_id});
3315
1
        std::string partition_version_key =
3316
1
                versioned::partition_version_key({instance_id_, partition_id});
3317
1
        txn->remove(partition_index_key);
3318
1
        txn->remove(partition_inverted_key);
3319
1
        versioned_remove_all(txn.get(), partition_meta_key);
3320
1
        versioned_remove_all(txn.get(), partition_version_key);
3321
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3322
1
                     << " table_id=" << table_id << " db_id=" << db_id
3323
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3324
1
                     << " partition_version_key=" << hex(partition_version_key);
3325
3326
1
        if (!is_table_kvs_recycled) {
3327
1
            is_table_kvs_recycled = true;
3328
3329
            // 2. Remove the table version kv of this table
3330
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3331
1
            versioned_remove_all(txn.get(), table_version_key);
3332
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3333
            // 3. Remove mow delete bitmap update lock and tablet job lock
3334
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3335
1
            txn->remove(lock_key);
3336
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3337
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3338
1
            std::string tablet_job_key_end =
3339
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3340
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3341
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3342
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3343
1
                         << " table_id=" << table_id;
3344
1
        }
3345
3346
1
        err = txn->commit();
3347
1
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            return -1;
3349
0
        }
3350
1
        metrics_context.total_recycled_num = ++num_recycled;
3351
1
        metrics_context.report();
3352
1
        return 0;
3353
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3276
2
                         this](std::string_view k, std::string_view) {
3277
2
        ++num_scanned;
3278
3279
2
        std::string_view k1(k);
3280
2
        int64_t db_id, table_id, partition_id;
3281
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3282
2
                                                            &partition_id)) {
3283
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3284
0
            return -1;
3285
2
        } else if (table_id != current_table_id) {
3286
2
            current_table_id = table_id;
3287
2
            is_table_kvs_recycled = false;
3288
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3289
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3290
2
            if (err != TxnErrorCode::TXN_OK) {
3291
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3292
0
                             << " table_id=" << table_id << " err=" << err;
3293
0
                return -1;
3294
0
            }
3295
2
        }
3296
3297
2
        if (!is_empty_table) {
3298
            // table is not empty, skip recycle
3299
1
            return 0;
3300
1
        }
3301
3302
1
        std::unique_ptr<Transaction> txn;
3303
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3304
1
        if (err != TxnErrorCode::TXN_OK) {
3305
0
            return -1;
3306
0
        }
3307
3308
        // 1. Remove all partition related kvs
3309
1
        std::string partition_meta_key =
3310
1
                versioned::meta_partition_key({instance_id_, partition_id});
3311
1
        std::string partition_index_key =
3312
1
                versioned::partition_index_key({instance_id_, partition_id});
3313
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3314
1
                {instance_id_, db_id, table_id, partition_id});
3315
1
        std::string partition_version_key =
3316
1
                versioned::partition_version_key({instance_id_, partition_id});
3317
1
        txn->remove(partition_index_key);
3318
1
        txn->remove(partition_inverted_key);
3319
1
        versioned_remove_all(txn.get(), partition_meta_key);
3320
1
        versioned_remove_all(txn.get(), partition_version_key);
3321
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3322
1
                     << " table_id=" << table_id << " db_id=" << db_id
3323
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3324
1
                     << " partition_version_key=" << hex(partition_version_key);
3325
3326
1
        if (!is_table_kvs_recycled) {
3327
1
            is_table_kvs_recycled = true;
3328
3329
            // 2. Remove the table version kv of this table
3330
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3331
1
            versioned_remove_all(txn.get(), table_version_key);
3332
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3333
            // 3. Remove mow delete bitmap update lock and tablet job lock
3334
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3335
1
            txn->remove(lock_key);
3336
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3337
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3338
1
            std::string tablet_job_key_end =
3339
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3340
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3341
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3342
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3343
1
                         << " table_id=" << table_id;
3344
1
        }
3345
3346
1
        err = txn->commit();
3347
1
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            return -1;
3349
0
        }
3350
1
        metrics_context.total_recycled_num = ++num_recycled;
3351
1
        metrics_context.report();
3352
1
        return 0;
3353
1
    };
3354
3355
    // recycle_func and loop_done for scan and recycle
3356
3
    return scan_and_recycle(
3357
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3358
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3359
3
            std::move(recycle_func));
3360
3
}
3361
3362
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3363
                                      RecyclerMetricsContext& metrics_context,
3364
54
                                      int64_t partition_id) {
3365
54
    int64_t num_scanned = 0;
3366
54
    std::atomic_long num_recycled = 0;
3367
3368
54
    std::string tablet_key_begin, tablet_key_end;
3369
54
    std::string stats_key_begin, stats_key_end;
3370
54
    std::string job_key_begin, job_key_end;
3371
3372
54
    std::string tablet_belongs;
3373
54
    if (partition_id > 0) {
3374
        // recycle tablets in a partition belonging to the index
3375
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3376
33
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3377
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3378
33
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3379
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3380
33
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3381
33
        tablet_belongs = "partition";
3382
33
    } else {
3383
        // recycle tablets in the index
3384
21
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3385
21
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3386
21
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3387
21
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3388
21
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3389
21
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3390
21
        tablet_belongs = "index";
3391
21
    }
3392
3393
54
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3394
54
            .tag("table_id", table_id)
3395
54
            .tag("index_id", index_id)
3396
54
            .tag("partition_id", partition_id);
3397
3398
54
    auto start_time = steady_clock::now();
3399
3400
54
    DORIS_CLOUD_DEFER {
3401
54
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
54
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
54
                .tag("instance_id", instance_id_)
3404
54
                .tag("table_id", table_id)
3405
54
                .tag("index_id", index_id)
3406
54
                .tag("partition_id", partition_id)
3407
54
                .tag("num_scanned", num_scanned)
3408
54
                .tag("num_recycled", num_recycled);
3409
54
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3400
4
    DORIS_CLOUD_DEFER {
3401
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
4
                .tag("instance_id", instance_id_)
3404
4
                .tag("table_id", table_id)
3405
4
                .tag("index_id", index_id)
3406
4
                .tag("partition_id", partition_id)
3407
4
                .tag("num_scanned", num_scanned)
3408
4
                .tag("num_recycled", num_recycled);
3409
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3400
50
    DORIS_CLOUD_DEFER {
3401
50
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3402
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3403
50
                .tag("instance_id", instance_id_)
3404
50
                .tag("table_id", table_id)
3405
50
                .tag("index_id", index_id)
3406
50
                .tag("partition_id", partition_id)
3407
50
                .tag("num_scanned", num_scanned)
3408
50
                .tag("num_recycled", num_recycled);
3409
50
    };
3410
3411
    // The tablet key and id which have been recycled.
3412
54
    struct TabletInfo {
3413
54
        std::string_view tablet_meta_key;
3414
54
        int64_t tablet_id;
3415
54
    };
3416
54
    SyncExecutor<TabletInfo> sync_executor(
3417
54
            _thread_pool_group.recycle_tablet_pool,
3418
54
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3419
54
                        index_id, partition_id),
3420
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3420
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3420
243
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3421
3422
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3423
54
    std::vector<std::string> init_rs_keys;
3424
54
    bool has_failure = false;
3425
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
8.25k
        ++num_scanned;
3427
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
4.00k
            has_failure = true;
3439
4.00k
            return -1;
3440
4.00k
        }
3441
3442
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
4.25k
        sync_executor.add(
3444
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
2
                        LOG_WARNING("failed to recycle tablet")
3447
2
                                .tag("instance_id", instance_id_)
3448
2
                                .tag("tablet_id", tid);
3449
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
2
                    }
3451
4.25k
                    ++num_recycled;
3452
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3444
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
0
                        LOG_WARNING("failed to recycle tablet")
3447
0
                                .tag("instance_id", instance_id_)
3448
0
                                .tag("tablet_id", tid);
3449
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
0
                    }
3451
4.00k
                    ++num_recycled;
3452
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3444
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
2
                        LOG_WARNING("failed to recycle tablet")
3447
2
                                .tag("instance_id", instance_id_)
3448
2
                                .tag("tablet_id", tid);
3449
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
2
                    }
3451
250
                    ++num_recycled;
3452
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
252
                });
3455
4.25k
        return 0;
3456
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3425
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
8.00k
        ++num_scanned;
3427
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
4.00k
            has_failure = true;
3439
4.00k
            return -1;
3440
4.00k
        }
3441
3442
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
4.00k
        sync_executor.add(
3444
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
4.00k
                        LOG_WARNING("failed to recycle tablet")
3447
4.00k
                                .tag("instance_id", instance_id_)
3448
4.00k
                                .tag("tablet_id", tid);
3449
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
4.00k
                    }
3451
4.00k
                    ++num_recycled;
3452
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
4.00k
                });
3455
4.00k
        return 0;
3456
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3425
253
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3426
253
        ++num_scanned;
3427
253
        doris::TabletMetaCloudPB tablet_meta_pb;
3428
253
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3429
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3430
0
            has_failure = true;
3431
0
            return -1;
3432
0
        }
3433
253
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3434
3435
253
        if (config::enable_recycler_check_lazy_txn_finished &&
3436
253
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3437
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3438
1
            has_failure = true;
3439
1
            return -1;
3440
1
        }
3441
3442
253
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3443
252
        sync_executor.add(
3444
252
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3445
252
                    if (recycle_tablet(tid, metrics_context) != 0) {
3446
252
                        LOG_WARNING("failed to recycle tablet")
3447
252
                                .tag("instance_id", instance_id_)
3448
252
                                .tag("tablet_id", tid);
3449
252
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3450
252
                    }
3451
252
                    ++num_recycled;
3452
252
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3453
252
                    return {.tablet_meta_key = k, .tablet_id = tid};
3454
252
                });
3455
252
        return 0;
3456
252
    };
3457
3458
54
    auto loop_done = [&, this]() -> int {
3459
54
        int ret = 0;
3460
54
        bool finished = true;
3461
54
        bool has_empty_key = false;
3462
54
        DORIS_CLOUD_DEFER {
3463
54
            init_rs_keys.clear();
3464
54
            has_failure = false;
3465
54
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3462
4
        DORIS_CLOUD_DEFER {
3463
4
            init_rs_keys.clear();
3464
4
            has_failure = false;
3465
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3462
50
        DORIS_CLOUD_DEFER {
3463
50
            init_rs_keys.clear();
3464
50
            has_failure = false;
3465
50
        };
3466
54
        auto tablets_info = sync_executor.when_all(&finished);
3467
54
        if (!finished) {
3468
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
1
            return -1;
3470
1
        }
3471
3472
53
        size_t size_before_erase = tablets_info.size();
3473
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3473
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3473
251
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
53
        if (tablets_info.empty()) {
3475
2
            return size_before_erase == 0 ? 0 : -1;
3476
51
        } else if (size_before_erase != tablets_info.size()) {
3477
1
            has_empty_key = true;
3478
1
        }
3479
3480
51
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3482
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3482
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
958
        });
3485
51
        std::unique_ptr<Transaction> txn;
3486
51
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
51
        std::string tablet_key_end;
3491
51
        if (!tablets_info.empty()) {
3492
51
            if (!has_empty_key && !has_failure) {
3493
49
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
49
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
49
            } else {
3496
8
                for (auto& tablet_info : tablets_info) {
3497
8
                    txn->remove(tablet_info.tablet_meta_key);
3498
8
                }
3499
2
            }
3500
51
        }
3501
51
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
7
            std::vector<std::string> versioned_idx_keys;
3504
7
            versioned_idx_keys.reserve(tablets_info.size());
3505
8
            for (const auto& tablet_info : tablets_info) {
3506
8
                versioned_idx_keys.push_back(
3507
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
8
            }
3509
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
7
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
8
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
8
                const auto& tablet_info = tablets_info[i];
3524
8
                TabletIndexPB tablet_index_pb;
3525
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
8
                         tablet_info.tablet_id});
3535
8
                txn->remove(versioned_inverted_idx_key);
3536
8
                txn->remove(versioned_idx_keys[i]);
3537
8
            }
3538
8
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
8
                LOG_INFO("remove versioned tablet compact stats key")
3542
8
                        .tag("compact_stats_key", hex(k));
3543
8
                versioned_remove_all(txn.get(), k);
3544
8
            }
3545
8
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
8
                versioned_remove_all(txn.get(), k);
3550
8
            }
3551
8
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
8
                versioned_remove_all(txn.get(), k);
3556
8
            }
3557
7
        }
3558
4.25k
        for (auto& tablet_info : tablets_info) {
3559
4.25k
            std::string k;
3560
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
4.25k
            txn->remove(k);
3562
4.25k
        }
3563
4.25k
        for (auto& tablet_info : tablets_info) {
3564
4.25k
            std::string k;
3565
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
4.25k
            txn->remove(k);
3567
4.25k
        }
3568
51
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
51
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
51
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
1
                         << ", err=" << err;
3575
1
            return -1;
3576
1
        }
3577
50
        return ret;
3578
51
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3458
4
    auto loop_done = [&, this]() -> int {
3459
4
        int ret = 0;
3460
4
        bool finished = true;
3461
4
        bool has_empty_key = false;
3462
4
        DORIS_CLOUD_DEFER {
3463
4
            init_rs_keys.clear();
3464
4
            has_failure = false;
3465
4
        };
3466
4
        auto tablets_info = sync_executor.when_all(&finished);
3467
4
        if (!finished) {
3468
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
0
            return -1;
3470
0
        }
3471
3472
4
        size_t size_before_erase = tablets_info.size();
3473
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
4
        if (tablets_info.empty()) {
3475
2
            return size_before_erase == 0 ? 0 : -1;
3476
2
        } else if (size_before_erase != tablets_info.size()) {
3477
0
            has_empty_key = true;
3478
0
        }
3479
3480
2
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
2
        });
3485
2
        std::unique_ptr<Transaction> txn;
3486
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
2
        std::string tablet_key_end;
3491
2
        if (!tablets_info.empty()) {
3492
2
            if (!has_empty_key && !has_failure) {
3493
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
2
            } else {
3496
0
                for (auto& tablet_info : tablets_info) {
3497
0
                    txn->remove(tablet_info.tablet_meta_key);
3498
0
                }
3499
0
            }
3500
2
        }
3501
2
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
0
            std::vector<std::string> versioned_idx_keys;
3504
0
            versioned_idx_keys.reserve(tablets_info.size());
3505
0
            for (const auto& tablet_info : tablets_info) {
3506
0
                versioned_idx_keys.push_back(
3507
0
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
0
            }
3509
0
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
0
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
0
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
0
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
0
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
0
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
0
                const auto& tablet_info = tablets_info[i];
3524
0
                TabletIndexPB tablet_index_pb;
3525
0
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
0
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
0
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
0
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
0
                         tablet_info.tablet_id});
3535
0
                txn->remove(versioned_inverted_idx_key);
3536
0
                txn->remove(versioned_idx_keys[i]);
3537
0
            }
3538
0
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
0
                LOG_INFO("remove versioned tablet compact stats key")
3542
0
                        .tag("compact_stats_key", hex(k));
3543
0
                versioned_remove_all(txn.get(), k);
3544
0
            }
3545
0
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
0
                versioned_remove_all(txn.get(), k);
3550
0
            }
3551
0
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
0
                versioned_remove_all(txn.get(), k);
3556
0
            }
3557
0
        }
3558
4.00k
        for (auto& tablet_info : tablets_info) {
3559
4.00k
            std::string k;
3560
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
4.00k
            txn->remove(k);
3562
4.00k
        }
3563
4.00k
        for (auto& tablet_info : tablets_info) {
3564
4.00k
            std::string k;
3565
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
4.00k
            txn->remove(k);
3567
4.00k
        }
3568
2
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
2
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
0
                         << ", err=" << err;
3575
0
            return -1;
3576
0
        }
3577
2
        return ret;
3578
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3458
50
    auto loop_done = [&, this]() -> int {
3459
50
        int ret = 0;
3460
50
        bool finished = true;
3461
50
        bool has_empty_key = false;
3462
50
        DORIS_CLOUD_DEFER {
3463
50
            init_rs_keys.clear();
3464
50
            has_failure = false;
3465
50
        };
3466
50
        auto tablets_info = sync_executor.when_all(&finished);
3467
50
        if (!finished) {
3468
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3469
1
            return -1;
3470
1
        }
3471
3472
49
        size_t size_before_erase = tablets_info.size();
3473
49
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3474
49
        if (tablets_info.empty()) {
3475
0
            return size_before_erase == 0 ? 0 : -1;
3476
49
        } else if (size_before_erase != tablets_info.size()) {
3477
1
            has_empty_key = true;
3478
1
        }
3479
3480
49
        ret = has_empty_key ? -1 : 0;
3481
        // sort the vector using key's order
3482
49
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3483
49
            return prev.tablet_meta_key < last.tablet_meta_key;
3484
49
        });
3485
49
        std::unique_ptr<Transaction> txn;
3486
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3487
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3488
0
            return -1;
3489
0
        }
3490
49
        std::string tablet_key_end;
3491
49
        if (!tablets_info.empty()) {
3492
49
            if (!has_empty_key && !has_failure) {
3493
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3494
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3495
47
            } else {
3496
8
                for (auto& tablet_info : tablets_info) {
3497
8
                    txn->remove(tablet_info.tablet_meta_key);
3498
8
                }
3499
2
            }
3500
49
        }
3501
49
        if (should_recycle_versioned_keys()) {
3502
            // Remove tablet indexes in the same transaction as tablet metadata.
3503
7
            std::vector<std::string> versioned_idx_keys;
3504
7
            versioned_idx_keys.reserve(tablets_info.size());
3505
8
            for (const auto& tablet_info : tablets_info) {
3506
8
                versioned_idx_keys.push_back(
3507
8
                        versioned::tablet_index_key({instance_id_, tablet_info.tablet_id}));
3508
8
            }
3509
7
            std::vector<std::optional<std::string>> tablet_index_vals;
3510
7
            TxnErrorCode err = txn->batch_get(&tablet_index_vals, versioned_idx_keys);
3511
7
            if (err != TxnErrorCode::TXN_OK) {
3512
0
                LOG_WARNING("failed to batch get tablet index kv")
3513
0
                        .tag("instance_id", instance_id_)
3514
0
                        .tag("num_tablets", tablets_info.size())
3515
0
                        .tag("err", err);
3516
0
                return -1;
3517
0
            }
3518
7
            DCHECK_EQ(tablet_index_vals.size(), versioned_idx_keys.size());
3519
15
            for (size_t i = 0; i < tablets_info.size(); ++i) {
3520
8
                if (!tablet_index_vals[i].has_value()) {
3521
0
                    continue;
3522
0
                }
3523
8
                const auto& tablet_info = tablets_info[i];
3524
8
                TabletIndexPB tablet_index_pb;
3525
8
                if (!tablet_index_pb.ParseFromString(tablet_index_vals[i].value())) {
3526
0
                    LOG_WARNING("failed to parse tablet index pb")
3527
0
                            .tag("instance_id", instance_id_)
3528
0
                            .tag("tablet_id", tablet_info.tablet_id);
3529
0
                    return -1;
3530
0
                }
3531
8
                std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
3532
8
                        {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
3533
8
                         tablet_index_pb.index_id(), tablet_index_pb.partition_id(),
3534
8
                         tablet_info.tablet_id});
3535
8
                txn->remove(versioned_inverted_idx_key);
3536
8
                txn->remove(versioned_idx_keys[i]);
3537
8
            }
3538
8
            for (auto& tablet_info : tablets_info) {
3539
                // Remove all versions of tablet compact stats for recycled tablet
3540
8
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3541
8
                LOG_INFO("remove versioned tablet compact stats key")
3542
8
                        .tag("compact_stats_key", hex(k));
3543
8
                versioned_remove_all(txn.get(), k);
3544
8
            }
3545
8
            for (auto& tablet_info : tablets_info) {
3546
                // Remove all versions of tablet load stats for recycled tablet
3547
8
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3548
8
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3549
8
                versioned_remove_all(txn.get(), k);
3550
8
            }
3551
8
            for (auto& tablet_info : tablets_info) {
3552
                // Remove all versions of meta tablet for recycled tablet
3553
8
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3554
8
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3555
8
                versioned_remove_all(txn.get(), k);
3556
8
            }
3557
7
        }
3558
250
        for (auto& tablet_info : tablets_info) {
3559
250
            std::string k;
3560
250
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3561
250
            txn->remove(k);
3562
250
        }
3563
250
        for (auto& tablet_info : tablets_info) {
3564
250
            std::string k;
3565
250
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3566
250
            txn->remove(k);
3567
250
        }
3568
49
        for (auto& k : init_rs_keys) {
3569
0
            txn->remove(k);
3570
0
        }
3571
49
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablets.before_commit", txn.get());
3572
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3573
1
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3574
1
                         << ", err=" << err;
3575
1
            return -1;
3576
1
        }
3577
48
        return ret;
3578
49
    };
3579
3580
54
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3581
54
                               std::move(loop_done));
3582
54
    if (ret != 0) {
3583
6
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3584
6
        return ret;
3585
6
    }
3586
3587
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3588
48
    std::unique_ptr<Transaction> txn;
3589
48
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3590
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3591
0
        return -1;
3592
0
    }
3593
48
    txn->remove(stats_key_begin, stats_key_end);
3594
48
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3595
48
                 << " end=" << hex(stats_key_end);
3596
48
    txn->remove(job_key_begin, job_key_end);
3597
48
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3598
48
    std::string schema_key_begin, schema_key_end;
3599
48
    std::string schema_dict_key;
3600
48
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3601
48
    if (partition_id <= 0) {
3602
        // Delete schema kv of this index
3603
16
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3604
16
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3605
16
        txn->remove(schema_key_begin, schema_key_end);
3606
16
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3607
16
                     << " end=" << hex(schema_key_end);
3608
16
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3609
16
        txn->remove(schema_dict_key);
3610
16
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3611
16
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3612
16
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3613
16
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3614
16
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3615
16
                     << " end=" << hex(versioned_schema_key_end);
3616
16
    }
3617
3618
48
    TxnErrorCode err = txn->commit();
3619
48
    if (err != TxnErrorCode::TXN_OK) {
3620
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3621
0
                     << " err=" << err;
3622
0
        return -1;
3623
0
    }
3624
3625
48
    return ret;
3626
48
}
3627
3628
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3629
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3630
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3631
5.61k
    if (num_segments <= 0) return 0;
3632
3633
5.61k
    std::vector<std::string> file_paths;
3634
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3635
0
        return -1;
3636
0
    }
3637
3638
    // Process inverted indexes
3639
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3640
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3641
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3642
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3643
5.61k
    bool delete_rowset_data_by_prefix = false;
3644
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3645
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3646
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3647
0
        delete_rowset_data_by_prefix = true;
3648
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3649
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3650
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3651
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3652
10.0k
            }
3653
10.0k
        }
3654
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3655
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3656
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3657
2.00k
        }
3658
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3659
        // schema version and index id are not found, delete rowset data by prefix directly.
3660
0
        delete_rowset_data_by_prefix = true;
3661
809
    } else {
3662
        // otherwise, try to get schema kv
3663
809
        InvertedIndexInfo index_info;
3664
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3665
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3666
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3667
809
                                 &inverted_index_get_ret);
3668
809
        if (inverted_index_get_ret == 0) {
3669
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3670
809
                index_format = index_info.first;
3671
809
            }
3672
809
            index_ids = index_info.second;
3673
809
        } else if (inverted_index_get_ret == 1) {
3674
            // 1. Schema kv not found means tablet has been recycled
3675
            // Maybe some tablet recycle failed by some bugs
3676
            // We need to delete again to double check
3677
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3678
            // because we are uncertain about the inverted index information.
3679
            // If there are inverted indexes, some data might not be deleted,
3680
            // but this is acceptable as we have made our best effort to delete the data.
3681
0
            LOG_INFO(
3682
0
                    "delete rowset data schema kv not found, need to delete again to double "
3683
0
                    "check")
3684
0
                    .tag("instance_id", instance_id_)
3685
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3686
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3687
            // Currently index_ids is guaranteed to be empty,
3688
            // but we clear it again here as a safeguard against future code changes
3689
            // that might cause index_ids to no longer be empty
3690
0
            index_format = InvertedIndexStorageFormatPB::V2;
3691
0
            index_ids.clear();
3692
0
        } else {
3693
            // failed to get schema kv, delete rowset data by prefix directly.
3694
0
            delete_rowset_data_by_prefix = true;
3695
0
        }
3696
809
    }
3697
3698
5.61k
    if (delete_rowset_data_by_prefix) {
3699
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3700
0
                                  rs_meta_pb.rowset_id_v2());
3701
0
    }
3702
3703
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3704
5.61k
    if (it == accessor_map_.end()) {
3705
1.60k
        LOG_WARNING("instance has no such resource id")
3706
1.60k
                .tag("instance_id", instance_id_)
3707
1.60k
                .tag("resource_id", rs_meta_pb.resource_id());
3708
1.60k
        return -1;
3709
1.60k
    }
3710
4.01k
    auto& accessor = it->second;
3711
3712
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3713
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3714
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3715
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, i),
3716
20.0k
                                         &file_paths);
3717
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3718
40.0k
            for (const auto& index_id : index_ids) {
3719
40.0k
                add_file_to_delete_if_not_packed(
3720
40.0k
                        rs_meta_pb,
3721
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
3722
40.0k
                                               index_id.second),
3723
40.0k
                        &file_paths);
3724
40.0k
            }
3725
20.0k
        } else if (!index_ids.empty()) {
3726
0
            add_file_to_delete_if_not_packed(
3727
0
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
3728
0
        }
3729
20.0k
    }
3730
3731
    // Process delete bitmap - check where it's stored.
3732
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3733
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3734
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3735
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3736
0
                .tag("instance_id", instance_id_)
3737
0
                .tag("tablet_id", tablet_id)
3738
0
                .tag("rowset_id", rowset_id);
3739
0
        return -1;
3740
0
    }
3741
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3742
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3743
2.00k
    }
3744
    // TODO(AlexYue): seems could do do batch
3745
4.01k
    return accessor->delete_files(file_paths);
3746
4.01k
}
3747
3748
102k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3749
102k
    LOG_INFO("begin process_packed_file_location_index")
3750
102k
            .tag("instance_id", instance_id_)
3751
102k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3752
102k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3753
102k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3754
102k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3755
102k
    if (index_map.empty()) {
3756
87.5k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3757
87.5k
                .tag("instance_id", instance_id_)
3758
87.5k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3759
87.5k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3760
87.5k
        return 0;
3761
87.5k
    }
3762
3763
15.0k
    struct PackedSmallFileInfo {
3764
15.0k
        std::string small_file_path;
3765
15.0k
    };
3766
15.0k
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3767
15.0k
    packed_file_updates.reserve(index_map.size());
3768
29.9k
    for (const auto& [small_path, index_pb] : index_map) {
3769
30.0k
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3770
0
            continue;
3771
0
        }
3772
29.9k
        packed_file_updates[index_pb.packed_file_path()].push_back(
3773
29.9k
                PackedSmallFileInfo {small_path});
3774
29.9k
    }
3775
15.0k
    if (packed_file_updates.empty()) {
3776
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3777
0
                .tag("instance_id", instance_id_)
3778
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3779
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3780
0
                .tag("index_map_size", index_map.size());
3781
0
        return 0;
3782
0
    }
3783
3784
15.0k
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3785
15.0k
    int ret = 0;
3786
15.0k
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3787
15.0k
        if (small_files.empty()) {
3788
0
            continue;
3789
0
        }
3790
3791
15.0k
        bool success = false;
3792
15.0k
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3793
14.9k
            std::unique_ptr<Transaction> txn;
3794
14.9k
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3795
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3796
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3797
0
                        .tag("instance_id", instance_id_)
3798
0
                        .tag("packed_file_path", packed_file_path)
3799
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3800
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3801
0
                        .tag("err", err);
3802
0
                ret = -1;
3803
0
                break;
3804
0
            }
3805
3806
14.9k
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3807
14.9k
            std::string packed_val;
3808
14.9k
            err = txn->get(packed_key, &packed_val);
3809
14.9k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3810
0
                LOG_WARNING("packed file info not found when recycling rowset")
3811
0
                        .tag("instance_id", instance_id_)
3812
0
                        .tag("packed_file_path", packed_file_path)
3813
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3814
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3815
0
                        .tag("key", hex(packed_key))
3816
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3817
                // Skip this packed file entry and continue with others
3818
0
                success = true;
3819
0
                break;
3820
0
            }
3821
14.9k
            if (err != TxnErrorCode::TXN_OK) {
3822
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
3823
0
                        .tag("instance_id", instance_id_)
3824
0
                        .tag("packed_file_path", packed_file_path)
3825
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3826
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3827
0
                        .tag("err", err);
3828
0
                ret = -1;
3829
0
                break;
3830
0
            }
3831
3832
14.9k
            cloud::PackedFileInfoPB packed_info;
3833
14.9k
            if (!packed_info.ParseFromString(packed_val)) {
3834
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
3835
0
                        .tag("instance_id", instance_id_)
3836
0
                        .tag("packed_file_path", packed_file_path)
3837
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3838
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3839
0
                ret = -1;
3840
0
                break;
3841
0
            }
3842
3843
14.9k
            LOG_INFO("packed file update check")
3844
14.9k
                    .tag("instance_id", instance_id_)
3845
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3846
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3847
14.9k
                    .tag("merged_file_path", packed_file_path)
3848
14.9k
                    .tag("requested_small_files", small_files.size())
3849
14.9k
                    .tag("merge_entries", packed_info.slices_size());
3850
3851
14.9k
            auto* small_file_entries = packed_info.mutable_slices();
3852
14.9k
            int64_t changed_files = 0;
3853
14.9k
            int64_t missing_entries = 0;
3854
14.9k
            int64_t already_deleted = 0;
3855
29.9k
            for (const auto& small_file_info : small_files) {
3856
29.9k
                bool found = false;
3857
74.8k
                for (auto& small_file_entry : *small_file_entries) {
3858
74.8k
                    if (small_file_entry.path() == small_file_info.small_file_path) {
3859
30.0k
                        if (!small_file_entry.deleted()) {
3860
29.9k
                            small_file_entry.set_deleted(true);
3861
29.9k
                            if (!small_file_entry.corrected()) {
3862
29.9k
                                small_file_entry.set_corrected(true);
3863
29.9k
                            }
3864
29.9k
                            ++changed_files;
3865
29.9k
                        } else {
3866
12
                            ++already_deleted;
3867
12
                        }
3868
30.0k
                        found = true;
3869
30.0k
                        break;
3870
30.0k
                    }
3871
74.8k
                }
3872
29.9k
                if (!found) {
3873
0
                    ++missing_entries;
3874
0
                    LOG_WARNING("packed file info missing small file entry")
3875
0
                            .tag("instance_id", instance_id_)
3876
0
                            .tag("packed_file_path", packed_file_path)
3877
0
                            .tag("small_file_path", small_file_info.small_file_path)
3878
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3879
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
3880
0
                }
3881
29.9k
            }
3882
3883
14.9k
            if (changed_files == 0) {
3884
0
                LOG_INFO("skip merge file update: no merge entries changed")
3885
0
                        .tag("instance_id", instance_id_)
3886
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3887
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3888
0
                        .tag("merged_file_path", packed_file_path)
3889
0
                        .tag("missing_entries", missing_entries)
3890
0
                        .tag("already_deleted", already_deleted)
3891
0
                        .tag("requested_small_files", small_files.size())
3892
0
                        .tag("merge_entries", packed_info.slices_size());
3893
0
                success = true;
3894
0
                break;
3895
0
            }
3896
3897
            // Calculate remaining files
3898
14.9k
            int64_t left_file_count = 0;
3899
14.9k
            int64_t left_file_bytes = 0;
3900
60.0k
            for (const auto& small_file_entry : packed_info.slices()) {
3901
60.0k
                if (!small_file_entry.deleted()) {
3902
15.0k
                    ++left_file_count;
3903
15.0k
                    left_file_bytes += small_file_entry.size();
3904
15.0k
                }
3905
60.0k
            }
3906
14.9k
            packed_info.set_remaining_slice_bytes(left_file_bytes);
3907
14.9k
            packed_info.set_ref_cnt(left_file_count);
3908
14.9k
            LOG_INFO("updated packed file reference info")
3909
14.9k
                    .tag("instance_id", instance_id_)
3910
14.9k
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3911
14.9k
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3912
14.9k
                    .tag("packed_file_path", packed_file_path)
3913
14.9k
                    .tag("ref_cnt", left_file_count)
3914
14.9k
                    .tag("left_file_bytes", left_file_bytes);
3915
3916
14.9k
            if (left_file_count == 0) {
3917
7.50k
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
3918
7.50k
            }
3919
3920
14.9k
            std::string updated_val;
3921
14.9k
            if (!packed_info.SerializeToString(&updated_val)) {
3922
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
3923
0
                        .tag("instance_id", instance_id_)
3924
0
                        .tag("packed_file_path", packed_file_path)
3925
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3926
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
3927
0
                ret = -1;
3928
0
                break;
3929
0
            }
3930
3931
14.9k
            txn->put(packed_key, updated_val);
3932
14.9k
            err = txn->commit();
3933
15.0k
            if (err == TxnErrorCode::TXN_OK) {
3934
15.0k
                success = true;
3935
15.0k
                if (left_file_count == 0) {
3936
7.50k
                    LOG_INFO("packed file ready to delete, deleting immediately")
3937
7.50k
                            .tag("instance_id", instance_id_)
3938
7.50k
                            .tag("packed_file_path", packed_file_path);
3939
7.50k
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
3940
0
                        ret = -1;
3941
0
                    }
3942
7.50k
                }
3943
15.0k
                break;
3944
15.0k
            }
3945
18.4E
            if (err == TxnErrorCode::TXN_CONFLICT) {
3946
0
                if (attempt >= max_retry_times) {
3947
0
                    LOG_WARNING("packed file info update conflict after max retry")
3948
0
                            .tag("instance_id", instance_id_)
3949
0
                            .tag("packed_file_path", packed_file_path)
3950
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3951
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
3952
0
                            .tag("changed_files", changed_files)
3953
0
                            .tag("attempt", attempt);
3954
0
                    ret = -1;
3955
0
                    break;
3956
0
                }
3957
0
                LOG_WARNING("packed file info update conflict, retrying")
3958
0
                        .tag("instance_id", instance_id_)
3959
0
                        .tag("packed_file_path", packed_file_path)
3960
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3961
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3962
0
                        .tag("changed_files", changed_files)
3963
0
                        .tag("attempt", attempt);
3964
0
                sleep_for_packed_file_retry();
3965
0
                continue;
3966
0
            }
3967
3968
18.4E
            LOG_WARNING("failed to commit packed file info update")
3969
18.4E
                    .tag("instance_id", instance_id_)
3970
18.4E
                    .tag("packed_file_path", packed_file_path)
3971
18.4E
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3972
18.4E
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3973
18.4E
                    .tag("err", err)
3974
18.4E
                    .tag("changed_files", changed_files);
3975
18.4E
            ret = -1;
3976
18.4E
            break;
3977
18.4E
        }
3978
3979
15.0k
        if (!success) {
3980
0
            ret = -1;
3981
0
        }
3982
15.0k
    }
3983
3984
15.0k
    return ret;
3985
15.0k
}
3986
3987
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
3988
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
3989
100k
        std::vector<std::string>* keys) {
3990
100k
    if (out_storage_type) {
3991
98.3k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3992
98.3k
    }
3993
3994
    // Get delete bitmap storage info from FDB
3995
100k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
3996
100k
    std::unique_ptr<Transaction> txn;
3997
100k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
3998
100k
    if (err != TxnErrorCode::TXN_OK) {
3999
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4000
0
                .tag("instance_id", instance_id_)
4001
0
                .tag("tablet_id", tablet_id)
4002
0
                .tag("rowset_id", rowset_id)
4003
0
                .tag("err", err);
4004
0
        return -1;
4005
0
    }
4006
4007
100k
    ValueBuf dbm_val;
4008
100k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4009
100k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4010
        // No delete bitmap for this rowset, nothing to do
4011
36.1k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4012
36.1k
                .tag("instance_id", instance_id_)
4013
36.1k
                .tag("tablet_id", tablet_id)
4014
36.1k
                .tag("rowset_id", rowset_id);
4015
36.1k
        return 0;
4016
36.1k
    }
4017
64.7k
    if (err != TxnErrorCode::TXN_OK) {
4018
0
        LOG_WARNING("failed to get delete bitmap storage")
4019
0
                .tag("instance_id", instance_id_)
4020
0
                .tag("tablet_id", tablet_id)
4021
0
                .tag("rowset_id", rowset_id)
4022
0
                .tag("err", err);
4023
0
        return -1;
4024
0
    }
4025
4026
64.7k
    if (keys) {
4027
11.5k
        for (auto& key : dbm_val.keys()) {
4028
11.5k
            keys->push_back(std::move(key));
4029
11.5k
        }
4030
11.5k
    }
4031
4032
64.7k
    DeleteBitmapStoragePB storage;
4033
64.7k
    if (!dbm_val.to_pb(&storage)) {
4034
0
        LOG_WARNING("failed to parse delete bitmap storage")
4035
0
                .tag("instance_id", instance_id_)
4036
0
                .tag("tablet_id", tablet_id)
4037
0
                .tag("rowset_id", rowset_id);
4038
0
        return -1;
4039
0
    }
4040
4041
64.7k
    if (storage.store_in_fdb()) {
4042
1
        if (out_storage_type) {
4043
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4044
1
        }
4045
1
        return 0;
4046
1
    }
4047
4048
    // Check if delete bitmap is stored in standalone file.
4049
64.7k
    if (!storage.has_packed_slice_location() ||
4050
64.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4051
64.8k
        if (out_storage_type) {
4052
63.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4053
63.5k
        }
4054
64.8k
        return 0;
4055
64.8k
    }
4056
4057
18.4E
    if (out_storage_type) {
4058
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4059
0
    }
4060
4061
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4062
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4063
4064
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4065
18.4E
            .tag("instance_id", instance_id_)
4066
18.4E
            .tag("tablet_id", tablet_id)
4067
18.4E
            .tag("rowset_id", rowset_id)
4068
18.4E
            .tag("packed_file_path", packed_file_path);
4069
4070
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4071
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4072
1
        std::unique_ptr<Transaction> update_txn;
4073
1
        err = txn_kv_->create_txn(&update_txn);
4074
1
        if (err != TxnErrorCode::TXN_OK) {
4075
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4076
0
                    .tag("instance_id", instance_id_)
4077
0
                    .tag("tablet_id", tablet_id)
4078
0
                    .tag("rowset_id", rowset_id)
4079
0
                    .tag("err", err);
4080
0
            return -1;
4081
0
        }
4082
4083
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4084
1
        std::string packed_val;
4085
1
        err = update_txn->get(packed_key, &packed_val);
4086
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4087
0
            LOG_WARNING("packed file info not found for delete bitmap")
4088
0
                    .tag("instance_id", instance_id_)
4089
0
                    .tag("tablet_id", tablet_id)
4090
0
                    .tag("rowset_id", rowset_id)
4091
0
                    .tag("packed_file_path", packed_file_path);
4092
0
            return 0;
4093
0
        }
4094
1
        if (err != TxnErrorCode::TXN_OK) {
4095
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4096
0
                    .tag("instance_id", instance_id_)
4097
0
                    .tag("tablet_id", tablet_id)
4098
0
                    .tag("rowset_id", rowset_id)
4099
0
                    .tag("packed_file_path", packed_file_path)
4100
0
                    .tag("err", err);
4101
0
            return -1;
4102
0
        }
4103
4104
1
        cloud::PackedFileInfoPB packed_info;
4105
1
        if (!packed_info.ParseFromString(packed_val)) {
4106
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4107
0
                    .tag("instance_id", instance_id_)
4108
0
                    .tag("tablet_id", tablet_id)
4109
0
                    .tag("rowset_id", rowset_id)
4110
0
                    .tag("packed_file_path", packed_file_path);
4111
0
            return -1;
4112
0
        }
4113
4114
        // Find and mark the small file entry as deleted
4115
        // Use tablet_id and rowset_id to match entry instead of path,
4116
        // because path format may vary with path_version (with or without shard prefix)
4117
1
        auto* entries = packed_info.mutable_slices();
4118
1
        bool found = false;
4119
1
        bool already_deleted = false;
4120
1
        for (auto& entry : *entries) {
4121
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4122
1
                if (!entry.deleted()) {
4123
1
                    entry.set_deleted(true);
4124
1
                    if (!entry.corrected()) {
4125
1
                        entry.set_corrected(true);
4126
1
                    }
4127
1
                } else {
4128
0
                    already_deleted = true;
4129
0
                }
4130
1
                found = true;
4131
1
                break;
4132
1
            }
4133
1
        }
4134
4135
1
        if (!found) {
4136
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4137
0
                    .tag("instance_id", instance_id_)
4138
0
                    .tag("tablet_id", tablet_id)
4139
0
                    .tag("rowset_id", rowset_id)
4140
0
                    .tag("packed_file_path", packed_file_path);
4141
0
            return 0;
4142
0
        }
4143
4144
1
        if (already_deleted) {
4145
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4146
0
                    .tag("instance_id", instance_id_)
4147
0
                    .tag("tablet_id", tablet_id)
4148
0
                    .tag("rowset_id", rowset_id)
4149
0
                    .tag("packed_file_path", packed_file_path);
4150
0
            return 0;
4151
0
        }
4152
4153
        // Calculate remaining files
4154
1
        int64_t left_file_count = 0;
4155
1
        int64_t left_file_bytes = 0;
4156
1
        for (const auto& entry : packed_info.slices()) {
4157
1
            if (!entry.deleted()) {
4158
0
                ++left_file_count;
4159
0
                left_file_bytes += entry.size();
4160
0
            }
4161
1
        }
4162
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4163
1
        packed_info.set_ref_cnt(left_file_count);
4164
4165
1
        if (left_file_count == 0) {
4166
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4167
1
        }
4168
4169
1
        std::string updated_val;
4170
1
        if (!packed_info.SerializeToString(&updated_val)) {
4171
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4172
0
                    .tag("instance_id", instance_id_)
4173
0
                    .tag("tablet_id", tablet_id)
4174
0
                    .tag("rowset_id", rowset_id)
4175
0
                    .tag("packed_file_path", packed_file_path);
4176
0
            return -1;
4177
0
        }
4178
4179
1
        update_txn->put(packed_key, updated_val);
4180
1
        err = update_txn->commit();
4181
1
        if (err == TxnErrorCode::TXN_OK) {
4182
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4183
1
                    .tag("instance_id", instance_id_)
4184
1
                    .tag("tablet_id", tablet_id)
4185
1
                    .tag("rowset_id", rowset_id)
4186
1
                    .tag("packed_file_path", packed_file_path)
4187
1
                    .tag("left_file_count", left_file_count);
4188
1
            if (left_file_count == 0) {
4189
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4190
0
                    return -1;
4191
0
                }
4192
1
            }
4193
1
            return 0;
4194
1
        }
4195
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4196
0
            if (attempt >= max_retry_times) {
4197
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4198
0
                        .tag("instance_id", instance_id_)
4199
0
                        .tag("tablet_id", tablet_id)
4200
0
                        .tag("rowset_id", rowset_id)
4201
0
                        .tag("packed_file_path", packed_file_path)
4202
0
                        .tag("attempt", attempt);
4203
0
                return -1;
4204
0
            }
4205
0
            sleep_for_packed_file_retry();
4206
0
            continue;
4207
0
        }
4208
4209
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4210
0
                .tag("instance_id", instance_id_)
4211
0
                .tag("tablet_id", tablet_id)
4212
0
                .tag("rowset_id", rowset_id)
4213
0
                .tag("packed_file_path", packed_file_path)
4214
0
                .tag("err", err);
4215
0
        return -1;
4216
0
    }
4217
4218
18.4E
    return -1;
4219
18.4E
}
4220
4221
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4222
                                                const std::string& packed_key,
4223
7.50k
                                                const cloud::PackedFileInfoPB& packed_info) {
4224
7.50k
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4225
0
        LOG_WARNING("packed file missing resource id when recycling")
4226
0
                .tag("instance_id", instance_id_)
4227
0
                .tag("packed_file_path", packed_file_path);
4228
0
        return -1;
4229
0
    }
4230
4231
7.50k
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4232
7.50k
    if (!accessor) {
4233
0
        LOG_WARNING("no accessor available to delete packed file")
4234
0
                .tag("instance_id", instance_id_)
4235
0
                .tag("packed_file_path", packed_file_path)
4236
0
                .tag("resource_id", packed_info.resource_id());
4237
0
        return -1;
4238
0
    }
4239
4240
7.50k
    int del_ret = accessor->delete_file(packed_file_path);
4241
7.50k
    if (del_ret != 0 && del_ret != 1) {
4242
0
        LOG_WARNING("failed to delete packed file")
4243
0
                .tag("instance_id", instance_id_)
4244
0
                .tag("packed_file_path", packed_file_path)
4245
0
                .tag("resource_id", resource_id)
4246
0
                .tag("ret", del_ret);
4247
0
        return -1;
4248
0
    }
4249
7.50k
    if (del_ret == 1) {
4250
0
        LOG_INFO("packed file already removed")
4251
0
                .tag("instance_id", instance_id_)
4252
0
                .tag("packed_file_path", packed_file_path)
4253
0
                .tag("resource_id", resource_id);
4254
7.50k
    } else {
4255
7.50k
        LOG_INFO("deleted packed file")
4256
7.50k
                .tag("instance_id", instance_id_)
4257
7.50k
                .tag("packed_file_path", packed_file_path)
4258
7.50k
                .tag("resource_id", resource_id);
4259
7.50k
    }
4260
4261
7.50k
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4262
7.50k
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4263
7.50k
        std::unique_ptr<Transaction> del_txn;
4264
7.50k
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4265
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4266
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4267
0
                    .tag("instance_id", instance_id_)
4268
0
                    .tag("packed_file_path", packed_file_path)
4269
0
                    .tag("attempt", attempt)
4270
0
                    .tag("err", err);
4271
0
            return -1;
4272
0
        }
4273
4274
7.50k
        std::string latest_val;
4275
7.50k
        err = del_txn->get(packed_key, &latest_val);
4276
7.50k
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4277
0
            return 0;
4278
0
        }
4279
7.50k
        if (err != TxnErrorCode::TXN_OK) {
4280
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4281
0
                    .tag("instance_id", instance_id_)
4282
0
                    .tag("packed_file_path", packed_file_path)
4283
0
                    .tag("attempt", attempt)
4284
0
                    .tag("err", err);
4285
0
            return -1;
4286
0
        }
4287
4288
7.50k
        cloud::PackedFileInfoPB latest_info;
4289
7.50k
        if (!latest_info.ParseFromString(latest_val)) {
4290
0
            LOG_WARNING("failed to parse packed file info before removal")
4291
0
                    .tag("instance_id", instance_id_)
4292
0
                    .tag("packed_file_path", packed_file_path)
4293
0
                    .tag("attempt", attempt);
4294
0
            return -1;
4295
0
        }
4296
4297
7.50k
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4298
7.50k
              latest_info.ref_cnt() == 0)) {
4299
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4300
0
                    .tag("instance_id", instance_id_)
4301
0
                    .tag("packed_file_path", packed_file_path)
4302
0
                    .tag("attempt", attempt);
4303
0
            return 0;
4304
0
        }
4305
4306
7.50k
        del_txn->remove(packed_key);
4307
7.50k
        err = del_txn->commit();
4308
7.50k
        if (err == TxnErrorCode::TXN_OK) {
4309
7.49k
            LOG_INFO("removed packed file metadata")
4310
7.49k
                    .tag("instance_id", instance_id_)
4311
7.49k
                    .tag("packed_file_path", packed_file_path);
4312
7.49k
            return 0;
4313
7.49k
        }
4314
5
        if (err == TxnErrorCode::TXN_CONFLICT) {
4315
0
            if (attempt >= max_retry_times) {
4316
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4317
0
                        .tag("instance_id", instance_id_)
4318
0
                        .tag("packed_file_path", packed_file_path)
4319
0
                        .tag("attempt", attempt);
4320
0
                return -1;
4321
0
            }
4322
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4323
0
                    .tag("instance_id", instance_id_)
4324
0
                    .tag("packed_file_path", packed_file_path)
4325
0
                    .tag("attempt", attempt);
4326
0
            sleep_for_packed_file_retry();
4327
0
            continue;
4328
0
        }
4329
5
        LOG_WARNING("failed to remove packed file kv")
4330
5
                .tag("instance_id", instance_id_)
4331
5
                .tag("packed_file_path", packed_file_path)
4332
5
                .tag("attempt", attempt)
4333
5
                .tag("err", err);
4334
5
        return -1;
4335
5
    }
4336
5
    return -1;
4337
7.50k
}
4338
4339
int InstanceRecycler::delete_rowset_data(
4340
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4341
        RecyclerMetricsContext& metrics_context,
4342
439
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4343
439
    int ret = 0;
4344
    // resource_id -> file_paths
4345
439
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4346
    // (resource_id, tablet_id, rowset_id)
4347
439
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4348
439
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4349
4350
106k
    for (const auto& [_, rs] : rowsets) {
4351
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4352
        // due to aborted schema change.
4353
106k
        if (is_formal_rowset) {
4354
53.1k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4355
                // Tablet has been recycled and this rowset has no packed slices, so file data
4356
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4357
                // slice info must still run to decrement packed file ref counts.
4358
0
                continue;
4359
0
            }
4360
53.1k
        }
4361
4362
106k
        int64_t num_segments = rs.num_segments();
4363
        // Check num_segments before accessor lookup, because empty rowsets
4364
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4365
        // set. Skipping them early avoids a spurious "no such resource id" error
4366
        // that marks the entire batch as failed and prevents txn_remove from
4367
        // cleaning up recycle KV keys.
4368
106k
        if (num_segments <= 0) {
4369
10.0k
            metrics_context.total_recycled_num++;
4370
10.0k
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4371
10.0k
            continue;
4372
10.0k
        }
4373
4374
96.4k
        auto it = accessor_map_.find(rs.resource_id());
4375
        // possible if the accessor is not initilized correctly
4376
96.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4377
2.00k
            LOG_WARNING("instance has no such resource id")
4378
2.00k
                    .tag("instance_id", instance_id_)
4379
2.00k
                    .tag("resource_id", rs.resource_id());
4380
2.00k
            ret = -1;
4381
2.00k
            continue;
4382
2.00k
        }
4383
4384
94.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4385
94.4k
        const auto& rowset_id = rs.rowset_id_v2();
4386
94.4k
        int64_t tablet_id = rs.tablet_id();
4387
94.4k
        LOG_INFO("recycle rowset merge index size")
4388
94.4k
                .tag("instance_id", instance_id_)
4389
94.4k
                .tag("tablet_id", tablet_id)
4390
94.4k
                .tag("rowset_id", rowset_id)
4391
94.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4392
94.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4393
0
            ret = -1;
4394
0
            continue;
4395
0
        }
4396
4397
94.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4398
94.4k
        std::vector<std::string> rowset_dbm_keys;
4399
94.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4400
94.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4401
94.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4402
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4403
0
                    .tag("instance_id", instance_id_)
4404
0
                    .tag("tablet_id", tablet_id)
4405
0
                    .tag("rowset_id", rowset_id);
4406
0
            ret = -1;
4407
0
            continue;
4408
0
        }
4409
94.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4410
11.5k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4411
11.5k
        }
4412
94.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4413
61.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4414
61.5k
        }
4415
4416
        // Process inverted indexes
4417
94.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4418
        // default format as v1.
4419
94.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4420
94.4k
                                                            ? rs.inverted_index_storage_format()
4421
94.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4422
94.4k
        int inverted_index_get_ret = 0;
4423
94.4k
        if (rs.has_tablet_schema()) {
4424
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4425
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4426
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4427
53.5k
                }
4428
53.5k
            }
4429
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4430
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4431
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4432
26.5k
            }
4433
67.5k
        } else {
4434
67.5k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4435
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4436
0
                                "instance_id="
4437
0
                             << instance_id_ << " tablet_id=" << tablet_id
4438
0
                             << " rowset_id=" << rowset_id;
4439
0
                ret = -1;
4440
0
                continue;
4441
0
            }
4442
67.5k
            InvertedIndexInfo index_info;
4443
67.5k
            inverted_index_get_ret =
4444
67.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4445
67.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4446
67.5k
                                     &inverted_index_get_ret);
4447
67.5k
            if (inverted_index_get_ret == 0) {
4448
62.0k
                if (!rs.has_inverted_index_storage_format()) {
4449
62.0k
                    index_format = index_info.first;
4450
62.0k
                }
4451
62.0k
                index_ids = index_info.second;
4452
62.0k
            } else if (inverted_index_get_ret == 1) {
4453
                // 1. Schema kv not found means tablet has been recycled
4454
                // Maybe some tablet recycle failed by some bugs
4455
                // We need to delete again to double check
4456
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4457
                // because we are uncertain about the inverted index information.
4458
                // If there are inverted indexes, some data might not be deleted,
4459
                // but this is acceptable as we have made our best effort to delete the data.
4460
5.50k
                LOG_INFO(
4461
5.50k
                        "delete rowset data schema kv not found, need to delete again to "
4462
5.50k
                        "double "
4463
5.50k
                        "check")
4464
5.50k
                        .tag("instance_id", instance_id_)
4465
5.50k
                        .tag("tablet_id", tablet_id)
4466
5.50k
                        .tag("rowset", rs.ShortDebugString());
4467
                // Currently index_ids is guaranteed to be empty,
4468
                // but we clear it again here as a safeguard against future code changes
4469
                // that might cause index_ids to no longer be empty
4470
5.50k
                index_format = InvertedIndexStorageFormatPB::V2;
4471
5.50k
                index_ids.clear();
4472
18.4E
            } else {
4473
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4474
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4475
18.4E
                ret = -1;
4476
18.4E
                continue;
4477
18.4E
            }
4478
67.5k
        }
4479
94.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE && !is_formal_rowset) {
4480
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4481
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4482
6
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4483
6
            continue;
4484
6
        }
4485
404k
        for (int64_t i = 0; i < num_segments; ++i) {
4486
310k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, i),
4487
310k
                                             &file_paths);
4488
310k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4489
572k
                for (const auto& index_id : index_ids) {
4490
572k
                    add_file_to_delete_if_not_packed(
4491
572k
                            rs,
4492
572k
                            inverted_index_path_v1(tablet_id, rowset_id, i, index_id.first,
4493
572k
                                                   index_id.second),
4494
572k
                            &file_paths);
4495
572k
                }
4496
302k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4497
                // try to recycle inverted index v2 when get_ret == 1
4498
                // we treat schema not found as if it has a v2 format inverted index
4499
                // to reduce chance of data leakage
4500
7.50k
                if (inverted_index_get_ret == 1) {
4501
7.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4502
7.50k
                            .tag("instance_id", instance_id_)
4503
7.50k
                            .tag("inverted index v2 path",
4504
7.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, i));
4505
7.50k
                }
4506
7.50k
                add_file_to_delete_if_not_packed(
4507
7.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, i), &file_paths);
4508
7.50k
            }
4509
310k
        }
4510
94.4k
    }
4511
4512
439
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4513
439
                                                 "delete_rowset_data",
4514
439
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_0clERKi
Line
Count
Source
4514
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
4514
198
                                                 [](const int& ret) { return ret != 0; });
4515
439
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4516
198
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4517
198
            DCHECK(accessor_map_.count(*rid))
4518
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4519
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4520
198
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4521
198
                                     &accessor_map_);
4522
198
            if (!accessor_map_.contains(*rid)) {
4523
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4524
0
                        .tag("resource_id", resource_id)
4525
0
                        .tag("instance_id", instance_id_);
4526
0
                return -1;
4527
0
            }
4528
198
            auto& accessor = accessor_map_[*rid];
4529
198
            int ret = accessor->delete_files(*paths);
4530
198
            if (!ret) {
4531
                // deduplication of different files with the same rowset id
4532
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4533
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4534
198
                std::set<std::string> deleted_rowset_id;
4535
4536
198
                std::for_each(paths->begin(), paths->end(),
4537
198
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4538
922k
                               this](const std::string& path) {
4539
922k
                                  std::vector<std::string> str;
4540
922k
                                  butil::SplitString(path, '/', &str);
4541
922k
                                  std::string rowset_id;
4542
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4543
921k
                                      rowset_id = str.back().substr(0, pos);
4544
921k
                                  } else {
4545
1.40k
                                      if (path.find("packed_file/") != std::string::npos) {
4546
0
                                          return; // packed files do not have rowset_id encoded
4547
0
                                      }
4548
1.40k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4549
1.40k
                                      return;
4550
1.40k
                                  }
4551
921k
                                  auto rs_meta = rowsets.find(rowset_id);
4552
921k
                                  if (rs_meta != rowsets.end() &&
4553
921k
                                      !deleted_rowset_id.contains(rowset_id)) {
4554
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4555
84.4k
                                      metrics_context.total_recycled_data_size +=
4556
84.4k
                                              rs_meta->second.total_disk_size();
4557
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4558
84.4k
                                              rs_meta->second.num_segments();
4559
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4560
84.4k
                                              rs_meta->second.total_disk_size();
4561
84.4k
                                      metrics_context.total_recycled_num++;
4562
84.4k
                                  }
4563
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
4538
7
                               this](const std::string& path) {
4539
7
                                  std::vector<std::string> str;
4540
7
                                  butil::SplitString(path, '/', &str);
4541
7
                                  std::string rowset_id;
4542
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4543
7
                                      rowset_id = str.back().substr(0, pos);
4544
7
                                  } else {
4545
0
                                      if (path.find("packed_file/") != std::string::npos) {
4546
0
                                          return; // packed files do not have rowset_id encoded
4547
0
                                      }
4548
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4549
0
                                      return;
4550
0
                                  }
4551
7
                                  auto rs_meta = rowsets.find(rowset_id);
4552
7
                                  if (rs_meta != rowsets.end() &&
4553
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4554
7
                                      deleted_rowset_id.emplace(rowset_id);
4555
7
                                      metrics_context.total_recycled_data_size +=
4556
7
                                              rs_meta->second.total_disk_size();
4557
7
                                      segment_metrics_context_.total_recycled_num +=
4558
7
                                              rs_meta->second.num_segments();
4559
7
                                      segment_metrics_context_.total_recycled_data_size +=
4560
7
                                              rs_meta->second.total_disk_size();
4561
7
                                      metrics_context.total_recycled_num++;
4562
7
                                  }
4563
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
4538
922k
                               this](const std::string& path) {
4539
922k
                                  std::vector<std::string> str;
4540
922k
                                  butil::SplitString(path, '/', &str);
4541
922k
                                  std::string rowset_id;
4542
922k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4543
921k
                                      rowset_id = str.back().substr(0, pos);
4544
921k
                                  } else {
4545
1.40k
                                      if (path.find("packed_file/") != std::string::npos) {
4546
0
                                          return; // packed files do not have rowset_id encoded
4547
0
                                      }
4548
1.40k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4549
1.40k
                                      return;
4550
1.40k
                                  }
4551
921k
                                  auto rs_meta = rowsets.find(rowset_id);
4552
921k
                                  if (rs_meta != rowsets.end() &&
4553
921k
                                      !deleted_rowset_id.contains(rowset_id)) {
4554
84.4k
                                      deleted_rowset_id.emplace(rowset_id);
4555
84.4k
                                      metrics_context.total_recycled_data_size +=
4556
84.4k
                                              rs_meta->second.total_disk_size();
4557
84.4k
                                      segment_metrics_context_.total_recycled_num +=
4558
84.4k
                                              rs_meta->second.num_segments();
4559
84.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4560
84.4k
                                              rs_meta->second.total_disk_size();
4561
84.4k
                                      metrics_context.total_recycled_num++;
4562
84.4k
                                  }
4563
921k
                              });
4564
198
            }
4565
198
            return ret;
4566
198
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4516
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4517
6
            DCHECK(accessor_map_.count(*rid))
4518
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4519
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4520
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4521
6
                                     &accessor_map_);
4522
6
            if (!accessor_map_.contains(*rid)) {
4523
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4524
0
                        .tag("resource_id", resource_id)
4525
0
                        .tag("instance_id", instance_id_);
4526
0
                return -1;
4527
0
            }
4528
6
            auto& accessor = accessor_map_[*rid];
4529
6
            int ret = accessor->delete_files(*paths);
4530
6
            if (!ret) {
4531
                // deduplication of different files with the same rowset id
4532
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4533
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4534
6
                std::set<std::string> deleted_rowset_id;
4535
4536
6
                std::for_each(paths->begin(), paths->end(),
4537
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4538
6
                               this](const std::string& path) {
4539
6
                                  std::vector<std::string> str;
4540
6
                                  butil::SplitString(path, '/', &str);
4541
6
                                  std::string rowset_id;
4542
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4543
6
                                      rowset_id = str.back().substr(0, pos);
4544
6
                                  } else {
4545
6
                                      if (path.find("packed_file/") != std::string::npos) {
4546
6
                                          return; // packed files do not have rowset_id encoded
4547
6
                                      }
4548
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4549
6
                                      return;
4550
6
                                  }
4551
6
                                  auto rs_meta = rowsets.find(rowset_id);
4552
6
                                  if (rs_meta != rowsets.end() &&
4553
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4554
6
                                      deleted_rowset_id.emplace(rowset_id);
4555
6
                                      metrics_context.total_recycled_data_size +=
4556
6
                                              rs_meta->second.total_disk_size();
4557
6
                                      segment_metrics_context_.total_recycled_num +=
4558
6
                                              rs_meta->second.num_segments();
4559
6
                                      segment_metrics_context_.total_recycled_data_size +=
4560
6
                                              rs_meta->second.total_disk_size();
4561
6
                                      metrics_context.total_recycled_num++;
4562
6
                                  }
4563
6
                              });
4564
6
            }
4565
6
            return ret;
4566
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4516
192
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4517
192
            DCHECK(accessor_map_.count(*rid))
4518
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4519
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4520
192
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4521
192
                                     &accessor_map_);
4522
192
            if (!accessor_map_.contains(*rid)) {
4523
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4524
0
                        .tag("resource_id", resource_id)
4525
0
                        .tag("instance_id", instance_id_);
4526
0
                return -1;
4527
0
            }
4528
192
            auto& accessor = accessor_map_[*rid];
4529
192
            int ret = accessor->delete_files(*paths);
4530
192
            if (!ret) {
4531
                // deduplication of different files with the same rowset id
4532
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4533
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4534
192
                std::set<std::string> deleted_rowset_id;
4535
4536
192
                std::for_each(paths->begin(), paths->end(),
4537
192
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4538
192
                               this](const std::string& path) {
4539
192
                                  std::vector<std::string> str;
4540
192
                                  butil::SplitString(path, '/', &str);
4541
192
                                  std::string rowset_id;
4542
192
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4543
192
                                      rowset_id = str.back().substr(0, pos);
4544
192
                                  } else {
4545
192
                                      if (path.find("packed_file/") != std::string::npos) {
4546
192
                                          return; // packed files do not have rowset_id encoded
4547
192
                                      }
4548
192
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4549
192
                                      return;
4550
192
                                  }
4551
192
                                  auto rs_meta = rowsets.find(rowset_id);
4552
192
                                  if (rs_meta != rowsets.end() &&
4553
192
                                      !deleted_rowset_id.contains(rowset_id)) {
4554
192
                                      deleted_rowset_id.emplace(rowset_id);
4555
192
                                      metrics_context.total_recycled_data_size +=
4556
192
                                              rs_meta->second.total_disk_size();
4557
192
                                      segment_metrics_context_.total_recycled_num +=
4558
192
                                              rs_meta->second.num_segments();
4559
192
                                      segment_metrics_context_.total_recycled_data_size +=
4560
192
                                              rs_meta->second.total_disk_size();
4561
192
                                      metrics_context.total_recycled_num++;
4562
192
                                  }
4563
192
                              });
4564
192
            }
4565
192
            return ret;
4566
192
        });
4567
198
    }
4568
439
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4569
6
        LOG_INFO(
4570
6
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4571
6
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4572
6
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4573
6
        concurrent_delete_executor.add([&]() -> int {
4574
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4575
6
            if (!ret) {
4576
6
                auto rs = rowsets.at(rowset_id);
4577
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4578
6
                metrics_context.total_recycled_num++;
4579
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4580
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4581
6
            }
4582
6
            return ret;
4583
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
4573
6
        concurrent_delete_executor.add([&]() -> int {
4574
6
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4575
6
            if (!ret) {
4576
6
                auto rs = rowsets.at(rowset_id);
4577
6
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4578
6
                metrics_context.total_recycled_num++;
4579
6
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4580
6
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4581
6
            }
4582
6
            return ret;
4583
6
        });
4584
6
    }
4585
4586
439
    bool finished = true;
4587
439
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4588
439
    for (int r : rets) {
4589
204
        if (r != 0) {
4590
0
            ret = -1;
4591
0
            break;
4592
0
        }
4593
204
    }
4594
439
    ret = finished ? ret : -1;
4595
439
    return ret;
4596
439
}
4597
4598
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4599
43.5k
                                         const std::string& rowset_id) {
4600
43.5k
    auto it = accessor_map_.find(resource_id);
4601
43.5k
    if (it == accessor_map_.end()) {
4602
400
        LOG_WARNING("instance has no such resource id")
4603
400
                .tag("instance_id", instance_id_)
4604
400
                .tag("resource_id", resource_id)
4605
400
                .tag("tablet_id", tablet_id)
4606
400
                .tag("rowset_id", rowset_id);
4607
400
        return -1;
4608
400
    }
4609
43.1k
    auto& accessor = it->second;
4610
43.1k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4611
43.5k
}
4612
4613
145k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4614
145k
    std::lock_guard lock(recycled_tablets_mtx_);
4615
145k
    return recycled_tablets_.contains(tablet_id);
4616
145k
}
4617
4618
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4619
92.4k
                                                                int64_t tablet_id) {
4620
92.4k
    bool is_mow = true;
4621
92.4k
    if (partition_id != -1) {
4622
82.1k
        std::lock_guard lock(partition_mow_cache_mutex);
4623
82.1k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4624
            // cache hit
4625
1
            is_mow = it->second;
4626
1
            return is_mow ? 1 : 0;
4627
1
        }
4628
82.1k
    }
4629
4630
92.4k
    TabletIndexPB tablet_index;
4631
92.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4632
92.4k
    if (ret == 1) {
4633
        // maybe recycled
4634
92.1k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4635
92.1k
    }
4636
269
    if (ret != 0) {
4637
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4638
0
                     << ", tablet_id=" << tablet_id;
4639
0
        return ret;
4640
0
    }
4641
4642
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4643
    // obtaining its partition ID from the tablet index.
4644
269
    if (partition_id == -1) {
4645
0
        partition_id = tablet_index.partition_id();
4646
0
        std::lock_guard lock(partition_mow_cache_mutex);
4647
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4648
0
            is_mow = it->second;
4649
0
            return is_mow ? 1 : 0;
4650
0
        }
4651
0
    }
4652
4653
269
    std::string tablet_meta_key =
4654
269
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4655
269
                             partition_id, tablet_id});
4656
269
    std::string tablet_meta_value;
4657
269
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4658
269
    if (ret == 1) {
4659
        // maybe recycled
4660
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4661
10
    }
4662
259
    if (ret != 0) {
4663
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4664
0
                     << ", tablet_id=" << tablet_id;
4665
0
        return ret;
4666
0
    }
4667
4668
259
    TabletMetaCloudPB tablet_meta;
4669
259
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4670
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4671
0
                     << ", tablet_id=" << tablet_id;
4672
0
        return -1;
4673
0
    }
4674
259
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4675
259
    std::lock_guard lock(partition_mow_cache_mutex);
4676
259
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4677
259
    return it->second ? 1 : 0;
4678
259
}
4679
4680
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4681
92.4k
                                                         const std::string& rowset_id) {
4682
92.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4683
92.4k
    if (ret <= 0) {
4684
1.00k
        return ret;
4685
1.00k
    }
4686
4687
91.4k
    std::string dbm_start_key =
4688
91.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4689
91.4k
    std::string dbm_end_key = dbm_start_key;
4690
91.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4691
91.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4692
91.4k
    if (ret != 0) {
4693
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4694
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4695
0
                     << " rowset_id=" << rowset_id;
4696
0
    }
4697
91.4k
    return ret;
4698
92.4k
}
4699
4700
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4701
51.2k
    std::string delete_bitmap_start =
4702
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4703
51.2k
    std::string delete_bitmap_end =
4704
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4705
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4706
51.2k
    if (ret != 0) {
4707
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4708
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4709
0
    }
4710
51.2k
    return ret;
4711
51.2k
}
4712
4713
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4714
4
    if (key.empty()) {
4715
0
        return false;
4716
0
    }
4717
4
    std::string_view key_view = key;
4718
4
    key_view.remove_prefix(1); // remove keyspace prefix
4719
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4720
4
    if (decode_key(&key_view, &decoded) != 0) {
4721
0
        return false;
4722
0
    }
4723
4
    if (decoded.size() < 4) {
4724
0
        return false;
4725
0
    }
4726
4
    try {
4727
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4728
4
    } catch (const std::bad_variant_access&) {
4729
0
        return false;
4730
0
    }
4731
4
    return true;
4732
4
}
4733
4734
14
int InstanceRecycler::recycle_packed_files() {
4735
14
    const std::string task_name = "recycle_packed_files";
4736
14
    auto start_tp = steady_clock::now();
4737
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4738
14
    int ret = 0;
4739
14
    PackedFileRecycleStats stats;
4740
4741
14
    register_recycle_task(task_name, start_time);
4742
14
    DORIS_CLOUD_DEFER {
4743
14
        unregister_recycle_task(task_name);
4744
14
        int64_t cost =
4745
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4746
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4747
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4748
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4749
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4750
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4751
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4752
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4753
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4754
14
                                                             stats.bytes_object_deleted);
4755
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4756
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4757
14
                .tag("instance_id", instance_id_)
4758
14
                .tag("num_scanned", stats.num_scanned)
4759
14
                .tag("num_corrected", stats.num_corrected)
4760
14
                .tag("num_deleted", stats.num_deleted)
4761
14
                .tag("num_failed", stats.num_failed)
4762
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4763
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4764
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4765
14
                .tag("bytes_deleted", stats.bytes_deleted)
4766
14
                .tag("ret", ret);
4767
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4742
14
    DORIS_CLOUD_DEFER {
4743
14
        unregister_recycle_task(task_name);
4744
14
        int64_t cost =
4745
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4746
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4747
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4748
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4749
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4750
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4751
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4752
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4753
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4754
14
                                                             stats.bytes_object_deleted);
4755
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4756
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4757
14
                .tag("instance_id", instance_id_)
4758
14
                .tag("num_scanned", stats.num_scanned)
4759
14
                .tag("num_corrected", stats.num_corrected)
4760
14
                .tag("num_deleted", stats.num_deleted)
4761
14
                .tag("num_failed", stats.num_failed)
4762
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4763
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4764
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4765
14
                .tag("bytes_deleted", stats.bytes_deleted)
4766
14
                .tag("ret", ret);
4767
14
    };
4768
4769
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4770
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4771
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4772
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
4769
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4770
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4771
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4772
4
    };
4773
4774
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4775
4776
14
    std::string begin = packed_file_key({instance_id_, ""});
4777
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4778
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4779
0
        ret = -1;
4780
0
    }
4781
4782
14
    return ret;
4783
14
}
4784
4785
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4786
                                                  RecyclerMetricsContext& metrics_context,
4787
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4788
0
    std::string tablet_key_begin, tablet_key_end;
4789
4790
0
    if (partition_id > 0) {
4791
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4792
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4793
0
    } else {
4794
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4795
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4796
0
    }
4797
    // for calculate the total num or bytes of recyled objects
4798
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4799
0
                                                          std::string_view v) -> int {
4800
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4801
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4802
0
            return 0;
4803
0
        }
4804
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4805
4806
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4807
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4808
0
            return 0;
4809
0
        }
4810
4811
0
        if (!is_empty_tablet) {
4812
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4813
0
                return 0;
4814
0
            }
4815
0
            tablet_metrics_context_.total_need_recycle_num++;
4816
0
        }
4817
0
        return 0;
4818
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_
4819
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
4820
0
    metrics_context.report(true);
4821
0
    tablet_metrics_context_.report(true);
4822
0
    segment_metrics_context_.report(true);
4823
0
    return ret;
4824
0
}
4825
4826
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
4827
0
                                                 RecyclerMetricsContext& metrics_context) {
4828
0
    int ret = 0;
4829
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
4830
0
    std::unique_ptr<Transaction> txn;
4831
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4832
0
        LOG_WARNING("failed to recycle tablet ")
4833
0
                .tag("tablet id", tablet_id)
4834
0
                .tag("instance_id", instance_id_)
4835
0
                .tag("reason", "failed to create txn");
4836
0
        ret = -1;
4837
0
    }
4838
0
    GetRowsetResponse resp;
4839
0
    std::string msg;
4840
0
    MetaServiceCode code = MetaServiceCode::OK;
4841
    // get rowsets in tablet
4842
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4843
0
                        tablet_id, code, msg, &resp);
4844
0
    if (code != MetaServiceCode::OK) {
4845
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4846
0
                .tag("tablet id", tablet_id)
4847
0
                .tag("msg", msg)
4848
0
                .tag("code", code)
4849
0
                .tag("instance id", instance_id_);
4850
0
        ret = -1;
4851
0
    }
4852
0
    for (const auto& rs_meta : resp.rowset_meta()) {
4853
        /*
4854
        * For compatibility, we skip the loop for [0-1] here.
4855
        * The purpose of this loop is to delete object files,
4856
        * and since [0-1] only has meta and doesn't have object files,
4857
        * skipping it doesn't affect system correctness.
4858
        *
4859
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
4860
        * would return error -1 directly, causing the recycle operation to fail.
4861
        *
4862
        * [0-1] doesn't have resource id is a bug.
4863
        * In the future, we will fix this problem, after that,
4864
        * we can remove this if statement.
4865
        *
4866
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
4867
        */
4868
4869
0
        if (rs_meta.end_version() == 1) {
4870
            // Assert that [0-1] has no resource_id to make sure
4871
            // this if statement will not be forgetted to remove
4872
            // when the resource id bug is fixed
4873
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4874
0
            continue;
4875
0
        }
4876
0
        if (!rs_meta.has_resource_id()) {
4877
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
4878
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
4879
0
                    .tag("instance_id", instance_id_)
4880
0
                    .tag("tablet_id", tablet_id);
4881
0
            continue;
4882
0
        }
4883
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
4884
0
        auto it = accessor_map_.find(rs_meta.resource_id());
4885
        // possible if the accessor is not initilized correctly
4886
0
        if (it == accessor_map_.end()) [[unlikely]] {
4887
0
            LOG_WARNING(
4888
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
4889
0
                    "recycle process")
4890
0
                    .tag("tablet id", tablet_id)
4891
0
                    .tag("instance_id", instance_id_)
4892
0
                    .tag("resource_id", rs_meta.resource_id())
4893
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
4894
0
            continue;
4895
0
        }
4896
4897
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
4898
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4899
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
4900
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
4901
0
    }
4902
0
    return ret;
4903
0
}
4904
4905
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
4906
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
4907
4.26k
            .tag("instance_id", instance_id_)
4908
4.26k
            .tag("tablet_id", tablet_id);
4909
4910
4.26k
    if (should_recycle_versioned_keys()) {
4911
16
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
4912
16
        if (ret != 0) {
4913
0
            return ret;
4914
0
        }
4915
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
4916
        // during the recycle_versioned_tablet process.
4917
        //
4918
        // .. And remove restore job rowsets of this tablet too
4919
16
    }
4920
4921
4.26k
    int ret = 0;
4922
4.26k
    auto start_time = steady_clock::now();
4923
4924
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
4925
4926
    // collect resource ids
4927
262
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
4928
262
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
4929
262
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
4930
262
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
4931
262
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
4932
262
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
4933
4934
262
    std::set<std::string> resource_ids;
4935
262
    int64_t recycle_rowsets_number = 0;
4936
262
    int64_t recycle_segments_number = 0;
4937
262
    int64_t recycle_rowsets_data_size = 0;
4938
262
    int64_t recycle_rowsets_index_size = 0;
4939
262
    int64_t recycle_restore_job_rowsets_number = 0;
4940
262
    int64_t recycle_restore_job_segments_number = 0;
4941
262
    int64_t recycle_restore_job_rowsets_data_size = 0;
4942
262
    int64_t recycle_restore_job_rowsets_index_size = 0;
4943
262
    int64_t max_rowset_version = 0;
4944
262
    int64_t min_rowset_creation_time = INT64_MAX;
4945
262
    int64_t max_rowset_creation_time = 0;
4946
262
    int64_t min_rowset_expiration_time = INT64_MAX;
4947
262
    int64_t max_rowset_expiration_time = 0;
4948
4949
262
    DORIS_CLOUD_DEFER {
4950
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4951
262
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4952
262
                .tag("instance_id", instance_id_)
4953
262
                .tag("tablet_id", tablet_id)
4954
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4955
262
                .tag("recycle segments number", recycle_segments_number)
4956
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4957
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4958
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4959
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4960
262
                .tag("all restore job rowsets recycle data size",
4961
262
                     recycle_restore_job_rowsets_data_size)
4962
262
                .tag("all restore job rowsets recycle index size",
4963
262
                     recycle_restore_job_rowsets_index_size)
4964
262
                .tag("max rowset version", max_rowset_version)
4965
262
                .tag("min rowset creation time", min_rowset_creation_time)
4966
262
                .tag("max rowset creation time", max_rowset_creation_time)
4967
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4968
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4969
262
                .tag("task type", metrics_context.operation_type)
4970
262
                .tag("ret", ret);
4971
262
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
4949
262
    DORIS_CLOUD_DEFER {
4950
262
        auto cost = duration<float>(steady_clock::now() - start_time).count();
4951
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
4952
262
                .tag("instance_id", instance_id_)
4953
262
                .tag("tablet_id", tablet_id)
4954
262
                .tag("recycle rowsets number", recycle_rowsets_number)
4955
262
                .tag("recycle segments number", recycle_segments_number)
4956
262
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
4957
262
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
4958
262
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
4959
262
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
4960
262
                .tag("all restore job rowsets recycle data size",
4961
262
                     recycle_restore_job_rowsets_data_size)
4962
262
                .tag("all restore job rowsets recycle index size",
4963
262
                     recycle_restore_job_rowsets_index_size)
4964
262
                .tag("max rowset version", max_rowset_version)
4965
262
                .tag("min rowset creation time", min_rowset_creation_time)
4966
262
                .tag("max rowset creation time", max_rowset_creation_time)
4967
262
                .tag("min rowset expiration time", min_rowset_expiration_time)
4968
262
                .tag("max rowset expiration time", max_rowset_expiration_time)
4969
262
                .tag("task type", metrics_context.operation_type)
4970
262
                .tag("ret", ret);
4971
262
    };
4972
4973
262
    std::unique_ptr<Transaction> txn;
4974
262
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
4975
0
        LOG_WARNING("failed to recycle tablet ")
4976
0
                .tag("tablet id", tablet_id)
4977
0
                .tag("instance_id", instance_id_)
4978
0
                .tag("reason", "failed to create txn");
4979
0
        ret = -1;
4980
0
    }
4981
262
    GetRowsetResponse resp;
4982
262
    std::string msg;
4983
262
    MetaServiceCode code = MetaServiceCode::OK;
4984
    // get rowsets in tablet
4985
262
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
4986
262
                        tablet_id, code, msg, &resp);
4987
262
    if (code != MetaServiceCode::OK) {
4988
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
4989
0
                .tag("tablet id", tablet_id)
4990
0
                .tag("msg", msg)
4991
0
                .tag("code", code)
4992
0
                .tag("instance id", instance_id_);
4993
0
        ret = -1;
4994
0
    }
4995
262
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
4996
4997
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
4998
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
4999
3
            if (rs_meta.num_segments() <= 0) {
5000
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5001
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5002
2
                        .tag("instance_id", instance_id_)
5003
2
                        .tag("tablet_id", tablet_id);
5004
2
                recycle_rowsets_number += 1;
5005
2
                continue;
5006
2
            }
5007
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5008
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5009
1
                    .tag("instance_id", instance_id_)
5010
1
                    .tag("tablet_id", tablet_id);
5011
1
            return -1;
5012
3
        }
5013
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5014
0
                << "rs_meta" << rs_meta.ShortDebugString();
5015
2.54k
        auto it = accessor_map_.find(rs_meta.resource_id());
5016
        // possible if the accessor is not initilized correctly
5017
2.54k
        if (it == accessor_map_.end()) [[unlikely]] {
5018
1
            LOG_WARNING(
5019
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5020
1
                    "recycle process")
5021
1
                    .tag("tablet id", tablet_id)
5022
1
                    .tag("instance_id", instance_id_)
5023
1
                    .tag("resource_id", rs_meta.resource_id())
5024
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5025
1
            return -1;
5026
1
        }
5027
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5028
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5029
0
                    .tag("instance_id", instance_id_)
5030
0
                    .tag("tablet_id", tablet_id)
5031
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5032
0
            return -1;
5033
0
        }
5034
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5035
2.54k
                                                           nullptr) != 0) {
5036
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5037
0
                    .tag("instance_id", instance_id_)
5038
0
                    .tag("tablet_id", tablet_id)
5039
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5040
0
            return -1;
5041
0
        }
5042
2.54k
        recycle_rowsets_number += 1;
5043
2.54k
        recycle_segments_number += rs_meta.num_segments();
5044
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5045
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5046
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5047
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5048
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5049
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5050
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5051
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5052
2.54k
    }
5053
5054
    // get restore job rowset in tablet
5055
260
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5056
260
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5057
260
    if (code != MetaServiceCode::OK) {
5058
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5059
0
                .tag("tablet id", tablet_id)
5060
0
                .tag("msg", msg)
5061
0
                .tag("code", code)
5062
0
                .tag("instance id", instance_id_);
5063
0
        return -1;
5064
0
    }
5065
5066
260
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5067
0
        if (!rs_meta.has_resource_id()) {
5068
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5069
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5070
0
                    .tag("instance_id", instance_id_)
5071
0
                    .tag("tablet_id", tablet_id);
5072
0
            return -1;
5073
0
        }
5074
5075
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5076
        // possible if the accessor is not initilized correctly
5077
0
        if (it == accessor_map_.end()) [[unlikely]] {
5078
0
            LOG_WARNING(
5079
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5080
0
                    "recycle process")
5081
0
                    .tag("tablet id", tablet_id)
5082
0
                    .tag("instance_id", instance_id_)
5083
0
                    .tag("resource_id", rs_meta.resource_id())
5084
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5085
0
            return -1;
5086
0
        }
5087
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5088
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5089
0
                    .tag("instance_id", instance_id_)
5090
0
                    .tag("tablet_id", tablet_id)
5091
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5092
0
            return -1;
5093
0
        }
5094
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5095
0
                                                           nullptr) != 0) {
5096
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5097
0
                    .tag("instance_id", instance_id_)
5098
0
                    .tag("tablet_id", tablet_id)
5099
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5100
0
            return -1;
5101
0
        }
5102
0
        recycle_restore_job_rowsets_number += 1;
5103
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5104
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5105
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5106
0
        resource_ids.emplace(rs_meta.resource_id());
5107
0
    }
5108
5109
260
    LOG_INFO("recycle tablet start to delete object")
5110
260
            .tag("instance id", instance_id_)
5111
260
            .tag("tablet id", tablet_id)
5112
260
            .tag("recycle tablet resource ids are",
5113
260
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5114
260
                                 [](std::string rs_id, const auto& it) {
5115
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5116
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
5114
217
                                 [](std::string rs_id, const auto& it) {
5115
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5116
217
                                 }));
5117
5118
260
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5119
260
            _thread_pool_group.s3_producer_pool,
5120
260
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5121
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
5121
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5122
5123
    // delete all rowset data in this tablet
5124
    // ATTN: there may be data leak if not all accessor initilized successfully
5125
    //       partial data deleted if the tablet is stored cross-storage vault
5126
    //       vault id is not attached to TabletMeta...
5127
260
    for (const auto& resource_id : resource_ids) {
5128
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5129
217
        concurrent_delete_executor.add(
5130
217
                [&, rs_id = resource_id,
5131
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5132
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5133
217
                    if (res != 0) {
5134
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5135
3
                                     << " path=" << accessor_ptr->uri()
5136
3
                                     << " task type=" << metrics_context.operation_type;
5137
3
                        return std::make_pair(-1, rs_id);
5138
3
                    }
5139
214
                    return std::make_pair(0, rs_id);
5140
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5131
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5132
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5133
217
                    if (res != 0) {
5134
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5135
3
                                     << " path=" << accessor_ptr->uri()
5136
3
                                     << " task type=" << metrics_context.operation_type;
5137
3
                        return std::make_pair(-1, rs_id);
5138
3
                    }
5139
214
                    return std::make_pair(0, rs_id);
5140
217
                });
5141
217
    }
5142
5143
260
    bool finished = true;
5144
260
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5145
260
    for (auto& r : rets) {
5146
217
        if (r.first != 0) {
5147
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5148
3
            ret = -1;
5149
3
        }
5150
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5151
217
    }
5152
260
    ret = finished ? ret : -1;
5153
5154
260
    if (ret != 0) { // failed recycle tablet data
5155
3
        LOG_WARNING("ret!=0")
5156
3
                .tag("finished", finished)
5157
3
                .tag("ret", ret)
5158
3
                .tag("instance_id", instance_id_)
5159
3
                .tag("tablet_id", tablet_id);
5160
3
        return ret;
5161
3
    }
5162
5163
257
    tablet_metrics_context_.total_recycled_data_size +=
5164
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5165
257
    tablet_metrics_context_.total_recycled_num += 1;
5166
257
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5167
257
    segment_metrics_context_.total_recycled_data_size +=
5168
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5169
257
    metrics_context.total_recycled_data_size +=
5170
257
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5171
257
    tablet_metrics_context_.report();
5172
257
    segment_metrics_context_.report();
5173
257
    metrics_context.report();
5174
5175
257
    txn.reset();
5176
257
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5177
0
        LOG_WARNING("failed to recycle tablet ")
5178
0
                .tag("tablet id", tablet_id)
5179
0
                .tag("instance_id", instance_id_)
5180
0
                .tag("reason", "failed to create txn");
5181
0
        ret = -1;
5182
0
    }
5183
    // delete all rowset kv in this tablet
5184
257
    txn->remove(rs_key0, rs_key1);
5185
257
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5186
257
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5187
5188
    // remove delete bitmap for MoW table
5189
257
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5190
257
    txn->remove(pending_key);
5191
257
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5192
257
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5193
257
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5194
5195
257
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5196
257
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5197
257
    txn->remove(dbm_start_key, dbm_end_key);
5198
257
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5199
257
              << " end=" << hex(dbm_end_key);
5200
5201
257
    TxnErrorCode err = txn->commit();
5202
257
    if (err != TxnErrorCode::TXN_OK) {
5203
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5204
0
        ret = -1;
5205
0
    }
5206
5207
257
    if (ret == 0) {
5208
        // All object files under tablet have been deleted
5209
257
        std::lock_guard lock(recycled_tablets_mtx_);
5210
257
        recycled_tablets_.insert(tablet_id);
5211
257
    }
5212
5213
257
    return ret;
5214
260
}
5215
5216
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5217
16
                                               RecyclerMetricsContext& metrics_context) {
5218
16
    int ret = 0;
5219
16
    auto start_time = steady_clock::now();
5220
5221
16
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5222
5223
    // collect resource ids
5224
13
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5225
13
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5226
13
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5227
13
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5228
5229
13
    int64_t recycle_rowsets_number = 0;
5230
13
    int64_t recycle_segments_number = 0;
5231
13
    int64_t recycle_rowsets_data_size = 0;
5232
13
    int64_t recycle_rowsets_index_size = 0;
5233
13
    int64_t max_rowset_version = 0;
5234
13
    int64_t min_rowset_creation_time = INT64_MAX;
5235
13
    int64_t max_rowset_creation_time = 0;
5236
13
    int64_t min_rowset_expiration_time = INT64_MAX;
5237
13
    int64_t max_rowset_expiration_time = 0;
5238
5239
13
    DORIS_CLOUD_DEFER {
5240
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5241
13
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5242
13
                .tag("instance_id", instance_id_)
5243
13
                .tag("tablet_id", tablet_id)
5244
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5245
13
                .tag("recycle segments number", recycle_segments_number)
5246
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5247
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5248
13
                .tag("max rowset version", max_rowset_version)
5249
13
                .tag("min rowset creation time", min_rowset_creation_time)
5250
13
                .tag("max rowset creation time", max_rowset_creation_time)
5251
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5252
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5253
13
                .tag("ret", ret);
5254
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5239
13
    DORIS_CLOUD_DEFER {
5240
13
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5241
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5242
13
                .tag("instance_id", instance_id_)
5243
13
                .tag("tablet_id", tablet_id)
5244
13
                .tag("recycle rowsets number", recycle_rowsets_number)
5245
13
                .tag("recycle segments number", recycle_segments_number)
5246
13
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5247
13
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5248
13
                .tag("max rowset version", max_rowset_version)
5249
13
                .tag("min rowset creation time", min_rowset_creation_time)
5250
13
                .tag("max rowset creation time", max_rowset_creation_time)
5251
13
                .tag("min rowset expiration time", min_rowset_expiration_time)
5252
13
                .tag("max rowset expiration time", max_rowset_expiration_time)
5253
13
                .tag("ret", ret);
5254
13
    };
5255
5256
13
    std::unique_ptr<Transaction> txn;
5257
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5258
0
        LOG_WARNING("failed to recycle tablet ")
5259
0
                .tag("tablet id", tablet_id)
5260
0
                .tag("instance_id", instance_id_)
5261
0
                .tag("reason", "failed to create txn");
5262
0
        ret = -1;
5263
0
    }
5264
5265
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5266
    // by the related operation logs.
5267
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5268
13
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5269
13
    MetaReader meta_reader(instance_id_);
5270
13
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5271
13
    if (err == TxnErrorCode::TXN_OK) {
5272
13
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5273
13
    }
5274
13
    if (err != TxnErrorCode::TXN_OK) {
5275
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5276
0
                .tag("tablet id", tablet_id)
5277
0
                .tag("err", err)
5278
0
                .tag("instance id", instance_id_);
5279
0
        ret = -1;
5280
0
    }
5281
5282
13
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5283
13
             load_rowset_metas.size(), compact_rowset_metas.size())
5284
13
            .tag("instance_id", instance_id_)
5285
13
            .tag("tablet_id", tablet_id);
5286
5287
13
    SyncExecutor<int> concurrent_delete_executor(
5288
13
            _thread_pool_group.s3_producer_pool,
5289
13
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5290
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
5291
5292
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5293
61
        recycle_rowsets_number += 1;
5294
61
        recycle_segments_number += rs_meta.num_segments();
5295
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5296
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5297
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5298
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5299
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5300
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5301
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5302
61
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5292
61
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5293
61
        recycle_rowsets_number += 1;
5294
61
        recycle_segments_number += rs_meta.num_segments();
5295
61
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5296
61
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5297
61
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5298
61
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5299
61
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5300
61
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5301
61
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5302
61
    };
5303
5304
13
    std::vector<RowsetDeleteTask> all_tasks;
5305
61
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5306
61
        update_rowset_stats(rs_meta);
5307
        // Version 0-1 rowset has no resource_id and no actual data files,
5308
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5309
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5310
61
        RowsetDeleteTask task;
5311
61
        task.rowset_meta = rs_meta;
5312
61
        task.versioned_rowset_key =
5313
61
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5314
61
        task.non_versioned_rowset_key =
5315
61
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5316
61
        task.versionstamp = versionstamp;
5317
61
        all_tasks.push_back(std::move(task));
5318
61
    }
5319
5320
13
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5321
0
        update_rowset_stats(rs_meta);
5322
        // Version 0-1 rowset has no resource_id and no actual data files,
5323
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5324
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5325
0
        RowsetDeleteTask task;
5326
0
        task.rowset_meta = rs_meta;
5327
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5328
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5329
0
        task.non_versioned_rowset_key =
5330
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5331
0
        task.versionstamp = versionstamp;
5332
0
        all_tasks.push_back(std::move(task));
5333
0
    }
5334
5335
13
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5336
0
        RecycleRowsetPB recycle_rowset;
5337
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5338
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5339
0
            return -1;
5340
0
        }
5341
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5342
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5343
                // in old version, keep this key-value pair and it needs to be checked manually
5344
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5345
0
                return -1;
5346
0
            }
5347
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5348
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5349
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5350
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5351
0
                return -1;
5352
0
            }
5353
            // decode rowset_id
5354
0
            auto k1 = k;
5355
0
            k1.remove_prefix(1);
5356
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5357
0
            decode_key(&k1, &out);
5358
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5359
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5360
0
            LOG_INFO("delete old-version rowset data")
5361
0
                    .tag("instance_id", instance_id_)
5362
0
                    .tag("tablet_id", tablet_id)
5363
0
                    .tag("rowset_id", rowset_id);
5364
5365
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5366
            // so we must use prefix deletion directly instead of batch delete.
5367
0
            concurrent_delete_executor.add(
5368
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5369
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5370
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5371
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
5372
0
        } else {
5373
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5374
            // Version 0-1 rowset has no resource_id and no actual data files,
5375
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5376
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5377
0
            RowsetDeleteTask task;
5378
0
            task.rowset_meta = rowset_meta;
5379
0
            task.recycle_rowset_key = k;
5380
0
            all_tasks.push_back(std::move(task));
5381
0
        }
5382
0
        return 0;
5383
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_
5384
5385
13
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5386
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5387
0
                .tag("tablet id", tablet_id)
5388
0
                .tag("instance_id", instance_id_)
5389
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5390
0
        ret = -1;
5391
0
    }
5392
5393
    // Phase 1: Classify tasks by ref_count
5394
13
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5395
61
    for (auto& task : all_tasks) {
5396
61
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5397
61
        if (classify_ret < 0) {
5398
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5399
0
                    .tag("instance_id", instance_id_)
5400
0
                    .tag("tablet_id", tablet_id)
5401
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5402
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5403
0
                return recycle_rowset_meta_and_data(t);
5404
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5405
0
        }
5406
61
    }
5407
5408
13
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5409
5410
13
    LOG_INFO("batch delete plan created")
5411
13
            .tag("instance_id", instance_id_)
5412
13
            .tag("tablet_id", tablet_id)
5413
13
            .tag("plan_count", batch_delete_tasks.size());
5414
5415
    // Phase 2: Execute batch delete using existing delete_rowset_data
5416
13
    if (!batch_delete_tasks.empty()) {
5417
11
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5418
50
        for (const auto& task : batch_delete_tasks) {
5419
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5420
50
            if (task.rowset_meta.resource_id().empty()) {
5421
11
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5422
11
                        .tag("instance_id", instance_id_)
5423
11
                        .tag("tablet_id", tablet_id)
5424
11
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5425
11
                continue;
5426
11
            }
5427
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5428
39
        }
5429
5430
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5431
11
        bool delete_success = true;
5432
11
        if (!rowsets_to_delete.empty()) {
5433
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5434
9
                                                         "batch_delete_versioned_tablet");
5435
9
            int delete_ret = delete_rowset_data(
5436
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5437
9
            if (delete_ret != 0) {
5438
0
                LOG_WARNING("batch delete execution failed")
5439
0
                        .tag("instance_id", instance_id_)
5440
0
                        .tag("tablet_id", tablet_id);
5441
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5442
0
                ret = -1;
5443
0
                delete_success = false;
5444
0
            }
5445
9
        }
5446
5447
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5448
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5449
11
        if (delete_success) {
5450
11
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5451
11
            if (cleanup_ret != 0) {
5452
0
                LOG_WARNING("batch delete cleanup failed")
5453
0
                        .tag("instance_id", instance_id_)
5454
0
                        .tag("tablet_id", tablet_id);
5455
0
                ret = -1;
5456
0
            }
5457
11
        }
5458
11
    }
5459
5460
    // Always wait for fallback tasks to complete before returning
5461
13
    bool finished = true;
5462
13
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5463
13
    for (int r : rets) {
5464
0
        if (r != 0) {
5465
0
            ret = -1;
5466
0
        }
5467
0
    }
5468
5469
13
    ret = finished ? ret : -1;
5470
5471
13
    if (ret != 0) { // failed recycle tablet data
5472
0
        LOG_WARNING("recycle versioned tablet failed")
5473
0
                .tag("finished", finished)
5474
0
                .tag("ret", ret)
5475
0
                .tag("instance_id", instance_id_)
5476
0
                .tag("tablet_id", tablet_id);
5477
0
        return ret;
5478
0
    }
5479
5480
13
    tablet_metrics_context_.total_recycled_data_size +=
5481
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5482
13
    tablet_metrics_context_.total_recycled_num += 1;
5483
13
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5484
13
    segment_metrics_context_.total_recycled_data_size +=
5485
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5486
13
    metrics_context.total_recycled_data_size +=
5487
13
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5488
13
    tablet_metrics_context_.report();
5489
13
    segment_metrics_context_.report();
5490
13
    metrics_context.report();
5491
5492
13
    txn.reset();
5493
13
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5494
0
        LOG_WARNING("failed to recycle tablet ")
5495
0
                .tag("tablet id", tablet_id)
5496
0
                .tag("instance_id", instance_id_)
5497
0
                .tag("reason", "failed to create txn");
5498
0
        ret = -1;
5499
0
    }
5500
    // delete all rowset kv in this tablet
5501
13
    txn->remove(rs_key0, rs_key1);
5502
13
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5503
5504
    // remove delete bitmap for MoW table
5505
13
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5506
13
    txn->remove(pending_key);
5507
13
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5508
13
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5509
13
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5510
5511
13
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5512
13
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5513
13
    txn->remove(dbm_start_key, dbm_end_key);
5514
13
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5515
13
              << " end=" << hex(dbm_end_key);
5516
5517
13
    err = txn->commit();
5518
13
    if (err != TxnErrorCode::TXN_OK) {
5519
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5520
0
        ret = -1;
5521
0
    }
5522
5523
13
    if (ret == 0) {
5524
        // All object files under tablet have been deleted
5525
13
        std::lock_guard lock(recycled_tablets_mtx_);
5526
13
        recycled_tablets_.insert(tablet_id);
5527
13
    }
5528
5529
13
    return ret;
5530
13
}
5531
5532
66
int InstanceRecycler::recycle_rowsets() {
5533
66
    if (should_recycle_versioned_keys()) {
5534
5
        return recycle_versioned_rowsets();
5535
5
    }
5536
5537
61
    const std::string task_name = "recycle_rowsets";
5538
61
    int64_t num_scanned = 0;
5539
61
    int64_t num_expired = 0;
5540
61
    int64_t num_prepare = 0;
5541
61
    int64_t num_compacted = 0;
5542
61
    int64_t num_empty_rowset = 0;
5543
61
    size_t total_rowset_key_size = 0;
5544
61
    size_t total_rowset_value_size = 0;
5545
61
    size_t expired_rowset_size = 0;
5546
61
    std::atomic_long num_recycled = 0;
5547
61
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5548
5549
61
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5550
61
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5551
61
    std::string recyc_rs_key0;
5552
61
    std::string recyc_rs_key1;
5553
61
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5554
61
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5555
5556
61
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5557
5558
61
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5559
61
    register_recycle_task(task_name, start_time);
5560
5561
61
    DORIS_CLOUD_DEFER {
5562
61
        unregister_recycle_task(task_name);
5563
61
        int64_t cost =
5564
61
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5565
61
        metrics_context.finish_report();
5566
61
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5567
61
                .tag("instance_id", instance_id_)
5568
61
                .tag("num_scanned", num_scanned)
5569
61
                .tag("num_expired", num_expired)
5570
61
                .tag("num_recycled", num_recycled)
5571
61
                .tag("num_recycled.prepare", num_prepare)
5572
61
                .tag("num_recycled.compacted", num_compacted)
5573
61
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5574
61
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5575
61
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5576
61
                .tag("expired_rowset_meta_size", expired_rowset_size);
5577
61
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5561
7
    DORIS_CLOUD_DEFER {
5562
7
        unregister_recycle_task(task_name);
5563
7
        int64_t cost =
5564
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5565
7
        metrics_context.finish_report();
5566
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5567
7
                .tag("instance_id", instance_id_)
5568
7
                .tag("num_scanned", num_scanned)
5569
7
                .tag("num_expired", num_expired)
5570
7
                .tag("num_recycled", num_recycled)
5571
7
                .tag("num_recycled.prepare", num_prepare)
5572
7
                .tag("num_recycled.compacted", num_compacted)
5573
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5574
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5575
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5576
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5577
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5561
54
    DORIS_CLOUD_DEFER {
5562
54
        unregister_recycle_task(task_name);
5563
54
        int64_t cost =
5564
54
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5565
54
        metrics_context.finish_report();
5566
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5567
54
                .tag("instance_id", instance_id_)
5568
54
                .tag("num_scanned", num_scanned)
5569
54
                .tag("num_expired", num_expired)
5570
54
                .tag("num_recycled", num_recycled)
5571
54
                .tag("num_recycled.prepare", num_prepare)
5572
54
                .tag("num_recycled.compacted", num_compacted)
5573
54
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5574
54
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5575
54
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5576
54
                .tag("expired_rowset_meta_size", expired_rowset_size);
5577
54
    };
5578
5579
61
    std::vector<std::string> rowset_keys;
5580
61
    std::vector<std::string> rowset_keys_to_mark_recycled;
5581
61
    std::vector<std::string> rowset_keys_to_abort_job;
5582
    // rowset_id -> rowset_meta
5583
    // store rowset id and meta for statistics rs size when delete
5584
61
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5585
5586
61
    std::mutex async_recycled_rowset_keys_mutex;
5587
61
    std::vector<std::string> async_recycled_rowset_keys;
5588
61
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5589
61
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5590
61
    worker_pool->start();
5591
61
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5592
61
                                            int64_t partition_id, int64_t tablet_id,
5593
30.9k
                                            const std::string& rowset_id) {
5594
        // Try to delete rowset data in background thread
5595
30.9k
        int ret = worker_pool->submit_with_timeout(
5596
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5597
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5598
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5599
0
                        return;
5600
0
                    }
5601
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5602
28.4k
                        0) {
5603
0
                        return;
5604
0
                    }
5605
28.4k
                    std::vector<std::string> keys;
5606
28.4k
                    {
5607
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5608
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5609
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5610
278
                            keys.swap(async_recycled_rowset_keys);
5611
278
                        }
5612
28.4k
                    }
5613
28.4k
                    if (keys.empty()) return;
5614
284
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5615
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5616
0
                                     << instance_id_;
5617
284
                    } else {
5618
284
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5619
284
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5620
284
                                           num_recycled, start_time);
5621
284
                    }
5622
284
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5596
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5597
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5598
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5599
0
                        return;
5600
0
                    }
5601
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5602
1
                        0) {
5603
0
                        return;
5604
0
                    }
5605
1
                    std::vector<std::string> keys;
5606
1
                    {
5607
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5608
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5609
1
                        if (async_recycled_rowset_keys.size() > 100) {
5610
0
                            keys.swap(async_recycled_rowset_keys);
5611
0
                        }
5612
1
                    }
5613
1
                    if (keys.empty()) return;
5614
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5615
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5616
0
                                     << instance_id_;
5617
0
                    } else {
5618
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5619
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5620
0
                                           num_recycled, start_time);
5621
0
                    }
5622
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5596
28.4k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5597
28.4k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5598
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5599
0
                        return;
5600
0
                    }
5601
28.4k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5602
28.4k
                        0) {
5603
0
                        return;
5604
0
                    }
5605
28.4k
                    std::vector<std::string> keys;
5606
28.4k
                    {
5607
28.4k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5608
28.4k
                        async_recycled_rowset_keys.push_back(std::move(key));
5609
28.4k
                        if (async_recycled_rowset_keys.size() > 100) {
5610
278
                            keys.swap(async_recycled_rowset_keys);
5611
278
                        }
5612
28.4k
                    }
5613
28.4k
                    if (keys.empty()) return;
5614
284
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5615
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5616
0
                                     << instance_id_;
5617
284
                    } else {
5618
284
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5619
284
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5620
284
                                           num_recycled, start_time);
5621
284
                    }
5622
284
                },
5623
30.9k
                0);
5624
30.9k
        if (ret == 0) return 0;
5625
        // Submit task failed, delete rowset data in current thread
5626
2.48k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5627
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5628
0
            return -1;
5629
0
        }
5630
2.48k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5631
0
            return -1;
5632
0
        }
5633
2.48k
        rowset_keys.push_back(std::move(key));
5634
2.48k
        return 0;
5635
2.48k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5593
1
                                            const std::string& rowset_id) {
5594
        // Try to delete rowset data in background thread
5595
1
        int ret = worker_pool->submit_with_timeout(
5596
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5597
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5598
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5599
1
                        return;
5600
1
                    }
5601
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5602
1
                        0) {
5603
1
                        return;
5604
1
                    }
5605
1
                    std::vector<std::string> keys;
5606
1
                    {
5607
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5608
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5609
1
                        if (async_recycled_rowset_keys.size() > 100) {
5610
1
                            keys.swap(async_recycled_rowset_keys);
5611
1
                        }
5612
1
                    }
5613
1
                    if (keys.empty()) return;
5614
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5615
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5616
1
                                     << instance_id_;
5617
1
                    } else {
5618
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5619
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5620
1
                                           num_recycled, start_time);
5621
1
                    }
5622
1
                },
5623
1
                0);
5624
1
        if (ret == 0) return 0;
5625
        // Submit task failed, delete rowset data in current thread
5626
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5627
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5628
0
            return -1;
5629
0
        }
5630
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5631
0
            return -1;
5632
0
        }
5633
0
        rowset_keys.push_back(std::move(key));
5634
0
        return 0;
5635
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5593
30.9k
                                            const std::string& rowset_id) {
5594
        // Try to delete rowset data in background thread
5595
30.9k
        int ret = worker_pool->submit_with_timeout(
5596
30.9k
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5597
30.9k
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5598
30.9k
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5599
30.9k
                        return;
5600
30.9k
                    }
5601
30.9k
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5602
30.9k
                        0) {
5603
30.9k
                        return;
5604
30.9k
                    }
5605
30.9k
                    std::vector<std::string> keys;
5606
30.9k
                    {
5607
30.9k
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5608
30.9k
                        async_recycled_rowset_keys.push_back(std::move(key));
5609
30.9k
                        if (async_recycled_rowset_keys.size() > 100) {
5610
30.9k
                            keys.swap(async_recycled_rowset_keys);
5611
30.9k
                        }
5612
30.9k
                    }
5613
30.9k
                    if (keys.empty()) return;
5614
30.9k
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5615
30.9k
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5616
30.9k
                                     << instance_id_;
5617
30.9k
                    } else {
5618
30.9k
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5619
30.9k
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5620
30.9k
                                           num_recycled, start_time);
5621
30.9k
                    }
5622
30.9k
                },
5623
30.9k
                0);
5624
30.9k
        if (ret == 0) return 0;
5625
        // Submit task failed, delete rowset data in current thread
5626
2.48k
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5627
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5628
0
            return -1;
5629
0
        }
5630
2.48k
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5631
0
            return -1;
5632
0
        }
5633
2.48k
        rowset_keys.push_back(std::move(key));
5634
2.48k
        return 0;
5635
2.48k
    };
5636
5637
61
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5638
5639
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5640
124k
        ++num_scanned;
5641
124k
        total_rowset_key_size += k.size();
5642
124k
        total_rowset_value_size += v.size();
5643
124k
        RecycleRowsetPB rowset;
5644
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5645
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5646
0
            return -1;
5647
0
        }
5648
5649
124k
        int64_t current_time = ::time(nullptr);
5650
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5651
5652
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5653
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5654
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5655
124k
        if (current_time < expiration) { // not expired
5656
0
            return 0;
5657
0
        }
5658
124k
        ++num_expired;
5659
124k
        expired_rowset_size += v.size();
5660
5661
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5662
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5663
                // in old version, keep this key-value pair and it needs to be checked manually
5664
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5665
0
                return -1;
5666
0
            }
5667
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5668
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5669
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5670
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5671
10.0k
                rowset_keys.emplace_back(k);
5672
10.0k
                return 0;
5673
10.0k
            }
5674
            // decode rowset_id
5675
10.2k
            auto k1 = k;
5676
10.2k
            k1.remove_prefix(1);
5677
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5678
10.2k
            decode_key(&k1, &out);
5679
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5680
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5681
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5682
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5683
10.2k
                      << " task_type=" << metrics_context.operation_type;
5684
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5685
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5686
0
                return -1;
5687
0
            }
5688
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5689
10.2k
            metrics_context.total_recycled_num++;
5690
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5691
10.2k
                    rowset.rowset_meta().total_disk_size();
5692
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5693
10.2k
            return 0;
5694
10.2k
        }
5695
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5696
5697
        // TODO(plat1ko): check rowset not referenced
5698
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5699
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5700
0
                LOG_INFO("recycle rowset that has empty resource id");
5701
0
            } else {
5702
                // other situations, keep this key-value pair and it needs to be checked manually
5703
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5704
0
                return -1;
5705
0
            }
5706
0
        }
5707
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5708
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5709
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5710
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5711
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5712
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5713
104k
                  << " rowset_meta_size=" << v.size()
5714
104k
                  << " creation_time=" << rowset_meta->creation_time()
5715
104k
                  << " task_type=" << metrics_context.operation_type;
5716
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5717
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5718
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5719
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5720
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5721
20.0k
                                 "kv "
5722
20.0k
                                 "at next turn, instance_id="
5723
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5724
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5725
20.0k
                              << rowset_meta->end_version() << "]";
5726
20.0k
                    return 0;
5727
20.0k
                }
5728
50.0k
            }
5729
5730
30.9k
            num_prepare += 1;
5731
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5732
30.9k
                rowset_meta->end_version() != 1) {
5733
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5734
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5735
10.2k
                                 "instance_id="
5736
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5737
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5738
10.2k
                              << rowset_meta->end_version() << "]";
5739
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5740
10.2k
                    return 0;
5741
10.2k
                }
5742
30.2k
            }
5743
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5744
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5745
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5746
0
                return -1;
5747
0
            }
5748
53.1k
        } else {
5749
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5750
53.1k
            rowset_keys.emplace_back(k);
5751
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5752
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5753
53.1k
                ++num_empty_rowset;
5754
53.1k
            }
5755
53.1k
        }
5756
73.7k
        return 0;
5757
104k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5639
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5640
7
        ++num_scanned;
5641
7
        total_rowset_key_size += k.size();
5642
7
        total_rowset_value_size += v.size();
5643
7
        RecycleRowsetPB rowset;
5644
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5645
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5646
0
            return -1;
5647
0
        }
5648
5649
7
        int64_t current_time = ::time(nullptr);
5650
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5651
5652
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5653
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5654
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5655
7
        if (current_time < expiration) { // not expired
5656
0
            return 0;
5657
0
        }
5658
7
        ++num_expired;
5659
7
        expired_rowset_size += v.size();
5660
5661
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5662
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5663
                // in old version, keep this key-value pair and it needs to be checked manually
5664
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5665
0
                return -1;
5666
0
            }
5667
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5668
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5669
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5670
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5671
0
                rowset_keys.emplace_back(k);
5672
0
                return 0;
5673
0
            }
5674
            // decode rowset_id
5675
0
            auto k1 = k;
5676
0
            k1.remove_prefix(1);
5677
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5678
0
            decode_key(&k1, &out);
5679
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5680
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5681
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5682
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5683
0
                      << " task_type=" << metrics_context.operation_type;
5684
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5685
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5686
0
                return -1;
5687
0
            }
5688
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5689
0
            metrics_context.total_recycled_num++;
5690
0
            segment_metrics_context_.total_recycled_data_size +=
5691
0
                    rowset.rowset_meta().total_disk_size();
5692
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5693
0
            return 0;
5694
0
        }
5695
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5696
5697
        // TODO(plat1ko): check rowset not referenced
5698
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5699
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5700
0
                LOG_INFO("recycle rowset that has empty resource id");
5701
0
            } else {
5702
                // other situations, keep this key-value pair and it needs to be checked manually
5703
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5704
0
                return -1;
5705
0
            }
5706
0
        }
5707
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5708
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5709
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5710
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5711
7
                  << "] txn_id=" << rowset_meta->txn_id()
5712
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5713
7
                  << " rowset_meta_size=" << v.size()
5714
7
                  << " creation_time=" << rowset_meta->creation_time()
5715
7
                  << " task_type=" << metrics_context.operation_type;
5716
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5717
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5718
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5719
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5720
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5721
4
                                 "kv "
5722
4
                                 "at next turn, instance_id="
5723
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5724
4
                              << " version=[" << rowset_meta->start_version() << '-'
5725
4
                              << rowset_meta->end_version() << "]";
5726
4
                    return 0;
5727
4
                }
5728
6
            }
5729
5730
3
            num_prepare += 1;
5731
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5732
3
                rowset_meta->end_version() != 1) {
5733
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5734
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5735
2
                                 "instance_id="
5736
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5737
2
                              << " version=[" << rowset_meta->start_version() << '-'
5738
2
                              << rowset_meta->end_version() << "]";
5739
2
                    rowset_keys_to_abort_job.emplace_back(k);
5740
2
                    return 0;
5741
2
                }
5742
2
            }
5743
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5744
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5745
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5746
0
                return -1;
5747
0
            }
5748
1
        } else {
5749
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5750
0
            rowset_keys.emplace_back(k);
5751
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5752
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5753
0
                ++num_empty_rowset;
5754
0
            }
5755
0
        }
5756
1
        return 0;
5757
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5639
124k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5640
124k
        ++num_scanned;
5641
124k
        total_rowset_key_size += k.size();
5642
124k
        total_rowset_value_size += v.size();
5643
124k
        RecycleRowsetPB rowset;
5644
124k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5645
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5646
0
            return -1;
5647
0
        }
5648
5649
124k
        int64_t current_time = ::time(nullptr);
5650
124k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5651
5652
124k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5653
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5654
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5655
124k
        if (current_time < expiration) { // not expired
5656
0
            return 0;
5657
0
        }
5658
124k
        ++num_expired;
5659
124k
        expired_rowset_size += v.size();
5660
5661
124k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5662
20.2k
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5663
                // in old version, keep this key-value pair and it needs to be checked manually
5664
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5665
0
                return -1;
5666
0
            }
5667
20.2k
            if (rowset.resource_id().empty()) [[unlikely]] {
5668
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5669
10.0k
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5670
10.0k
                          << hex(k) << " value=" << proto_to_json(rowset);
5671
10.0k
                rowset_keys.emplace_back(k);
5672
10.0k
                return 0;
5673
10.0k
            }
5674
            // decode rowset_id
5675
10.2k
            auto k1 = k;
5676
10.2k
            k1.remove_prefix(1);
5677
10.2k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5678
10.2k
            decode_key(&k1, &out);
5679
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5680
10.2k
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5681
10.2k
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5682
10.2k
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5683
10.2k
                      << " task_type=" << metrics_context.operation_type;
5684
10.2k
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5685
10.2k
                                             rowset.tablet_id(), rowset_id) != 0) {
5686
0
                return -1;
5687
0
            }
5688
10.2k
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5689
10.2k
            metrics_context.total_recycled_num++;
5690
10.2k
            segment_metrics_context_.total_recycled_data_size +=
5691
10.2k
                    rowset.rowset_meta().total_disk_size();
5692
10.2k
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5693
10.2k
            return 0;
5694
10.2k
        }
5695
104k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5696
5697
        // TODO(plat1ko): check rowset not referenced
5698
104k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5699
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5700
0
                LOG_INFO("recycle rowset that has empty resource id");
5701
0
            } else {
5702
                // other situations, keep this key-value pair and it needs to be checked manually
5703
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5704
0
                return -1;
5705
0
            }
5706
0
        }
5707
104k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5708
104k
                  << " tablet_id=" << rowset_meta->tablet_id()
5709
104k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5710
104k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5711
104k
                  << "] txn_id=" << rowset_meta->txn_id()
5712
104k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5713
104k
                  << " rowset_meta_size=" << v.size()
5714
104k
                  << " creation_time=" << rowset_meta->creation_time()
5715
104k
                  << " task_type=" << metrics_context.operation_type;
5716
104k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5717
50.9k
            if (config::enable_mark_delete_rowset_before_recycle) {
5718
50.0k
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5719
20.0k
                    rowset_keys_to_mark_recycled.emplace_back(k);
5720
20.0k
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5721
20.0k
                                 "kv "
5722
20.0k
                                 "at next turn, instance_id="
5723
20.0k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5724
20.0k
                              << " version=[" << rowset_meta->start_version() << '-'
5725
20.0k
                              << rowset_meta->end_version() << "]";
5726
20.0k
                    return 0;
5727
20.0k
                }
5728
50.0k
            }
5729
5730
30.9k
            num_prepare += 1;
5731
30.9k
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5732
30.9k
                rowset_meta->end_version() != 1) {
5733
30.2k
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5734
10.2k
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5735
10.2k
                                 "instance_id="
5736
10.2k
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5737
10.2k
                              << " version=[" << rowset_meta->start_version() << '-'
5738
10.2k
                              << rowset_meta->end_version() << "]";
5739
10.2k
                    rowset_keys_to_abort_job.emplace_back(k);
5740
10.2k
                    return 0;
5741
10.2k
                }
5742
30.2k
            }
5743
20.6k
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5744
20.6k
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5745
20.6k
                                             rowset_meta->rowset_id_v2()) != 0) {
5746
0
                return -1;
5747
0
            }
5748
53.1k
        } else {
5749
53.1k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5750
53.1k
            rowset_keys.emplace_back(k);
5751
53.1k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5752
53.1k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5753
53.1k
                ++num_empty_rowset;
5754
53.1k
            }
5755
53.1k
        }
5756
73.7k
        return 0;
5757
104k
    };
5758
5759
390
    auto loop_done = [&]() -> int {
5760
390
        std::vector<std::string> rowset_keys_to_delete;
5761
        // rowset_id -> rowset_meta
5762
        // store rowset id and meta for statistics rs size when delete
5763
390
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5764
390
        std::vector<std::string> mark_keys_to_process;
5765
390
        std::vector<std::string> abort_job_keys_to_process;
5766
390
        rowset_keys_to_delete.swap(rowset_keys);
5767
390
        rowsets_to_delete.swap(rowsets);
5768
390
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5769
390
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5770
390
        if (!mark_keys_to_process.empty()) {
5771
69
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5772
69
                    *worker_pool, std::move(mark_keys_to_process));
5773
69
        }
5774
390
        if (!abort_job_keys_to_process.empty()) {
5775
46
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5776
46
                                               &num_recycled);
5777
46
        }
5778
390
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5779
390
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5780
390
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5781
390
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5782
390
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5783
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5784
0
                return;
5785
0
            }
5786
390
            if (!versioned_delete_bitmap_key_groups.empty() &&
5787
390
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5788
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
5789
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5790
0
                             << instance_id_;
5791
0
                return;
5792
0
            }
5793
390
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5794
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5795
0
                return;
5796
0
            }
5797
390
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5798
390
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5779
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5780
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5781
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5782
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5783
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5784
0
                return;
5785
0
            }
5786
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5787
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5788
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
5789
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5790
0
                             << instance_id_;
5791
0
                return;
5792
0
            }
5793
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5794
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5795
0
                return;
5796
0
            }
5797
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5798
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5779
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5780
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5781
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5782
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5783
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5784
0
                return;
5785
0
            }
5786
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
5787
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5788
49
                                                         versioned_delete_bitmap_key_groups) != 0) {
5789
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5790
0
                             << instance_id_;
5791
0
                return;
5792
0
            }
5793
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5794
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5795
0
                return;
5796
0
            }
5797
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5798
383
        });
5799
390
        return 0;
5800
390
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5759
7
    auto loop_done = [&]() -> int {
5760
7
        std::vector<std::string> rowset_keys_to_delete;
5761
        // rowset_id -> rowset_meta
5762
        // store rowset id and meta for statistics rs size when delete
5763
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5764
7
        std::vector<std::string> mark_keys_to_process;
5765
7
        std::vector<std::string> abort_job_keys_to_process;
5766
7
        rowset_keys_to_delete.swap(rowset_keys);
5767
7
        rowsets_to_delete.swap(rowsets);
5768
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5769
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5770
7
        if (!mark_keys_to_process.empty()) {
5771
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5772
4
                    *worker_pool, std::move(mark_keys_to_process));
5773
4
        }
5774
7
        if (!abort_job_keys_to_process.empty()) {
5775
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5776
2
                                               &num_recycled);
5777
2
        }
5778
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5779
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5780
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5781
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5782
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5783
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5784
7
                return;
5785
7
            }
5786
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5787
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5788
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
5789
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5790
7
                             << instance_id_;
5791
7
                return;
5792
7
            }
5793
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5794
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5795
7
                return;
5796
7
            }
5797
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5798
7
        });
5799
7
        return 0;
5800
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5759
383
    auto loop_done = [&]() -> int {
5760
383
        std::vector<std::string> rowset_keys_to_delete;
5761
        // rowset_id -> rowset_meta
5762
        // store rowset id and meta for statistics rs size when delete
5763
383
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5764
383
        std::vector<std::string> mark_keys_to_process;
5765
383
        std::vector<std::string> abort_job_keys_to_process;
5766
383
        rowset_keys_to_delete.swap(rowset_keys);
5767
383
        rowsets_to_delete.swap(rowsets);
5768
383
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5769
383
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5770
383
        if (!mark_keys_to_process.empty()) {
5771
65
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5772
65
                    *worker_pool, std::move(mark_keys_to_process));
5773
65
        }
5774
383
        if (!abort_job_keys_to_process.empty()) {
5775
44
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5776
44
                                               &num_recycled);
5777
44
        }
5778
383
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5779
383
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5780
383
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5781
383
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5782
383
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5783
383
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5784
383
                return;
5785
383
            }
5786
383
            if (!versioned_delete_bitmap_key_groups.empty() &&
5787
383
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5788
383
                                                         versioned_delete_bitmap_key_groups) != 0) {
5789
383
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5790
383
                             << instance_id_;
5791
383
                return;
5792
383
            }
5793
383
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5794
383
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5795
383
                return;
5796
383
            }
5797
383
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5798
383
        });
5799
383
        return 0;
5800
383
    };
5801
5802
61
    if (config::enable_recycler_stats_metrics) {
5803
0
        scan_and_statistics_rowsets();
5804
0
    }
5805
    // recycle_func and loop_done for scan and recycle
5806
61
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5807
61
                               std::move(loop_done));
5808
5809
61
    worker_pool->stop();
5810
5811
61
    if (!async_recycled_rowset_keys.empty()) {
5812
9
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5813
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5814
0
            return -1;
5815
9
        } else {
5816
9
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5817
9
        }
5818
9
    }
5819
5820
    // Report final metrics after all concurrent tasks completed
5821
61
    segment_metrics_context_.report();
5822
61
    metrics_context.report();
5823
5824
61
    return ret;
5825
61
}
5826
5827
13
int InstanceRecycler::recycle_restore_jobs() {
5828
13
    const std::string task_name = "recycle_restore_jobs";
5829
13
    int64_t num_scanned = 0;
5830
13
    int64_t num_expired = 0;
5831
13
    int64_t num_recycled = 0;
5832
13
    int64_t num_aborted = 0;
5833
5834
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5835
5836
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5837
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5838
13
    std::string restore_job_key0;
5839
13
    std::string restore_job_key1;
5840
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5841
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5842
5843
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5844
5845
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5846
13
    register_recycle_task(task_name, start_time);
5847
5848
13
    DORIS_CLOUD_DEFER {
5849
13
        unregister_recycle_task(task_name);
5850
13
        int64_t cost =
5851
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5852
13
        metrics_context.finish_report();
5853
5854
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5855
13
                .tag("instance_id", instance_id_)
5856
13
                .tag("num_scanned", num_scanned)
5857
13
                .tag("num_expired", num_expired)
5858
13
                .tag("num_recycled", num_recycled)
5859
13
                .tag("num_aborted", num_aborted);
5860
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5848
13
    DORIS_CLOUD_DEFER {
5849
13
        unregister_recycle_task(task_name);
5850
13
        int64_t cost =
5851
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5852
13
        metrics_context.finish_report();
5853
5854
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5855
13
                .tag("instance_id", instance_id_)
5856
13
                .tag("num_scanned", num_scanned)
5857
13
                .tag("num_expired", num_expired)
5858
13
                .tag("num_recycled", num_recycled)
5859
13
                .tag("num_aborted", num_aborted);
5860
13
    };
5861
5862
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5863
5864
13
    std::vector<std::string_view> restore_job_keys;
5865
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5866
41
        ++num_scanned;
5867
41
        RestoreJobCloudPB restore_job_pb;
5868
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5869
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5870
0
            return -1;
5871
0
        }
5872
41
        int64_t expiration =
5873
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5874
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5875
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5876
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5877
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5878
0
                   << " state=" << restore_job_pb.state();
5879
41
        int64_t current_time = ::time(nullptr);
5880
41
        if (current_time < expiration) { // not expired
5881
0
            return 0;
5882
0
        }
5883
41
        ++num_expired;
5884
5885
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5886
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5887
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5888
5889
41
        std::unique_ptr<Transaction> txn;
5890
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5891
41
        if (err != TxnErrorCode::TXN_OK) {
5892
0
            LOG_WARNING("failed to recycle restore job")
5893
0
                    .tag("err", err)
5894
0
                    .tag("tablet id", tablet_id)
5895
0
                    .tag("instance_id", instance_id_)
5896
0
                    .tag("reason", "failed to create txn");
5897
0
            return -1;
5898
0
        }
5899
5900
41
        std::string val;
5901
41
        err = txn->get(k, &val);
5902
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5903
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5904
0
            return 0;
5905
0
        }
5906
41
        if (err != TxnErrorCode::TXN_OK) {
5907
0
            LOG_WARNING("failed to get kv");
5908
0
            return -1;
5909
0
        }
5910
41
        restore_job_pb.Clear();
5911
41
        if (!restore_job_pb.ParseFromString(val)) {
5912
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5913
0
            return -1;
5914
0
        }
5915
5916
        // PREPARED or COMMITTED, change state to DROPPED and return
5917
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5918
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5919
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5920
0
            restore_job_pb.set_need_recycle_data(true);
5921
0
            txn->put(k, restore_job_pb.SerializeAsString());
5922
0
            err = txn->commit();
5923
0
            if (err != TxnErrorCode::TXN_OK) {
5924
0
                LOG_WARNING("failed to commit txn: {}", err);
5925
0
                return -1;
5926
0
            }
5927
0
            num_aborted++;
5928
0
            return 0;
5929
0
        }
5930
5931
        // Change state to RECYCLING
5932
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5933
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5934
21
            txn->put(k, restore_job_pb.SerializeAsString());
5935
21
            err = txn->commit();
5936
21
            if (err != TxnErrorCode::TXN_OK) {
5937
0
                LOG_WARNING("failed to commit txn: {}", err);
5938
0
                return -1;
5939
0
            }
5940
21
            return 0;
5941
21
        }
5942
5943
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5944
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5945
5946
        // Recycle all data associated with the restore job.
5947
        // This includes rowsets, segments, and related resources.
5948
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5949
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5950
0
            LOG_WARNING("failed to recycle tablet")
5951
0
                    .tag("tablet_id", tablet_id)
5952
0
                    .tag("instance_id", instance_id_);
5953
0
            return -1;
5954
0
        }
5955
5956
        // delete all restore job rowset kv
5957
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5958
5959
20
        err = txn->commit();
5960
20
        if (err != TxnErrorCode::TXN_OK) {
5961
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5962
0
                    .tag("err", err)
5963
0
                    .tag("tablet id", tablet_id)
5964
0
                    .tag("instance_id", instance_id_)
5965
0
                    .tag("reason", "failed to commit txn");
5966
0
            return -1;
5967
0
        }
5968
5969
20
        metrics_context.total_recycled_num = ++num_recycled;
5970
20
        metrics_context.report();
5971
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5972
20
        restore_job_keys.push_back(k);
5973
5974
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5975
20
                  << " tablet_id=" << tablet_id;
5976
20
        return 0;
5977
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
5865
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5866
41
        ++num_scanned;
5867
41
        RestoreJobCloudPB restore_job_pb;
5868
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5869
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5870
0
            return -1;
5871
0
        }
5872
41
        int64_t expiration =
5873
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5874
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5875
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5876
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5877
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5878
0
                   << " state=" << restore_job_pb.state();
5879
41
        int64_t current_time = ::time(nullptr);
5880
41
        if (current_time < expiration) { // not expired
5881
0
            return 0;
5882
0
        }
5883
41
        ++num_expired;
5884
5885
41
        int64_t tablet_id = restore_job_pb.tablet_id();
5886
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
5887
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
5888
5889
41
        std::unique_ptr<Transaction> txn;
5890
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5891
41
        if (err != TxnErrorCode::TXN_OK) {
5892
0
            LOG_WARNING("failed to recycle restore job")
5893
0
                    .tag("err", err)
5894
0
                    .tag("tablet id", tablet_id)
5895
0
                    .tag("instance_id", instance_id_)
5896
0
                    .tag("reason", "failed to create txn");
5897
0
            return -1;
5898
0
        }
5899
5900
41
        std::string val;
5901
41
        err = txn->get(k, &val);
5902
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
5903
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
5904
0
            return 0;
5905
0
        }
5906
41
        if (err != TxnErrorCode::TXN_OK) {
5907
0
            LOG_WARNING("failed to get kv");
5908
0
            return -1;
5909
0
        }
5910
41
        restore_job_pb.Clear();
5911
41
        if (!restore_job_pb.ParseFromString(val)) {
5912
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
5913
0
            return -1;
5914
0
        }
5915
5916
        // PREPARED or COMMITTED, change state to DROPPED and return
5917
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
5918
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
5919
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
5920
0
            restore_job_pb.set_need_recycle_data(true);
5921
0
            txn->put(k, restore_job_pb.SerializeAsString());
5922
0
            err = txn->commit();
5923
0
            if (err != TxnErrorCode::TXN_OK) {
5924
0
                LOG_WARNING("failed to commit txn: {}", err);
5925
0
                return -1;
5926
0
            }
5927
0
            num_aborted++;
5928
0
            return 0;
5929
0
        }
5930
5931
        // Change state to RECYCLING
5932
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
5933
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
5934
21
            txn->put(k, restore_job_pb.SerializeAsString());
5935
21
            err = txn->commit();
5936
21
            if (err != TxnErrorCode::TXN_OK) {
5937
0
                LOG_WARNING("failed to commit txn: {}", err);
5938
0
                return -1;
5939
0
            }
5940
21
            return 0;
5941
21
        }
5942
5943
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5944
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5945
5946
        // Recycle all data associated with the restore job.
5947
        // This includes rowsets, segments, and related resources.
5948
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
5949
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
5950
0
            LOG_WARNING("failed to recycle tablet")
5951
0
                    .tag("tablet_id", tablet_id)
5952
0
                    .tag("instance_id", instance_id_);
5953
0
            return -1;
5954
0
        }
5955
5956
        // delete all restore job rowset kv
5957
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5958
5959
20
        err = txn->commit();
5960
20
        if (err != TxnErrorCode::TXN_OK) {
5961
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
5962
0
                    .tag("err", err)
5963
0
                    .tag("tablet id", tablet_id)
5964
0
                    .tag("instance_id", instance_id_)
5965
0
                    .tag("reason", "failed to commit txn");
5966
0
            return -1;
5967
0
        }
5968
5969
20
        metrics_context.total_recycled_num = ++num_recycled;
5970
20
        metrics_context.report();
5971
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
5972
20
        restore_job_keys.push_back(k);
5973
5974
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
5975
20
                  << " tablet_id=" << tablet_id;
5976
20
        return 0;
5977
20
    };
5978
5979
13
    auto loop_done = [&restore_job_keys, this]() -> int {
5980
3
        if (restore_job_keys.empty()) return 0;
5981
1
        DORIS_CLOUD_DEFER {
5982
1
            restore_job_keys.clear();
5983
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
5981
1
        DORIS_CLOUD_DEFER {
5982
1
            restore_job_keys.clear();
5983
1
        };
5984
5985
1
        std::unique_ptr<Transaction> txn;
5986
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5987
1
        if (err != TxnErrorCode::TXN_OK) {
5988
0
            LOG_WARNING("failed to recycle restore job")
5989
0
                    .tag("err", err)
5990
0
                    .tag("instance_id", instance_id_)
5991
0
                    .tag("reason", "failed to create txn");
5992
0
            return -1;
5993
0
        }
5994
20
        for (auto& k : restore_job_keys) {
5995
20
            txn->remove(k);
5996
20
        }
5997
1
        err = txn->commit();
5998
1
        if (err != TxnErrorCode::TXN_OK) {
5999
0
            LOG_WARNING("failed to recycle restore job")
6000
0
                    .tag("err", err)
6001
0
                    .tag("instance_id", instance_id_)
6002
0
                    .tag("reason", "failed to commit txn");
6003
0
            return -1;
6004
0
        }
6005
1
        return 0;
6006
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
5979
3
    auto loop_done = [&restore_job_keys, this]() -> int {
5980
3
        if (restore_job_keys.empty()) return 0;
5981
1
        DORIS_CLOUD_DEFER {
5982
1
            restore_job_keys.clear();
5983
1
        };
5984
5985
1
        std::unique_ptr<Transaction> txn;
5986
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
5987
1
        if (err != TxnErrorCode::TXN_OK) {
5988
0
            LOG_WARNING("failed to recycle restore job")
5989
0
                    .tag("err", err)
5990
0
                    .tag("instance_id", instance_id_)
5991
0
                    .tag("reason", "failed to create txn");
5992
0
            return -1;
5993
0
        }
5994
20
        for (auto& k : restore_job_keys) {
5995
20
            txn->remove(k);
5996
20
        }
5997
1
        err = txn->commit();
5998
1
        if (err != TxnErrorCode::TXN_OK) {
5999
0
            LOG_WARNING("failed to recycle restore job")
6000
0
                    .tag("err", err)
6001
0
                    .tag("instance_id", instance_id_)
6002
0
                    .tag("reason", "failed to commit txn");
6003
0
            return -1;
6004
0
        }
6005
1
        return 0;
6006
1
    };
6007
6008
13
    if (config::enable_recycler_stats_metrics) {
6009
0
        scan_and_statistics_restore_jobs();
6010
0
    }
6011
6012
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6013
13
                            std::move(loop_done));
6014
13
}
6015
6016
11
int InstanceRecycler::recycle_versioned_rowsets() {
6017
11
    const std::string task_name = "recycle_rowsets";
6018
11
    int64_t num_scanned = 0;
6019
11
    int64_t num_expired = 0;
6020
11
    int64_t num_prepare = 0;
6021
11
    int64_t num_compacted = 0;
6022
11
    int64_t num_empty_rowset = 0;
6023
11
    size_t total_rowset_key_size = 0;
6024
11
    size_t total_rowset_value_size = 0;
6025
11
    size_t expired_rowset_size = 0;
6026
11
    std::atomic_long num_recycled = 0;
6027
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6028
6029
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6030
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6031
11
    std::string recyc_rs_key0;
6032
11
    std::string recyc_rs_key1;
6033
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6034
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6035
6036
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6037
6038
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6039
11
    register_recycle_task(task_name, start_time);
6040
6041
11
    DORIS_CLOUD_DEFER {
6042
11
        unregister_recycle_task(task_name);
6043
11
        int64_t cost =
6044
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6045
11
        metrics_context.finish_report();
6046
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6047
11
                .tag("instance_id", instance_id_)
6048
11
                .tag("num_scanned", num_scanned)
6049
11
                .tag("num_expired", num_expired)
6050
11
                .tag("num_recycled", num_recycled)
6051
11
                .tag("num_recycled.prepare", num_prepare)
6052
11
                .tag("num_recycled.compacted", num_compacted)
6053
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6054
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6055
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6056
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6057
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6041
11
    DORIS_CLOUD_DEFER {
6042
11
        unregister_recycle_task(task_name);
6043
11
        int64_t cost =
6044
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6045
11
        metrics_context.finish_report();
6046
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6047
11
                .tag("instance_id", instance_id_)
6048
11
                .tag("num_scanned", num_scanned)
6049
11
                .tag("num_expired", num_expired)
6050
11
                .tag("num_recycled", num_recycled)
6051
11
                .tag("num_recycled.prepare", num_prepare)
6052
11
                .tag("num_recycled.compacted", num_compacted)
6053
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6054
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6055
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6056
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6057
11
    };
6058
6059
11
    std::vector<std::string> orphan_rowset_keys;
6060
6061
    // Store keys of rowset recycled by background workers
6062
11
    std::mutex async_recycled_rowset_keys_mutex;
6063
11
    std::vector<std::string> async_recycled_rowset_keys;
6064
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6065
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6066
11
    worker_pool->start();
6067
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6068
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6069
        // Try to delete rowset data in background thread
6070
400
        int ret = worker_pool->submit_with_timeout(
6071
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6072
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6073
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6074
400
                        return;
6075
400
                    }
6076
                    // The async recycled rowsets are staled format or has not been used,
6077
                    // so we don't need to check the rowset ref count key.
6078
0
                    std::vector<std::string> keys;
6079
0
                    {
6080
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6081
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6082
0
                        if (async_recycled_rowset_keys.size() > 100) {
6083
0
                            keys.swap(async_recycled_rowset_keys);
6084
0
                        }
6085
0
                    }
6086
0
                    if (keys.empty()) return;
6087
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6088
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6089
0
                                     << instance_id_;
6090
0
                    } else {
6091
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6092
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6093
0
                                           num_recycled, start_time);
6094
0
                    }
6095
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
6071
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6072
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6073
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6074
400
                        return;
6075
400
                    }
6076
                    // The async recycled rowsets are staled format or has not been used,
6077
                    // so we don't need to check the rowset ref count key.
6078
0
                    std::vector<std::string> keys;
6079
0
                    {
6080
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6081
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6082
0
                        if (async_recycled_rowset_keys.size() > 100) {
6083
0
                            keys.swap(async_recycled_rowset_keys);
6084
0
                        }
6085
0
                    }
6086
0
                    if (keys.empty()) return;
6087
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6088
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6089
0
                                     << instance_id_;
6090
0
                    } else {
6091
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6092
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6093
0
                                           num_recycled, start_time);
6094
0
                    }
6095
0
                },
6096
400
                0);
6097
400
        if (ret == 0) return 0;
6098
        // Submit task failed, delete rowset data in current thread
6099
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6100
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6101
0
            return -1;
6102
0
        }
6103
0
        orphan_rowset_keys.push_back(std::move(key));
6104
0
        return 0;
6105
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
6068
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6069
        // Try to delete rowset data in background thread
6070
400
        int ret = worker_pool->submit_with_timeout(
6071
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6072
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6073
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6074
400
                        return;
6075
400
                    }
6076
                    // The async recycled rowsets are staled format or has not been used,
6077
                    // so we don't need to check the rowset ref count key.
6078
400
                    std::vector<std::string> keys;
6079
400
                    {
6080
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6081
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6082
400
                        if (async_recycled_rowset_keys.size() > 100) {
6083
400
                            keys.swap(async_recycled_rowset_keys);
6084
400
                        }
6085
400
                    }
6086
400
                    if (keys.empty()) return;
6087
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6088
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6089
400
                                     << instance_id_;
6090
400
                    } else {
6091
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6092
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6093
400
                                           num_recycled, start_time);
6094
400
                    }
6095
400
                },
6096
400
                0);
6097
400
        if (ret == 0) return 0;
6098
        // Submit task failed, delete rowset data in current thread
6099
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6100
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6101
0
            return -1;
6102
0
        }
6103
0
        orphan_rowset_keys.push_back(std::move(key));
6104
0
        return 0;
6105
0
    };
6106
6107
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6108
6109
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6110
2.01k
        ++num_scanned;
6111
2.01k
        total_rowset_key_size += k.size();
6112
2.01k
        total_rowset_value_size += v.size();
6113
2.01k
        RecycleRowsetPB rowset;
6114
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6115
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6116
0
            return -1;
6117
0
        }
6118
6119
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6120
6121
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6122
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6123
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6124
2.01k
        int64_t current_time = ::time(nullptr);
6125
2.01k
        if (current_time < final_expiration) { // not expired
6126
0
            return 0;
6127
0
        }
6128
2.01k
        ++num_expired;
6129
2.01k
        expired_rowset_size += v.size();
6130
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6131
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6132
                // in old version, keep this key-value pair and it needs to be checked manually
6133
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6134
0
                return -1;
6135
0
            }
6136
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6137
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6138
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6139
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6140
0
                orphan_rowset_keys.emplace_back(k);
6141
0
                return -1;
6142
0
            }
6143
            // decode rowset_id
6144
0
            auto k1 = k;
6145
0
            k1.remove_prefix(1);
6146
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6147
0
            decode_key(&k1, &out);
6148
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6149
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6150
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6151
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6152
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6153
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6154
0
                return -1;
6155
0
            }
6156
0
            return 0;
6157
0
        }
6158
        // TODO(plat1ko): check rowset not referenced
6159
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6160
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6161
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6162
0
                LOG_INFO("recycle rowset that has empty resource id");
6163
0
            } else {
6164
                // other situations, keep this key-value pair and it needs to be checked manually
6165
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6166
0
                return -1;
6167
0
            }
6168
0
        }
6169
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6170
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6171
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6172
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6173
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6174
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6175
2.01k
                  << " rowset_meta_size=" << v.size()
6176
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6177
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6178
            // unable to calculate file path, can only be deleted by rowset id prefix
6179
400
            num_prepare += 1;
6180
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6181
400
                                             rowset_meta->tablet_id(),
6182
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6183
0
                return -1;
6184
0
            }
6185
1.61k
        } else {
6186
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6187
1.61k
            worker_pool->submit(
6188
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6189
                        // The load & compact rowset keys are recycled during recycling operation logs.
6190
1.61k
                        RowsetDeleteTask task;
6191
1.61k
                        task.rowset_meta = rowset_meta;
6192
1.61k
                        task.recycle_rowset_key = k;
6193
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6194
1.60k
                            return;
6195
1.60k
                        }
6196
13
                        num_compacted += is_compacted;
6197
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6198
13
                        if (rowset_meta.num_segments() == 0) {
6199
0
                            ++num_empty_rowset;
6200
0
                        }
6201
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
6188
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6189
                        // The load & compact rowset keys are recycled during recycling operation logs.
6190
1.61k
                        RowsetDeleteTask task;
6191
1.61k
                        task.rowset_meta = rowset_meta;
6192
1.61k
                        task.recycle_rowset_key = k;
6193
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6194
1.60k
                            return;
6195
1.60k
                        }
6196
13
                        num_compacted += is_compacted;
6197
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6198
13
                        if (rowset_meta.num_segments() == 0) {
6199
0
                            ++num_empty_rowset;
6200
0
                        }
6201
13
                    });
6202
1.61k
        }
6203
2.01k
        return 0;
6204
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
6109
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6110
2.01k
        ++num_scanned;
6111
2.01k
        total_rowset_key_size += k.size();
6112
2.01k
        total_rowset_value_size += v.size();
6113
2.01k
        RecycleRowsetPB rowset;
6114
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6115
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6116
0
            return -1;
6117
0
        }
6118
6119
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6120
6121
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6122
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6123
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6124
2.01k
        int64_t current_time = ::time(nullptr);
6125
2.01k
        if (current_time < final_expiration) { // not expired
6126
0
            return 0;
6127
0
        }
6128
2.01k
        ++num_expired;
6129
2.01k
        expired_rowset_size += v.size();
6130
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6131
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6132
                // in old version, keep this key-value pair and it needs to be checked manually
6133
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6134
0
                return -1;
6135
0
            }
6136
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6137
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6138
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6139
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6140
0
                orphan_rowset_keys.emplace_back(k);
6141
0
                return -1;
6142
0
            }
6143
            // decode rowset_id
6144
0
            auto k1 = k;
6145
0
            k1.remove_prefix(1);
6146
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6147
0
            decode_key(&k1, &out);
6148
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6149
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6150
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6151
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6152
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6153
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6154
0
                return -1;
6155
0
            }
6156
0
            return 0;
6157
0
        }
6158
        // TODO(plat1ko): check rowset not referenced
6159
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6160
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6161
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6162
0
                LOG_INFO("recycle rowset that has empty resource id");
6163
0
            } else {
6164
                // other situations, keep this key-value pair and it needs to be checked manually
6165
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6166
0
                return -1;
6167
0
            }
6168
0
        }
6169
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6170
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6171
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6172
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6173
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6174
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6175
2.01k
                  << " rowset_meta_size=" << v.size()
6176
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6177
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6178
            // unable to calculate file path, can only be deleted by rowset id prefix
6179
400
            num_prepare += 1;
6180
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6181
400
                                             rowset_meta->tablet_id(),
6182
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6183
0
                return -1;
6184
0
            }
6185
1.61k
        } else {
6186
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6187
1.61k
            worker_pool->submit(
6188
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6189
                        // The load & compact rowset keys are recycled during recycling operation logs.
6190
1.61k
                        RowsetDeleteTask task;
6191
1.61k
                        task.rowset_meta = rowset_meta;
6192
1.61k
                        task.recycle_rowset_key = k;
6193
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6194
1.61k
                            return;
6195
1.61k
                        }
6196
1.61k
                        num_compacted += is_compacted;
6197
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6198
1.61k
                        if (rowset_meta.num_segments() == 0) {
6199
1.61k
                            ++num_empty_rowset;
6200
1.61k
                        }
6201
1.61k
                    });
6202
1.61k
        }
6203
2.01k
        return 0;
6204
2.01k
    };
6205
6206
11
    if (config::enable_recycler_stats_metrics) {
6207
0
        scan_and_statistics_rowsets();
6208
0
    }
6209
6210
11
    auto loop_done = [&]() -> int {
6211
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6212
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6213
0
        }
6214
6
        orphan_rowset_keys.clear();
6215
6
        return 0;
6216
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6210
6
    auto loop_done = [&]() -> int {
6211
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6212
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6213
0
        }
6214
6
        orphan_rowset_keys.clear();
6215
6
        return 0;
6216
6
    };
6217
6218
    // recycle_func and loop_done for scan and recycle
6219
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6220
11
                               std::move(loop_done));
6221
6222
11
    worker_pool->stop();
6223
6224
11
    if (!async_recycled_rowset_keys.empty()) {
6225
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6226
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6227
0
            return -1;
6228
0
        } else {
6229
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6230
0
        }
6231
0
    }
6232
6233
    // Report final metrics after all concurrent tasks completed
6234
11
    segment_metrics_context_.report();
6235
11
    metrics_context.report();
6236
6237
11
    return ret;
6238
11
}
6239
6240
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6241
1.61k
    constexpr int MAX_RETRY = 10;
6242
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6243
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6244
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6245
1.61k
    std::string_view reference_instance_id = instance_id_;
6246
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6247
8
        reference_instance_id = rowset_meta.reference_instance_id();
6248
8
    }
6249
6250
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6251
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6252
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6253
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6254
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6255
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6256
1.61k
        std::unique_ptr<Transaction> txn;
6257
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6258
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6259
0
            LOG_WARNING("failed to create txn").tag("err", err);
6260
0
            return -1;
6261
0
        }
6262
6263
1.61k
        std::string rowset_ref_count_key =
6264
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6265
1.61k
        int64_t ref_count = 0;
6266
1.61k
        {
6267
1.61k
            std::string value;
6268
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6269
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6270
                // This is the old version rowset, we could recycle it directly.
6271
1.60k
                ref_count = 1;
6272
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6273
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6274
0
                return -1;
6275
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6276
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6277
0
                return -1;
6278
0
            }
6279
1.61k
        }
6280
6281
1.61k
        if (ref_count == 1) {
6282
            // It would not be added since it is recycling.
6283
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6284
1.59k
                LOG_WARNING("failed to delete rowset data");
6285
1.59k
                return -1;
6286
1.59k
            }
6287
6288
            // Reset the transaction to avoid timeout.
6289
12
            err = txn_kv_->create_txn(&txn);
6290
12
            if (err != TxnErrorCode::TXN_OK) {
6291
0
                LOG_WARNING("failed to create txn").tag("err", err);
6292
0
                return -1;
6293
0
            }
6294
12
            txn->remove(rowset_ref_count_key);
6295
12
            LOG_INFO("delete rowset data ref count key")
6296
12
                    .tag("txn_id", rowset_meta.txn_id())
6297
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6298
6299
12
            std::string dbm_start_key =
6300
12
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6301
12
            std::string dbm_end_key = meta_delete_bitmap_key(
6302
12
                    {reference_instance_id, tablet_id, rowset_id,
6303
12
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6304
12
            txn->remove(dbm_start_key, dbm_end_key);
6305
12
            LOG_INFO("remove delete bitmap kv")
6306
12
                    .tag("begin", hex(dbm_start_key))
6307
12
                    .tag("end", hex(dbm_end_key));
6308
6309
12
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6310
12
                    {reference_instance_id, tablet_id, rowset_id});
6311
12
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6312
12
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6313
12
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6314
12
            LOG_INFO("remove versioned delete bitmap kv")
6315
12
                    .tag("begin", hex(versioned_dbm_start_key))
6316
12
                    .tag("end", hex(versioned_dbm_end_key));
6317
12
        } else {
6318
            // Decrease the rowset ref count.
6319
            //
6320
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6321
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6322
2
            txn->atomic_add(rowset_ref_count_key, -1);
6323
2
            LOG_INFO("decrease rowset data ref count")
6324
2
                    .tag("txn_id", rowset_meta.txn_id())
6325
2
                    .tag("ref_count", ref_count - 1)
6326
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6327
2
        }
6328
6329
14
        if (!task.versioned_rowset_key.empty()) {
6330
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6331
0
                                                          task.versionstamp);
6332
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6333
0
        }
6334
6335
14
        if (!task.non_versioned_rowset_key.empty()) {
6336
0
            txn->remove(task.non_versioned_rowset_key);
6337
0
            LOG_INFO("remove non versioned rowset key")
6338
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6339
0
        }
6340
6341
        // empty when recycle ref rowsets for deleted instance
6342
14
        if (!task.recycle_rowset_key.empty()) {
6343
13
            txn->remove(task.recycle_rowset_key);
6344
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6345
13
        }
6346
6347
14
        err = txn->commit();
6348
14
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6349
            // The rowset ref count key has been changed, we need to retry.
6350
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6351
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6352
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6353
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6354
0
            continue;
6355
14
        } else if (err != TxnErrorCode::TXN_OK) {
6356
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6357
0
            return -1;
6358
0
        }
6359
14
        LOG_INFO("recycle rowset meta and data success");
6360
14
        return 0;
6361
14
    }
6362
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6363
1
            .tag("tablet_id", tablet_id)
6364
1
            .tag("rowset_id", rowset_id)
6365
1
            .tag("retry", MAX_RETRY);
6366
1
    return -1;
6367
1.61k
}
6368
6369
37
int InstanceRecycler::recycle_tmp_rowsets() {
6370
37
    const std::string task_name = "recycle_tmp_rowsets";
6371
37
    int64_t num_scanned = 0;
6372
37
    int64_t num_expired = 0;
6373
37
    std::atomic_long num_recycled = 0;
6374
37
    size_t expired_rowset_size = 0;
6375
37
    size_t total_rowset_key_size = 0;
6376
37
    size_t total_rowset_value_size = 0;
6377
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6378
6379
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6380
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6381
37
    std::string tmp_rs_key0;
6382
37
    std::string tmp_rs_key1;
6383
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6384
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6385
6386
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6387
6388
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6389
37
    register_recycle_task(task_name, start_time);
6390
6391
37
    DORIS_CLOUD_DEFER {
6392
37
        unregister_recycle_task(task_name);
6393
37
        int64_t cost =
6394
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6395
37
        metrics_context.finish_report();
6396
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6397
37
                .tag("instance_id", instance_id_)
6398
37
                .tag("num_scanned", num_scanned)
6399
37
                .tag("num_expired", num_expired)
6400
37
                .tag("num_recycled", num_recycled)
6401
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6402
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6403
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6404
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6391
12
    DORIS_CLOUD_DEFER {
6392
12
        unregister_recycle_task(task_name);
6393
12
        int64_t cost =
6394
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6395
12
        metrics_context.finish_report();
6396
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6397
12
                .tag("instance_id", instance_id_)
6398
12
                .tag("num_scanned", num_scanned)
6399
12
                .tag("num_expired", num_expired)
6400
12
                .tag("num_recycled", num_recycled)
6401
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6402
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6403
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6404
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6391
25
    DORIS_CLOUD_DEFER {
6392
25
        unregister_recycle_task(task_name);
6393
25
        int64_t cost =
6394
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6395
25
        metrics_context.finish_report();
6396
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6397
25
                .tag("instance_id", instance_id_)
6398
25
                .tag("num_scanned", num_scanned)
6399
25
                .tag("num_expired", num_expired)
6400
25
                .tag("num_recycled", num_recycled)
6401
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6402
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6403
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6404
25
    };
6405
6406
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6407
37
    std::vector<std::string> tmp_rowset_keys;
6408
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6409
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6410
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6411
6412
    // rowset_id -> rowset_meta
6413
    // store tmp_rowset id and meta for statistics rs size when delete
6414
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6415
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6416
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6417
37
    worker_pool->start();
6418
6419
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6420
6421
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6422
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6423
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6424
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6425
53.2k
                                    std::string_view k, std::string_view v) -> int {
6426
53.2k
        ++num_scanned;
6427
53.2k
        total_rowset_key_size += k.size();
6428
53.2k
        total_rowset_value_size += v.size();
6429
53.2k
        doris::RowsetMetaCloudPB rowset;
6430
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6431
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6432
0
            return -1;
6433
0
        }
6434
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6435
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6436
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6437
0
                   << " txn_expiration=" << rowset.txn_expiration()
6438
0
                   << " rowset_creation_time=" << rowset.creation_time();
6439
53.2k
        int64_t current_time = ::time(nullptr);
6440
53.2k
        if (current_time < expiration) { // not expired
6441
0
            return 0;
6442
0
        }
6443
53.2k
        ++num_expired;
6444
53.2k
        expired_rowset_size += v.size();
6445
53.2k
        if (!rowset.has_resource_id()) {
6446
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6447
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6448
0
                return -1;
6449
0
            }
6450
            // might be a delete pred rowset
6451
0
            tmp_rowset_keys.emplace_back(k);
6452
0
            return 0;
6453
0
        }
6454
6455
        // TODO(plat1ko): check rowset not referenced
6456
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6457
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6458
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6459
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6460
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6461
53.2k
                  << " num_expired=" << num_expired
6462
53.2k
                  << " task_type=" << metrics_context.operation_type;
6463
6464
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6465
16
            if (need_mark_rowset_as_recycled(rowset)) {
6466
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6467
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6468
9
                             "at next turn, instance_id="
6469
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6470
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6471
9
                return 0;
6472
9
            }
6473
16
        }
6474
6475
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6476
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6477
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6478
261
                             "instance_id="
6479
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6480
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6481
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6482
261
                return 0;
6483
261
            }
6484
265
        }
6485
6486
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6487
        // Remove the rowset ref count key directly since it has not been used.
6488
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6489
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6490
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6491
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6492
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6493
6494
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6495
53.0k
        return 0;
6496
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6425
16
                                    std::string_view k, std::string_view v) -> int {
6426
16
        ++num_scanned;
6427
16
        total_rowset_key_size += k.size();
6428
16
        total_rowset_value_size += v.size();
6429
16
        doris::RowsetMetaCloudPB rowset;
6430
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6431
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6432
0
            return -1;
6433
0
        }
6434
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6435
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6436
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6437
0
                   << " txn_expiration=" << rowset.txn_expiration()
6438
0
                   << " rowset_creation_time=" << rowset.creation_time();
6439
16
        int64_t current_time = ::time(nullptr);
6440
16
        if (current_time < expiration) { // not expired
6441
0
            return 0;
6442
0
        }
6443
16
        ++num_expired;
6444
16
        expired_rowset_size += v.size();
6445
16
        if (!rowset.has_resource_id()) {
6446
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6447
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6448
0
                return -1;
6449
0
            }
6450
            // might be a delete pred rowset
6451
0
            tmp_rowset_keys.emplace_back(k);
6452
0
            return 0;
6453
0
        }
6454
6455
        // TODO(plat1ko): check rowset not referenced
6456
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6457
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6458
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6459
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6460
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6461
16
                  << " num_expired=" << num_expired
6462
16
                  << " task_type=" << metrics_context.operation_type;
6463
6464
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6465
16
            if (need_mark_rowset_as_recycled(rowset)) {
6466
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6467
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6468
9
                             "at next turn, instance_id="
6469
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6470
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6471
9
                return 0;
6472
9
            }
6473
16
        }
6474
6475
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6476
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6477
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6478
3
                             "instance_id="
6479
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6480
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6481
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6482
3
                return 0;
6483
3
            }
6484
7
        }
6485
6486
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6487
        // Remove the rowset ref count key directly since it has not been used.
6488
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6489
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6490
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6491
4
                  << "key=" << hex(rowset_ref_count_key);
6492
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6493
6494
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6495
4
        return 0;
6496
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6425
53.2k
                                    std::string_view k, std::string_view v) -> int {
6426
53.2k
        ++num_scanned;
6427
53.2k
        total_rowset_key_size += k.size();
6428
53.2k
        total_rowset_value_size += v.size();
6429
53.2k
        doris::RowsetMetaCloudPB rowset;
6430
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6431
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6432
0
            return -1;
6433
0
        }
6434
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6435
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6436
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6437
0
                   << " txn_expiration=" << rowset.txn_expiration()
6438
0
                   << " rowset_creation_time=" << rowset.creation_time();
6439
53.2k
        int64_t current_time = ::time(nullptr);
6440
53.2k
        if (current_time < expiration) { // not expired
6441
0
            return 0;
6442
0
        }
6443
53.2k
        ++num_expired;
6444
53.2k
        expired_rowset_size += v.size();
6445
53.2k
        if (!rowset.has_resource_id()) {
6446
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6447
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6448
0
                return -1;
6449
0
            }
6450
            // might be a delete pred rowset
6451
0
            tmp_rowset_keys.emplace_back(k);
6452
0
            return 0;
6453
0
        }
6454
6455
        // TODO(plat1ko): check rowset not referenced
6456
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6457
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6458
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6459
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6460
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6461
53.2k
                  << " num_expired=" << num_expired
6462
53.2k
                  << " task_type=" << metrics_context.operation_type;
6463
6464
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6465
0
            if (need_mark_rowset_as_recycled(rowset)) {
6466
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6467
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6468
0
                             "at next turn, instance_id="
6469
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6470
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6471
0
                return 0;
6472
0
            }
6473
0
        }
6474
6475
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6476
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6477
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6478
258
                             "instance_id="
6479
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6480
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6481
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6482
258
                return 0;
6483
258
            }
6484
258
        }
6485
6486
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6487
        // Remove the rowset ref count key directly since it has not been used.
6488
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6489
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6490
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6491
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6492
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6493
6494
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6495
53.0k
        return 0;
6496
53.2k
    };
6497
6498
37
    auto loop_done = [&]() -> int {
6499
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6500
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6501
24
        std::vector<std::string> mark_keys_to_process;
6502
24
        std::vector<std::string> abort_keys_to_process;
6503
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6504
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6505
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6506
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6507
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6508
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6509
24
        if (!mark_keys_to_process.empty()) {
6510
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6511
7
                    *worker_pool, std::move(mark_keys_to_process));
6512
7
        }
6513
24
        if (!abort_keys_to_process.empty()) {
6514
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6515
5
                                           &num_recycled, &metrics_context);
6516
5
        }
6517
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6518
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6519
24
                             tmp_rowset_ref_count_keys_to_delete =
6520
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6521
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6522
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6523
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6524
24
                                   metrics_context) != 0) {
6525
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6526
2
                return;
6527
2
            }
6528
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6529
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6530
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6531
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6532
0
                                 << rs.ShortDebugString();
6533
0
                    return;
6534
0
                }
6535
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6536
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6537
0
                                 << rs.ShortDebugString();
6538
0
                    return;
6539
0
                }
6540
51.0k
            }
6541
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6542
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6543
0
                return;
6544
0
            }
6545
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6546
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6547
0
                return;
6548
0
            }
6549
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6550
22
            return;
6551
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6522
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6523
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6524
12
                                   metrics_context) != 0) {
6525
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6526
0
                return;
6527
0
            }
6528
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6529
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6530
4
                                                       rs.rowset_id_v2()) != 0) {
6531
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6532
0
                                 << rs.ShortDebugString();
6533
0
                    return;
6534
0
                }
6535
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6536
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6537
0
                                 << rs.ShortDebugString();
6538
0
                    return;
6539
0
                }
6540
4
            }
6541
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6542
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6543
0
                return;
6544
0
            }
6545
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6546
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6547
0
                return;
6548
0
            }
6549
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6550
12
            return;
6551
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6522
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6523
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6524
12
                                   metrics_context) != 0) {
6525
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6526
2
                return;
6527
2
            }
6528
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6529
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6530
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6531
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6532
0
                                 << rs.ShortDebugString();
6533
0
                    return;
6534
0
                }
6535
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6536
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6537
0
                                 << rs.ShortDebugString();
6538
0
                    return;
6539
0
                }
6540
51.0k
            }
6541
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6542
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6543
0
                return;
6544
0
            }
6545
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6546
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6547
0
                return;
6548
0
            }
6549
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6550
10
            return;
6551
10
        });
6552
24
        return 0;
6553
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6498
12
    auto loop_done = [&]() -> int {
6499
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6500
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6501
12
        std::vector<std::string> mark_keys_to_process;
6502
12
        std::vector<std::string> abort_keys_to_process;
6503
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6504
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6505
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6506
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6507
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6508
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6509
12
        if (!mark_keys_to_process.empty()) {
6510
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6511
7
                    *worker_pool, std::move(mark_keys_to_process));
6512
7
        }
6513
12
        if (!abort_keys_to_process.empty()) {
6514
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6515
3
                                           &num_recycled, &metrics_context);
6516
3
        }
6517
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6518
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6519
12
                             tmp_rowset_ref_count_keys_to_delete =
6520
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6521
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6522
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6523
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6524
12
                                   metrics_context) != 0) {
6525
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6526
12
                return;
6527
12
            }
6528
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6529
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6530
12
                                                       rs.rowset_id_v2()) != 0) {
6531
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6532
12
                                 << rs.ShortDebugString();
6533
12
                    return;
6534
12
                }
6535
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6536
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6537
12
                                 << rs.ShortDebugString();
6538
12
                    return;
6539
12
                }
6540
12
            }
6541
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6542
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6543
12
                return;
6544
12
            }
6545
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6546
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6547
12
                return;
6548
12
            }
6549
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6550
12
            return;
6551
12
        });
6552
12
        return 0;
6553
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6498
12
    auto loop_done = [&]() -> int {
6499
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6500
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6501
12
        std::vector<std::string> mark_keys_to_process;
6502
12
        std::vector<std::string> abort_keys_to_process;
6503
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6504
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6505
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6506
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6507
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6508
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6509
12
        if (!mark_keys_to_process.empty()) {
6510
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6511
0
                    *worker_pool, std::move(mark_keys_to_process));
6512
0
        }
6513
12
        if (!abort_keys_to_process.empty()) {
6514
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6515
2
                                           &num_recycled, &metrics_context);
6516
2
        }
6517
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6518
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6519
12
                             tmp_rowset_ref_count_keys_to_delete =
6520
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6521
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6522
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6523
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6524
12
                                   metrics_context) != 0) {
6525
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6526
12
                return;
6527
12
            }
6528
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6529
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6530
12
                                                       rs.rowset_id_v2()) != 0) {
6531
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6532
12
                                 << rs.ShortDebugString();
6533
12
                    return;
6534
12
                }
6535
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6536
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6537
12
                                 << rs.ShortDebugString();
6538
12
                    return;
6539
12
                }
6540
12
            }
6541
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6542
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6543
12
                return;
6544
12
            }
6545
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6546
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6547
12
                return;
6548
12
            }
6549
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6550
12
            return;
6551
12
        });
6552
12
        return 0;
6553
12
    };
6554
6555
37
    if (config::enable_recycler_stats_metrics) {
6556
0
        scan_and_statistics_tmp_rowsets();
6557
0
    }
6558
    // recycle_func and loop_done for scan and recycle
6559
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6560
37
                               std::move(loop_done));
6561
6562
37
    worker_pool->stop();
6563
6564
    // Report final metrics after all concurrent tasks completed
6565
37
    segment_metrics_context_.report();
6566
37
    metrics_context.report();
6567
6568
37
    return ret;
6569
37
}
6570
6571
int InstanceRecycler::scan_and_recycle(
6572
        std::string begin, std::string_view end,
6573
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6574
316
        std::function<int()> loop_done) {
6575
316
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6576
316
    int ret = 0;
6577
316
    int64_t cnt = 0;
6578
316
    int get_range_retried = 0;
6579
316
    std::string err;
6580
316
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6581
316
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6582
316
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6583
316
                  << " ret=" << ret << " err=" << err;
6584
316
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6580
31
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6581
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6582
31
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6583
31
                  << " ret=" << ret << " err=" << err;
6584
31
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEEENK3$_0clEv
Line
Count
Source
6580
285
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6581
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6582
285
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6583
285
                  << " ret=" << ret << " err=" << err;
6584
285
    };
6585
6586
316
    std::unique_ptr<RangeGetIterator> it;
6587
840
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6588
669
        if (get_range_retried > 1000) {
6589
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6590
0
            ret = -3;
6591
0
            return ret;
6592
0
        }
6593
669
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6594
669
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6595
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6596
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6597
0
                         << " get_range_retried=" << get_range_retried;
6598
0
            ++get_range_retried;
6599
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6600
0
            continue; // try again
6601
0
        }
6602
669
        if (!it->has_next()) {
6603
145
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6604
145
            break; // scan finished
6605
145
        }
6606
238k
        while (it->has_next()) {
6607
237k
            ++cnt;
6608
            // recycle corresponding resources
6609
237k
            auto [k, v] = it->next();
6610
237k
            if (!it->has_next()) {
6611
524
                begin = k;
6612
524
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6613
524
            }
6614
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6615
237k
            if (recycle_func(k, v) != 0) {
6616
4.00k
                err = "recycle_func error";
6617
4.00k
                ret = -1;
6618
4.00k
            }
6619
237k
        }
6620
524
        begin.push_back('\x00'); // Update to next smallest key for iteration
6621
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6622
524
        if (loop_done && loop_done() != 0) {
6623
9
            err = "loop_done error";
6624
9
            ret = -1;
6625
9
        }
6626
524
    }
6627
316
    return ret;
6628
316
}
6629
6630
19
int InstanceRecycler::abort_timeout_txn() {
6631
19
    const std::string task_name = "abort_timeout_txn";
6632
19
    int64_t num_scanned = 0;
6633
19
    int64_t num_timeout = 0;
6634
19
    int64_t num_abort = 0;
6635
19
    int64_t num_advance = 0;
6636
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6637
6638
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6639
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6640
19
    std::string begin_txn_running_key;
6641
19
    std::string end_txn_running_key;
6642
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6643
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6644
6645
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6646
6647
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6648
19
    register_recycle_task(task_name, start_time);
6649
6650
19
    DORIS_CLOUD_DEFER {
6651
19
        unregister_recycle_task(task_name);
6652
19
        int64_t cost =
6653
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6654
19
        metrics_context.finish_report();
6655
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6656
19
                .tag("instance_id", instance_id_)
6657
19
                .tag("num_scanned", num_scanned)
6658
19
                .tag("num_timeout", num_timeout)
6659
19
                .tag("num_abort", num_abort)
6660
19
                .tag("num_advance", num_advance);
6661
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6650
3
    DORIS_CLOUD_DEFER {
6651
3
        unregister_recycle_task(task_name);
6652
3
        int64_t cost =
6653
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6654
3
        metrics_context.finish_report();
6655
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6656
3
                .tag("instance_id", instance_id_)
6657
3
                .tag("num_scanned", num_scanned)
6658
3
                .tag("num_timeout", num_timeout)
6659
3
                .tag("num_abort", num_abort)
6660
3
                .tag("num_advance", num_advance);
6661
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6650
16
    DORIS_CLOUD_DEFER {
6651
16
        unregister_recycle_task(task_name);
6652
16
        int64_t cost =
6653
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6654
16
        metrics_context.finish_report();
6655
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6656
16
                .tag("instance_id", instance_id_)
6657
16
                .tag("num_scanned", num_scanned)
6658
16
                .tag("num_timeout", num_timeout)
6659
16
                .tag("num_abort", num_abort)
6660
16
                .tag("num_advance", num_advance);
6661
16
    };
6662
6663
19
    int64_t current_time =
6664
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6665
6666
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6667
19
                                  &current_time, &metrics_context,
6668
19
                                  this](std::string_view k, std::string_view v) -> int {
6669
9
        ++num_scanned;
6670
6671
9
        std::unique_ptr<Transaction> txn;
6672
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6673
9
        if (err != TxnErrorCode::TXN_OK) {
6674
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6675
0
            return -1;
6676
0
        }
6677
9
        std::string_view k1 = k;
6678
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6679
9
        k1.remove_prefix(1); // Remove key space
6680
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6681
9
        if (decode_key(&k1, &out) != 0) {
6682
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6683
0
            return -1;
6684
0
        }
6685
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6686
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6687
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6688
        // Update txn_info
6689
9
        std::string txn_inf_key, txn_inf_val;
6690
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6691
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6692
9
        if (err != TxnErrorCode::TXN_OK) {
6693
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6694
0
            return -1;
6695
0
        }
6696
9
        TxnInfoPB txn_info;
6697
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6698
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6699
0
            return -1;
6700
0
        }
6701
6702
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6703
3
            txn.reset();
6704
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6705
3
            std::shared_ptr<TxnLazyCommitTask> task =
6706
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6707
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6708
3
            if (ret.first != MetaServiceCode::OK) {
6709
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6710
0
                             << "msg=" << ret.second;
6711
0
                return -1;
6712
0
            }
6713
3
            ++num_advance;
6714
3
            return 0;
6715
6
        } else {
6716
6
            TxnRunningPB txn_running_pb;
6717
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6718
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6719
0
                return -1;
6720
0
            }
6721
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6722
4
                return 0;
6723
4
            }
6724
2
            ++num_timeout;
6725
6726
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6727
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6728
2
            txn_info.set_finish_time(current_time);
6729
2
            txn_info.set_reason("timeout");
6730
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6731
2
            txn_inf_val.clear();
6732
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6733
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6734
0
                return -1;
6735
0
            }
6736
2
            txn->put(txn_inf_key, txn_inf_val);
6737
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6738
            // Put recycle txn key
6739
2
            std::string recyc_txn_key, recyc_txn_val;
6740
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6741
2
            RecycleTxnPB recycle_txn_pb;
6742
2
            recycle_txn_pb.set_creation_time(current_time);
6743
2
            recycle_txn_pb.set_label(txn_info.label());
6744
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6745
0
                LOG_WARNING("failed to serialize txn recycle info")
6746
0
                        .tag("key", hex(k))
6747
0
                        .tag("db_id", db_id)
6748
0
                        .tag("txn_id", txn_id);
6749
0
                return -1;
6750
0
            }
6751
2
            txn->put(recyc_txn_key, recyc_txn_val);
6752
            // Remove txn running key
6753
2
            txn->remove(k);
6754
2
            err = txn->commit();
6755
2
            if (err != TxnErrorCode::TXN_OK) {
6756
0
                LOG_WARNING("failed to commit txn err={}", err)
6757
0
                        .tag("key", hex(k))
6758
0
                        .tag("db_id", db_id)
6759
0
                        .tag("txn_id", txn_id);
6760
0
                return -1;
6761
0
            }
6762
2
            metrics_context.total_recycled_num = ++num_abort;
6763
2
            metrics_context.report();
6764
2
        }
6765
6766
2
        return 0;
6767
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6668
3
                                  this](std::string_view k, std::string_view v) -> int {
6669
3
        ++num_scanned;
6670
6671
3
        std::unique_ptr<Transaction> txn;
6672
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6673
3
        if (err != TxnErrorCode::TXN_OK) {
6674
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6675
0
            return -1;
6676
0
        }
6677
3
        std::string_view k1 = k;
6678
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6679
3
        k1.remove_prefix(1); // Remove key space
6680
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6681
3
        if (decode_key(&k1, &out) != 0) {
6682
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6683
0
            return -1;
6684
0
        }
6685
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6686
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6687
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6688
        // Update txn_info
6689
3
        std::string txn_inf_key, txn_inf_val;
6690
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6691
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6692
3
        if (err != TxnErrorCode::TXN_OK) {
6693
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6694
0
            return -1;
6695
0
        }
6696
3
        TxnInfoPB txn_info;
6697
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6698
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6699
0
            return -1;
6700
0
        }
6701
6702
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6703
3
            txn.reset();
6704
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6705
3
            std::shared_ptr<TxnLazyCommitTask> task =
6706
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6707
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6708
3
            if (ret.first != MetaServiceCode::OK) {
6709
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6710
0
                             << "msg=" << ret.second;
6711
0
                return -1;
6712
0
            }
6713
3
            ++num_advance;
6714
3
            return 0;
6715
3
        } else {
6716
0
            TxnRunningPB txn_running_pb;
6717
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6718
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6719
0
                return -1;
6720
0
            }
6721
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6722
0
                return 0;
6723
0
            }
6724
0
            ++num_timeout;
6725
6726
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6727
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6728
0
            txn_info.set_finish_time(current_time);
6729
0
            txn_info.set_reason("timeout");
6730
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6731
0
            txn_inf_val.clear();
6732
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6733
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6734
0
                return -1;
6735
0
            }
6736
0
            txn->put(txn_inf_key, txn_inf_val);
6737
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6738
            // Put recycle txn key
6739
0
            std::string recyc_txn_key, recyc_txn_val;
6740
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6741
0
            RecycleTxnPB recycle_txn_pb;
6742
0
            recycle_txn_pb.set_creation_time(current_time);
6743
0
            recycle_txn_pb.set_label(txn_info.label());
6744
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6745
0
                LOG_WARNING("failed to serialize txn recycle info")
6746
0
                        .tag("key", hex(k))
6747
0
                        .tag("db_id", db_id)
6748
0
                        .tag("txn_id", txn_id);
6749
0
                return -1;
6750
0
            }
6751
0
            txn->put(recyc_txn_key, recyc_txn_val);
6752
            // Remove txn running key
6753
0
            txn->remove(k);
6754
0
            err = txn->commit();
6755
0
            if (err != TxnErrorCode::TXN_OK) {
6756
0
                LOG_WARNING("failed to commit txn err={}", err)
6757
0
                        .tag("key", hex(k))
6758
0
                        .tag("db_id", db_id)
6759
0
                        .tag("txn_id", txn_id);
6760
0
                return -1;
6761
0
            }
6762
0
            metrics_context.total_recycled_num = ++num_abort;
6763
0
            metrics_context.report();
6764
0
        }
6765
6766
0
        return 0;
6767
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6668
6
                                  this](std::string_view k, std::string_view v) -> int {
6669
6
        ++num_scanned;
6670
6671
6
        std::unique_ptr<Transaction> txn;
6672
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6673
6
        if (err != TxnErrorCode::TXN_OK) {
6674
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6675
0
            return -1;
6676
0
        }
6677
6
        std::string_view k1 = k;
6678
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6679
6
        k1.remove_prefix(1); // Remove key space
6680
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6681
6
        if (decode_key(&k1, &out) != 0) {
6682
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6683
0
            return -1;
6684
0
        }
6685
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6686
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6687
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6688
        // Update txn_info
6689
6
        std::string txn_inf_key, txn_inf_val;
6690
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6691
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6692
6
        if (err != TxnErrorCode::TXN_OK) {
6693
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6694
0
            return -1;
6695
0
        }
6696
6
        TxnInfoPB txn_info;
6697
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6698
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6699
0
            return -1;
6700
0
        }
6701
6702
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6703
0
            txn.reset();
6704
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6705
0
            std::shared_ptr<TxnLazyCommitTask> task =
6706
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6707
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6708
0
            if (ret.first != MetaServiceCode::OK) {
6709
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6710
0
                             << "msg=" << ret.second;
6711
0
                return -1;
6712
0
            }
6713
0
            ++num_advance;
6714
0
            return 0;
6715
6
        } else {
6716
6
            TxnRunningPB txn_running_pb;
6717
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6718
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6719
0
                return -1;
6720
0
            }
6721
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6722
4
                return 0;
6723
4
            }
6724
2
            ++num_timeout;
6725
6726
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6727
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6728
2
            txn_info.set_finish_time(current_time);
6729
2
            txn_info.set_reason("timeout");
6730
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6731
2
            txn_inf_val.clear();
6732
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6733
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6734
0
                return -1;
6735
0
            }
6736
2
            txn->put(txn_inf_key, txn_inf_val);
6737
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6738
            // Put recycle txn key
6739
2
            std::string recyc_txn_key, recyc_txn_val;
6740
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6741
2
            RecycleTxnPB recycle_txn_pb;
6742
2
            recycle_txn_pb.set_creation_time(current_time);
6743
2
            recycle_txn_pb.set_label(txn_info.label());
6744
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6745
0
                LOG_WARNING("failed to serialize txn recycle info")
6746
0
                        .tag("key", hex(k))
6747
0
                        .tag("db_id", db_id)
6748
0
                        .tag("txn_id", txn_id);
6749
0
                return -1;
6750
0
            }
6751
2
            txn->put(recyc_txn_key, recyc_txn_val);
6752
            // Remove txn running key
6753
2
            txn->remove(k);
6754
2
            err = txn->commit();
6755
2
            if (err != TxnErrorCode::TXN_OK) {
6756
0
                LOG_WARNING("failed to commit txn err={}", err)
6757
0
                        .tag("key", hex(k))
6758
0
                        .tag("db_id", db_id)
6759
0
                        .tag("txn_id", txn_id);
6760
0
                return -1;
6761
0
            }
6762
2
            metrics_context.total_recycled_num = ++num_abort;
6763
2
            metrics_context.report();
6764
2
        }
6765
6766
2
        return 0;
6767
6
    };
6768
6769
19
    if (config::enable_recycler_stats_metrics) {
6770
0
        scan_and_statistics_abort_timeout_txn();
6771
0
    }
6772
    // recycle_func and loop_done for scan and recycle
6773
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6774
19
                            std::move(handle_txn_running_kv));
6775
19
}
6776
6777
22
int InstanceRecycler::recycle_expired_txn_label() {
6778
22
    const std::string task_name = "recycle_expired_txn_label";
6779
22
    int64_t num_scanned = 0;
6780
22
    int64_t num_expired = 0;
6781
22
    std::atomic_long num_recycled = 0;
6782
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6783
22
    int ret = 0;
6784
6785
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6786
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6787
22
    std::string begin_recycle_txn_key;
6788
22
    std::string end_recycle_txn_key;
6789
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6790
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6791
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
6792
6793
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6794
6795
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6796
22
    register_recycle_task(task_name, start_time);
6797
22
    DORIS_CLOUD_DEFER {
6798
22
        unregister_recycle_task(task_name);
6799
22
        int64_t cost =
6800
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6801
22
        metrics_context.finish_report();
6802
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6803
22
                .tag("instance_id", instance_id_)
6804
22
                .tag("num_scanned", num_scanned)
6805
22
                .tag("num_expired", num_expired)
6806
22
                .tag("num_recycled", num_recycled);
6807
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6797
1
    DORIS_CLOUD_DEFER {
6798
1
        unregister_recycle_task(task_name);
6799
1
        int64_t cost =
6800
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6801
1
        metrics_context.finish_report();
6802
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6803
1
                .tag("instance_id", instance_id_)
6804
1
                .tag("num_scanned", num_scanned)
6805
1
                .tag("num_expired", num_expired)
6806
1
                .tag("num_recycled", num_recycled);
6807
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6797
21
    DORIS_CLOUD_DEFER {
6798
21
        unregister_recycle_task(task_name);
6799
21
        int64_t cost =
6800
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6801
21
        metrics_context.finish_report();
6802
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6803
21
                .tag("instance_id", instance_id_)
6804
21
                .tag("num_scanned", num_scanned)
6805
21
                .tag("num_expired", num_expired)
6806
21
                .tag("num_recycled", num_recycled);
6807
21
    };
6808
6809
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6810
6811
22
    SyncExecutor<int> concurrent_delete_executor(
6812
22
            _thread_pool_group.s3_producer_pool,
6813
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6814
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6814
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6814
38.0k
            [](const int& ret) { return ret != 0; });
6815
6816
22
    int64_t current_time_ms =
6817
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6818
6819
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6820
50.0k
        ++num_scanned;
6821
50.0k
        RecycleTxnPB recycle_txn_pb;
6822
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6823
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6824
0
            return -1;
6825
0
        }
6826
50.0k
        if ((config::force_immediate_recycle) ||
6827
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6828
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6829
50.0k
             current_time_ms)) {
6830
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6831
38.0k
            num_expired++;
6832
6833
38.0k
            std::string_view k1 = k;
6834
38.0k
            k1.remove_prefix(1); // Remove key space
6835
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6836
38.0k
            if (decode_key(&k1, &out) != 0) {
6837
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6838
0
                return -1;
6839
0
            }
6840
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6841
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6842
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6843
38.0k
        }
6844
50.0k
        return 0;
6845
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6819
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6820
1
        ++num_scanned;
6821
1
        RecycleTxnPB recycle_txn_pb;
6822
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6823
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6824
0
            return -1;
6825
0
        }
6826
1
        if ((config::force_immediate_recycle) ||
6827
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6828
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6829
1
             current_time_ms)) {
6830
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6831
1
            num_expired++;
6832
6833
1
            std::string_view k1 = k;
6834
1
            k1.remove_prefix(1); // Remove key space
6835
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6836
1
            if (decode_key(&k1, &out) != 0) {
6837
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6838
0
                return -1;
6839
0
            }
6840
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6841
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6842
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6843
1
        }
6844
1
        return 0;
6845
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6819
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6820
50.0k
        ++num_scanned;
6821
50.0k
        RecycleTxnPB recycle_txn_pb;
6822
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6823
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6824
0
            return -1;
6825
0
        }
6826
50.0k
        if ((config::force_immediate_recycle) ||
6827
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6828
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6829
50.0k
             current_time_ms)) {
6830
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6831
38.0k
            num_expired++;
6832
6833
38.0k
            std::string_view k1 = k;
6834
38.0k
            k1.remove_prefix(1); // Remove key space
6835
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6836
38.0k
            if (decode_key(&k1, &out) != 0) {
6837
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
6838
0
                return -1;
6839
0
            }
6840
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6841
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
6842
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
6843
38.0k
        }
6844
50.0k
        return 0;
6845
50.0k
    };
6846
6847
    // int 0 for success, 1 for conflict, -1 for error
6848
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6849
38.0k
        std::string_view k1 = k;
6850
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6851
38.0k
        k1.remove_prefix(1); // Remove key space
6852
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6853
38.0k
        int ret = decode_key(&k1, &out);
6854
38.0k
        if (ret != 0) {
6855
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6856
0
            return -1;
6857
0
        }
6858
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6859
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6860
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6861
38.0k
        std::unique_ptr<Transaction> txn;
6862
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
        // Remove txn index kv
6868
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6869
38.0k
        txn->remove(index_key);
6870
        // Remove txn info kv
6871
38.0k
        std::string info_key, info_val;
6872
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6873
38.0k
        err = txn->get(info_key, &info_val);
6874
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6875
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6876
0
            return -1;
6877
0
        }
6878
38.0k
        TxnInfoPB txn_info;
6879
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6880
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6881
0
            return -1;
6882
0
        }
6883
38.0k
        txn->remove(info_key);
6884
        // Remove sub txn index kvs
6885
38.0k
        std::vector<std::string> sub_txn_index_keys;
6886
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6887
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6888
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6889
38.0k
        }
6890
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6891
37.9k
            txn->remove(sub_txn_index_key);
6892
37.9k
        }
6893
        // Update txn label
6894
38.0k
        std::string label_key, label_val;
6895
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6896
38.0k
        err = txn->get(label_key, &label_val);
6897
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6898
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6899
0
                         << " err=" << err;
6900
0
            return -1;
6901
0
        }
6902
38.0k
        TxnLabelPB txn_label;
6903
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6904
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6905
0
            return -1;
6906
0
        }
6907
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6908
38.0k
        if (it != txn_label.txn_ids().end()) {
6909
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6910
38.0k
        }
6911
38.0k
        if (txn_label.txn_ids().empty()) {
6912
38.0k
            txn->remove(label_key);
6913
38.0k
            TEST_SYNC_POINT_CALLBACK(
6914
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6915
38.0k
        } else {
6916
11
            if (!txn_label.SerializeToString(&label_val)) {
6917
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6918
0
                return -1;
6919
0
            }
6920
11
            TEST_SYNC_POINT_CALLBACK(
6921
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6922
11
            txn->atomic_set_ver_value(label_key, label_val);
6923
11
            TEST_SYNC_POINT_CALLBACK(
6924
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6925
11
        }
6926
        // Remove recycle txn kv
6927
38.0k
        txn->remove(k);
6928
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6929
38.0k
        err = txn->commit();
6930
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6931
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6932
4
                TEST_SYNC_POINT_CALLBACK(
6933
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6934
                // log the txn_id and label
6935
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6936
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6937
4
                             << " txn_label=" << txn_info.label();
6938
4
                return 1;
6939
4
            }
6940
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6941
0
            return -1;
6942
4
        }
6943
38.0k
        ++num_recycled;
6944
6945
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6946
38.0k
        return 0;
6947
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6848
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6849
1
        std::string_view k1 = k;
6850
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6851
1
        k1.remove_prefix(1); // Remove key space
6852
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6853
1
        int ret = decode_key(&k1, &out);
6854
1
        if (ret != 0) {
6855
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6856
0
            return -1;
6857
0
        }
6858
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6859
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6860
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6861
1
        std::unique_ptr<Transaction> txn;
6862
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
1
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
        // Remove txn index kv
6868
1
        auto index_key = txn_index_key({instance_id_, txn_id});
6869
1
        txn->remove(index_key);
6870
        // Remove txn info kv
6871
1
        std::string info_key, info_val;
6872
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6873
1
        err = txn->get(info_key, &info_val);
6874
1
        if (err != TxnErrorCode::TXN_OK) {
6875
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6876
0
            return -1;
6877
0
        }
6878
1
        TxnInfoPB txn_info;
6879
1
        if (!txn_info.ParseFromString(info_val)) {
6880
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6881
0
            return -1;
6882
0
        }
6883
1
        txn->remove(info_key);
6884
        // Remove sub txn index kvs
6885
1
        std::vector<std::string> sub_txn_index_keys;
6886
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6887
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6888
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
6889
0
        }
6890
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6891
0
            txn->remove(sub_txn_index_key);
6892
0
        }
6893
        // Update txn label
6894
1
        std::string label_key, label_val;
6895
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6896
1
        err = txn->get(label_key, &label_val);
6897
1
        if (err != TxnErrorCode::TXN_OK) {
6898
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6899
0
                         << " err=" << err;
6900
0
            return -1;
6901
0
        }
6902
1
        TxnLabelPB txn_label;
6903
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6904
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6905
0
            return -1;
6906
0
        }
6907
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6908
1
        if (it != txn_label.txn_ids().end()) {
6909
1
            txn_label.mutable_txn_ids()->erase(it);
6910
1
        }
6911
1
        if (txn_label.txn_ids().empty()) {
6912
1
            txn->remove(label_key);
6913
1
            TEST_SYNC_POINT_CALLBACK(
6914
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6915
1
        } else {
6916
0
            if (!txn_label.SerializeToString(&label_val)) {
6917
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6918
0
                return -1;
6919
0
            }
6920
0
            TEST_SYNC_POINT_CALLBACK(
6921
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6922
0
            txn->atomic_set_ver_value(label_key, label_val);
6923
0
            TEST_SYNC_POINT_CALLBACK(
6924
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6925
0
        }
6926
        // Remove recycle txn kv
6927
1
        txn->remove(k);
6928
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6929
1
        err = txn->commit();
6930
1
        if (err != TxnErrorCode::TXN_OK) {
6931
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
6932
0
                TEST_SYNC_POINT_CALLBACK(
6933
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6934
                // log the txn_id and label
6935
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6936
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6937
0
                             << " txn_label=" << txn_info.label();
6938
0
                return 1;
6939
0
            }
6940
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6941
0
            return -1;
6942
0
        }
6943
1
        ++num_recycled;
6944
6945
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6946
1
        return 0;
6947
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
6848
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
6849
38.0k
        std::string_view k1 = k;
6850
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
6851
38.0k
        k1.remove_prefix(1); // Remove key space
6852
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6853
38.0k
        int ret = decode_key(&k1, &out);
6854
38.0k
        if (ret != 0) {
6855
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
6856
0
            return -1;
6857
0
        }
6858
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6859
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6860
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6861
38.0k
        std::unique_ptr<Transaction> txn;
6862
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6863
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6864
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6865
0
            return -1;
6866
0
        }
6867
        // Remove txn index kv
6868
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
6869
38.0k
        txn->remove(index_key);
6870
        // Remove txn info kv
6871
38.0k
        std::string info_key, info_val;
6872
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
6873
38.0k
        err = txn->get(info_key, &info_val);
6874
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6875
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
6876
0
            return -1;
6877
0
        }
6878
38.0k
        TxnInfoPB txn_info;
6879
38.0k
        if (!txn_info.ParseFromString(info_val)) {
6880
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
6881
0
            return -1;
6882
0
        }
6883
38.0k
        txn->remove(info_key);
6884
        // Remove sub txn index kvs
6885
38.0k
        std::vector<std::string> sub_txn_index_keys;
6886
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
6887
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
6888
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
6889
38.0k
        }
6890
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
6891
37.9k
            txn->remove(sub_txn_index_key);
6892
37.9k
        }
6893
        // Update txn label
6894
38.0k
        std::string label_key, label_val;
6895
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
6896
38.0k
        err = txn->get(label_key, &label_val);
6897
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6898
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
6899
0
                         << " err=" << err;
6900
0
            return -1;
6901
0
        }
6902
38.0k
        TxnLabelPB txn_label;
6903
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
6904
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
6905
0
            return -1;
6906
0
        }
6907
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
6908
38.0k
        if (it != txn_label.txn_ids().end()) {
6909
38.0k
            txn_label.mutable_txn_ids()->erase(it);
6910
38.0k
        }
6911
38.0k
        if (txn_label.txn_ids().empty()) {
6912
38.0k
            txn->remove(label_key);
6913
38.0k
            TEST_SYNC_POINT_CALLBACK(
6914
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
6915
38.0k
        } else {
6916
11
            if (!txn_label.SerializeToString(&label_val)) {
6917
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
6918
0
                return -1;
6919
0
            }
6920
11
            TEST_SYNC_POINT_CALLBACK(
6921
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
6922
11
            txn->atomic_set_ver_value(label_key, label_val);
6923
11
            TEST_SYNC_POINT_CALLBACK(
6924
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
6925
11
        }
6926
        // Remove recycle txn kv
6927
38.0k
        txn->remove(k);
6928
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
6929
38.0k
        err = txn->commit();
6930
38.0k
        if (err != TxnErrorCode::TXN_OK) {
6931
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
6932
4
                TEST_SYNC_POINT_CALLBACK(
6933
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
6934
                // log the txn_id and label
6935
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
6936
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
6937
4
                             << " txn_label=" << txn_info.label();
6938
4
                return 1;
6939
4
            }
6940
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
6941
0
            return -1;
6942
4
        }
6943
38.0k
        ++num_recycled;
6944
6945
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
6946
38.0k
        return 0;
6947
38.0k
    };
6948
6949
22
    auto loop_done = [&]() -> int {
6950
15
        DORIS_CLOUD_DEFER {
6951
15
            recycle_txn_keys_by_label.clear();
6952
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6950
1
        DORIS_CLOUD_DEFER {
6951
1
            recycle_txn_keys_by_label.clear();
6952
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
6950
14
        DORIS_CLOUD_DEFER {
6951
14
            recycle_txn_keys_by_label.clear();
6952
14
        };
6953
15
        TEST_SYNC_POINT_CALLBACK(
6954
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6955
15
                &recycle_txn_keys_by_label);
6956
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6957
38.0k
            int ret = delete_recycle_txn_kv(k);
6958
38.0k
            TEST_SYNC_POINT_CALLBACK(
6959
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6960
38.0k
                    &ret);
6961
38.0k
            if (ret == 1) {
6962
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6963
4
                for (int i = 1; i <= max_retry; ++i) {
6964
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6965
3
                    ret = delete_recycle_txn_kv(k);
6966
3
                    TEST_SYNC_POINT_CALLBACK(
6967
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6968
3
                            "error",
6969
3
                            &ret);
6970
3
                    if (ret != 1) {
6971
1
                        break;
6972
1
                    }
6973
                    // random sleep 0-100 ms to retry
6974
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6975
2
                }
6976
2
            }
6977
38.0k
            return ret;
6978
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6956
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6957
1
            int ret = delete_recycle_txn_kv(k);
6958
1
            TEST_SYNC_POINT_CALLBACK(
6959
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6960
1
                    &ret);
6961
1
            if (ret == 1) {
6962
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6963
0
                for (int i = 1; i <= max_retry; ++i) {
6964
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6965
0
                    ret = delete_recycle_txn_kv(k);
6966
0
                    TEST_SYNC_POINT_CALLBACK(
6967
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6968
0
                            "error",
6969
0
                            &ret);
6970
0
                    if (ret != 1) {
6971
0
                        break;
6972
0
                    }
6973
                    // random sleep 0-100 ms to retry
6974
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6975
0
                }
6976
0
            }
6977
1
            return ret;
6978
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
6956
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6957
38.0k
            int ret = delete_recycle_txn_kv(k);
6958
38.0k
            TEST_SYNC_POINT_CALLBACK(
6959
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6960
38.0k
                    &ret);
6961
38.0k
            if (ret == 1) {
6962
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6963
4
                for (int i = 1; i <= max_retry; ++i) {
6964
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6965
3
                    ret = delete_recycle_txn_kv(k);
6966
3
                    TEST_SYNC_POINT_CALLBACK(
6967
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6968
3
                            "error",
6969
3
                            &ret);
6970
3
                    if (ret != 1) {
6971
1
                        break;
6972
1
                    }
6973
                    // random sleep 0-100 ms to retry
6974
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6975
2
                }
6976
2
            }
6977
38.0k
            return ret;
6978
38.0k
        };
6979
6980
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6981
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6982
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6983
0
                           << " txn_count=" << txn_keys.size();
6984
38.0k
                for (const auto& k : txn_keys) {
6985
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6986
38.0k
                    if (ret != 0) {
6987
2
                        LOG_WARNING("failed to delete recycle txn kv")
6988
2
                                .tag("instance id", instance_id_)
6989
2
                                .tag("key", hex(k))
6990
2
                                .tag("label_key", hex(label_key));
6991
2
                        return -1;
6992
2
                    }
6993
38.0k
                }
6994
38.0k
                return 0;
6995
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6981
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6982
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6983
0
                           << " txn_count=" << txn_keys.size();
6984
1
                for (const auto& k : txn_keys) {
6985
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
6986
1
                    if (ret != 0) {
6987
0
                        LOG_WARNING("failed to delete recycle txn kv")
6988
0
                                .tag("instance id", instance_id_)
6989
0
                                .tag("key", hex(k))
6990
0
                                .tag("label_key", hex(label_key));
6991
0
                        return -1;
6992
0
                    }
6993
1
                }
6994
1
                return 0;
6995
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
6981
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6982
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6983
0
                           << " txn_count=" << txn_keys.size();
6984
38.0k
                for (const auto& k : txn_keys) {
6985
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6986
38.0k
                    if (ret != 0) {
6987
2
                        LOG_WARNING("failed to delete recycle txn kv")
6988
2
                                .tag("instance id", instance_id_)
6989
2
                                .tag("key", hex(k))
6990
2
                                .tag("label_key", hex(label_key));
6991
2
                        return -1;
6992
2
                    }
6993
38.0k
                }
6994
38.0k
                return 0;
6995
38.0k
            });
6996
38.0k
        }
6997
15
        bool finished = true;
6998
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6999
38.0k
        for (int r : rets) {
7000
38.0k
            if (r != 0) {
7001
2
                ret = -1;
7002
2
            }
7003
38.0k
        }
7004
7005
15
        ret = finished ? ret : -1;
7006
7007
        // Update metrics after all concurrent tasks completed
7008
15
        metrics_context.total_recycled_num = num_recycled.load();
7009
15
        metrics_context.report();
7010
7011
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7012
7013
15
        if (ret != 0) {
7014
6
            LOG_WARNING("recycle txn kv ret!=0")
7015
6
                    .tag("finished", finished)
7016
6
                    .tag("ret", ret)
7017
6
                    .tag("instance_id", instance_id_);
7018
6
            return ret;
7019
6
        }
7020
9
        return ret;
7021
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6949
1
    auto loop_done = [&]() -> int {
6950
1
        DORIS_CLOUD_DEFER {
6951
1
            recycle_txn_keys_by_label.clear();
6952
1
        };
6953
1
        TEST_SYNC_POINT_CALLBACK(
6954
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6955
1
                &recycle_txn_keys_by_label);
6956
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6957
1
            int ret = delete_recycle_txn_kv(k);
6958
1
            TEST_SYNC_POINT_CALLBACK(
6959
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6960
1
                    &ret);
6961
1
            if (ret == 1) {
6962
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6963
1
                for (int i = 1; i <= max_retry; ++i) {
6964
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6965
1
                    ret = delete_recycle_txn_kv(k);
6966
1
                    TEST_SYNC_POINT_CALLBACK(
6967
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6968
1
                            "error",
6969
1
                            &ret);
6970
1
                    if (ret != 1) {
6971
1
                        break;
6972
1
                    }
6973
                    // random sleep 0-100 ms to retry
6974
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6975
1
                }
6976
1
            }
6977
1
            return ret;
6978
1
        };
6979
6980
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6981
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6982
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6983
1
                           << " txn_count=" << txn_keys.size();
6984
1
                for (const auto& k : txn_keys) {
6985
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
6986
1
                    if (ret != 0) {
6987
1
                        LOG_WARNING("failed to delete recycle txn kv")
6988
1
                                .tag("instance id", instance_id_)
6989
1
                                .tag("key", hex(k))
6990
1
                                .tag("label_key", hex(label_key));
6991
1
                        return -1;
6992
1
                    }
6993
1
                }
6994
1
                return 0;
6995
1
            });
6996
1
        }
6997
1
        bool finished = true;
6998
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6999
1
        for (int r : rets) {
7000
1
            if (r != 0) {
7001
0
                ret = -1;
7002
0
            }
7003
1
        }
7004
7005
1
        ret = finished ? ret : -1;
7006
7007
        // Update metrics after all concurrent tasks completed
7008
1
        metrics_context.total_recycled_num = num_recycled.load();
7009
1
        metrics_context.report();
7010
7011
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7012
7013
1
        if (ret != 0) {
7014
0
            LOG_WARNING("recycle txn kv ret!=0")
7015
0
                    .tag("finished", finished)
7016
0
                    .tag("ret", ret)
7017
0
                    .tag("instance_id", instance_id_);
7018
0
            return ret;
7019
0
        }
7020
1
        return ret;
7021
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
6949
14
    auto loop_done = [&]() -> int {
6950
14
        DORIS_CLOUD_DEFER {
6951
14
            recycle_txn_keys_by_label.clear();
6952
14
        };
6953
14
        TEST_SYNC_POINT_CALLBACK(
6954
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
6955
14
                &recycle_txn_keys_by_label);
6956
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
6957
14
            int ret = delete_recycle_txn_kv(k);
6958
14
            TEST_SYNC_POINT_CALLBACK(
6959
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
6960
14
                    &ret);
6961
14
            if (ret == 1) {
6962
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
6963
14
                for (int i = 1; i <= max_retry; ++i) {
6964
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
6965
14
                    ret = delete_recycle_txn_kv(k);
6966
14
                    TEST_SYNC_POINT_CALLBACK(
6967
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
6968
14
                            "error",
6969
14
                            &ret);
6970
14
                    if (ret != 1) {
6971
14
                        break;
6972
14
                    }
6973
                    // random sleep 0-100 ms to retry
6974
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
6975
14
                }
6976
14
            }
6977
14
            return ret;
6978
14
        };
6979
6980
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
6981
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
6982
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
6983
38.0k
                           << " txn_count=" << txn_keys.size();
6984
38.0k
                for (const auto& k : txn_keys) {
6985
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
6986
38.0k
                    if (ret != 0) {
6987
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
6988
38.0k
                                .tag("instance id", instance_id_)
6989
38.0k
                                .tag("key", hex(k))
6990
38.0k
                                .tag("label_key", hex(label_key));
6991
38.0k
                        return -1;
6992
38.0k
                    }
6993
38.0k
                }
6994
38.0k
                return 0;
6995
38.0k
            });
6996
38.0k
        }
6997
14
        bool finished = true;
6998
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
6999
38.0k
        for (int r : rets) {
7000
38.0k
            if (r != 0) {
7001
2
                ret = -1;
7002
2
            }
7003
38.0k
        }
7004
7005
14
        ret = finished ? ret : -1;
7006
7007
        // Update metrics after all concurrent tasks completed
7008
14
        metrics_context.total_recycled_num = num_recycled.load();
7009
14
        metrics_context.report();
7010
7011
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7012
7013
14
        if (ret != 0) {
7014
6
            LOG_WARNING("recycle txn kv ret!=0")
7015
6
                    .tag("finished", finished)
7016
6
                    .tag("ret", ret)
7017
6
                    .tag("instance_id", instance_id_);
7018
6
            return ret;
7019
6
        }
7020
8
        return ret;
7021
14
    };
7022
7023
22
    if (config::enable_recycler_stats_metrics) {
7024
0
        scan_and_statistics_expired_txn_label();
7025
0
    }
7026
    // recycle_func and loop_done for scan and recycle
7027
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7028
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7029
22
}
7030
7031
struct CopyJobIdTuple {
7032
    std::string instance_id;
7033
    std::string stage_id;
7034
    long table_id;
7035
    std::string copy_id;
7036
    std::string stage_path;
7037
};
7038
struct BatchObjStoreAccessor {
7039
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7040
                          TxnKv* txn_kv)
7041
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7042
3
    ~BatchObjStoreAccessor() {
7043
3
        if (!paths_.empty()) {
7044
3
            consume();
7045
3
        }
7046
3
    }
7047
7048
    /**
7049
    * To implicitely do batch work and submit the batch delete task to s3
7050
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7051
    *
7052
    * @param copy_job The protubuf struct consists of the copy job files.
7053
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7054
    *            it would last until we finish the delete task, here we need pass one string value
7055
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7056
    */
7057
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7058
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7059
5
        auto& file_keys = copy_file_keys_[key];
7060
5
        file_keys.log_trace =
7061
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7062
5
                            instance_id, stage_id, table_id, copy_id, path);
7063
5
        std::string_view log_trace = file_keys.log_trace;
7064
2.03k
        for (const auto& file : copy_job.object_files()) {
7065
2.03k
            auto relative_path = file.relative_path();
7066
2.03k
            paths_.push_back(relative_path);
7067
2.03k
            file_keys.keys.push_back(copy_file_key(
7068
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7069
2.03k
            LOG_INFO(log_trace)
7070
2.03k
                    .tag("relative_path", relative_path)
7071
2.03k
                    .tag("batch_count", batch_count_);
7072
2.03k
        }
7073
5
        LOG_INFO(log_trace)
7074
5
                .tag("objects_num", copy_job.object_files().size())
7075
5
                .tag("batch_count", batch_count_);
7076
        // 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
7077
        // recommend using delete objects when objects num is less than 10)
7078
5
        if (paths_.size() < 1000) {
7079
3
            return;
7080
3
        }
7081
2
        consume();
7082
2
    }
7083
7084
private:
7085
5
    void consume() {
7086
5
        DORIS_CLOUD_DEFER {
7087
5
            paths_.clear();
7088
5
            copy_file_keys_.clear();
7089
5
            batch_count_++;
7090
7091
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7092
5
                        batch_count_);
7093
5
        };
7094
7095
5
        StopWatch sw;
7096
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7097
5
        if (0 != accessor_->delete_files(paths_)) {
7098
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7099
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7100
2
            return;
7101
2
        }
7102
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7103
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7104
        // delete fdb's keys
7105
3
        for (auto& file_keys : copy_file_keys_) {
7106
3
            auto& [log_trace, keys] = file_keys.second;
7107
3
            std::unique_ptr<Transaction> txn;
7108
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7109
0
                LOG(WARNING) << "failed to create txn";
7110
0
                continue;
7111
0
            }
7112
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7113
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7114
            // limited, should not cause the txn commit failed.
7115
1.02k
            for (const auto& key : keys) {
7116
1.02k
                txn->remove(key);
7117
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7118
1.02k
            }
7119
3
            txn->remove(file_keys.first);
7120
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7121
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7122
0
                continue;
7123
0
            }
7124
3
        }
7125
3
    }
7126
    std::shared_ptr<StorageVaultAccessor> accessor_;
7127
    // the path of the s3 files to be deleted
7128
    std::vector<std::string> paths_;
7129
    struct CopyFiles {
7130
        std::string log_trace;
7131
        std::vector<std::string> keys;
7132
    };
7133
    // pair<std::string, std::vector<std::string>>
7134
    // first: instance_id_ stage_id table_id query_id
7135
    // second: keys to be deleted
7136
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7137
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7138
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7139
    // which can together uniquely identifies different tasks for tracing log
7140
    uint64_t& batch_count_;
7141
    TxnKv* txn_kv_;
7142
};
7143
7144
13
int InstanceRecycler::recycle_copy_jobs() {
7145
13
    int64_t num_scanned = 0;
7146
13
    int64_t num_finished = 0;
7147
13
    int64_t num_expired = 0;
7148
13
    int64_t num_recycled = 0;
7149
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7150
13
    uint64_t batch_count = 0;
7151
13
    const std::string task_name = "recycle_copy_jobs";
7152
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7153
7154
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7155
7156
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7157
13
    register_recycle_task(task_name, start_time);
7158
7159
13
    DORIS_CLOUD_DEFER {
7160
13
        unregister_recycle_task(task_name);
7161
13
        int64_t cost =
7162
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7163
13
        metrics_context.finish_report();
7164
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7165
13
                .tag("instance_id", instance_id_)
7166
13
                .tag("num_scanned", num_scanned)
7167
13
                .tag("num_finished", num_finished)
7168
13
                .tag("num_expired", num_expired)
7169
13
                .tag("num_recycled", num_recycled);
7170
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7159
13
    DORIS_CLOUD_DEFER {
7160
13
        unregister_recycle_task(task_name);
7161
13
        int64_t cost =
7162
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7163
13
        metrics_context.finish_report();
7164
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7165
13
                .tag("instance_id", instance_id_)
7166
13
                .tag("num_scanned", num_scanned)
7167
13
                .tag("num_finished", num_finished)
7168
13
                .tag("num_expired", num_expired)
7169
13
                .tag("num_recycled", num_recycled);
7170
13
    };
7171
7172
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7173
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7174
13
    std::string key0;
7175
13
    std::string key1;
7176
13
    copy_job_key(key_info0, &key0);
7177
13
    copy_job_key(key_info1, &key1);
7178
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7179
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7180
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7181
16
                         this](std::string_view k, std::string_view v) -> int {
7182
16
        ++num_scanned;
7183
16
        CopyJobPB copy_job;
7184
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7185
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7186
0
            return -1;
7187
0
        }
7188
7189
        // decode copy job key
7190
16
        auto k1 = k;
7191
16
        k1.remove_prefix(1);
7192
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7193
16
        decode_key(&k1, &out);
7194
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7195
        // -> CopyJobPB
7196
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7197
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7198
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7199
7200
16
        bool check_storage = true;
7201
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7202
12
            ++num_finished;
7203
7204
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7205
7
                auto it = stage_accessor_map.find(stage_id);
7206
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7207
7
                std::string_view path;
7208
7
                if (it != stage_accessor_map.end()) {
7209
2
                    accessor = it->second;
7210
5
                } else {
7211
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7212
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7213
5
                                                      &inner_accessor);
7214
5
                    if (ret < 0) { // error
7215
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7216
0
                        return -1;
7217
5
                    } else if (ret == 0) {
7218
3
                        path = inner_accessor->uri();
7219
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7220
3
                                inner_accessor, batch_count, txn_kv_.get());
7221
3
                        stage_accessor_map.emplace(stage_id, accessor);
7222
3
                    } else { // stage not found, skip check storage
7223
2
                        check_storage = false;
7224
2
                    }
7225
5
                }
7226
7
                if (check_storage) {
7227
                    // TODO delete objects with key and etag is not supported
7228
5
                    accessor->add(std::move(copy_job), std::string(k),
7229
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7230
5
                    return 0;
7231
5
                }
7232
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7233
5
                int64_t current_time =
7234
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7235
5
                if (copy_job.finish_time_ms() > 0) {
7236
2
                    if (!config::force_immediate_recycle &&
7237
2
                        current_time < copy_job.finish_time_ms() +
7238
2
                                               config::copy_job_max_retention_second * 1000) {
7239
1
                        return 0;
7240
1
                    }
7241
3
                } else {
7242
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7243
3
                    if (!config::force_immediate_recycle &&
7244
3
                        current_time < copy_job.start_time_ms() +
7245
3
                                               config::copy_job_max_retention_second * 1000) {
7246
1
                        return 0;
7247
1
                    }
7248
3
                }
7249
5
            }
7250
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7251
4
            int64_t current_time =
7252
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7253
            // if copy job is timeout: delete all copy file kvs and copy job kv
7254
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7255
2
                return 0;
7256
2
            }
7257
2
            ++num_expired;
7258
2
        }
7259
7260
        // delete all copy files
7261
7
        std::vector<std::string> copy_file_keys;
7262
70
        for (auto& file : copy_job.object_files()) {
7263
70
            copy_file_keys.push_back(copy_file_key(
7264
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7265
70
        }
7266
7
        std::unique_ptr<Transaction> txn;
7267
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7268
0
            LOG(WARNING) << "failed to create txn";
7269
0
            return -1;
7270
0
        }
7271
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7272
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7273
        // limited, should not cause the txn commit failed.
7274
70
        for (const auto& key : copy_file_keys) {
7275
70
            txn->remove(key);
7276
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7277
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7278
70
                      << ", query_id=" << copy_id;
7279
70
        }
7280
7
        txn->remove(k);
7281
7
        TxnErrorCode err = txn->commit();
7282
7
        if (err != TxnErrorCode::TXN_OK) {
7283
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7284
0
            return -1;
7285
0
        }
7286
7287
7
        metrics_context.total_recycled_num = ++num_recycled;
7288
7
        metrics_context.report();
7289
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7290
7
        return 0;
7291
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
7181
16
                         this](std::string_view k, std::string_view v) -> int {
7182
16
        ++num_scanned;
7183
16
        CopyJobPB copy_job;
7184
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7185
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7186
0
            return -1;
7187
0
        }
7188
7189
        // decode copy job key
7190
16
        auto k1 = k;
7191
16
        k1.remove_prefix(1);
7192
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7193
16
        decode_key(&k1, &out);
7194
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7195
        // -> CopyJobPB
7196
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7197
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7198
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7199
7200
16
        bool check_storage = true;
7201
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7202
12
            ++num_finished;
7203
7204
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7205
7
                auto it = stage_accessor_map.find(stage_id);
7206
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7207
7
                std::string_view path;
7208
7
                if (it != stage_accessor_map.end()) {
7209
2
                    accessor = it->second;
7210
5
                } else {
7211
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7212
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7213
5
                                                      &inner_accessor);
7214
5
                    if (ret < 0) { // error
7215
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7216
0
                        return -1;
7217
5
                    } else if (ret == 0) {
7218
3
                        path = inner_accessor->uri();
7219
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7220
3
                                inner_accessor, batch_count, txn_kv_.get());
7221
3
                        stage_accessor_map.emplace(stage_id, accessor);
7222
3
                    } else { // stage not found, skip check storage
7223
2
                        check_storage = false;
7224
2
                    }
7225
5
                }
7226
7
                if (check_storage) {
7227
                    // TODO delete objects with key and etag is not supported
7228
5
                    accessor->add(std::move(copy_job), std::string(k),
7229
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7230
5
                    return 0;
7231
5
                }
7232
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7233
5
                int64_t current_time =
7234
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7235
5
                if (copy_job.finish_time_ms() > 0) {
7236
2
                    if (!config::force_immediate_recycle &&
7237
2
                        current_time < copy_job.finish_time_ms() +
7238
2
                                               config::copy_job_max_retention_second * 1000) {
7239
1
                        return 0;
7240
1
                    }
7241
3
                } else {
7242
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7243
3
                    if (!config::force_immediate_recycle &&
7244
3
                        current_time < copy_job.start_time_ms() +
7245
3
                                               config::copy_job_max_retention_second * 1000) {
7246
1
                        return 0;
7247
1
                    }
7248
3
                }
7249
5
            }
7250
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7251
4
            int64_t current_time =
7252
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7253
            // if copy job is timeout: delete all copy file kvs and copy job kv
7254
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7255
2
                return 0;
7256
2
            }
7257
2
            ++num_expired;
7258
2
        }
7259
7260
        // delete all copy files
7261
7
        std::vector<std::string> copy_file_keys;
7262
70
        for (auto& file : copy_job.object_files()) {
7263
70
            copy_file_keys.push_back(copy_file_key(
7264
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7265
70
        }
7266
7
        std::unique_ptr<Transaction> txn;
7267
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7268
0
            LOG(WARNING) << "failed to create txn";
7269
0
            return -1;
7270
0
        }
7271
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7272
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7273
        // limited, should not cause the txn commit failed.
7274
70
        for (const auto& key : copy_file_keys) {
7275
70
            txn->remove(key);
7276
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7277
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7278
70
                      << ", query_id=" << copy_id;
7279
70
        }
7280
7
        txn->remove(k);
7281
7
        TxnErrorCode err = txn->commit();
7282
7
        if (err != TxnErrorCode::TXN_OK) {
7283
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7284
0
            return -1;
7285
0
        }
7286
7287
7
        metrics_context.total_recycled_num = ++num_recycled;
7288
7
        metrics_context.report();
7289
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7290
7
        return 0;
7291
7
    };
7292
7293
13
    if (config::enable_recycler_stats_metrics) {
7294
0
        scan_and_statistics_copy_jobs();
7295
0
    }
7296
    // recycle_func and loop_done for scan and recycle
7297
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7298
13
}
7299
7300
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7301
                                             const StagePB::StageType& stage_type,
7302
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7303
5
#ifdef UNIT_TEST
7304
    // In unit test, external use the same accessor as the internal stage
7305
5
    auto it = accessor_map_.find(stage_id);
7306
5
    if (it != accessor_map_.end()) {
7307
3
        *accessor = it->second;
7308
3
    } else {
7309
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7310
2
        return 1;
7311
2
    }
7312
#else
7313
    // init s3 accessor and add to accessor map
7314
    auto stage_it =
7315
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7316
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7317
7318
    if (stage_it == instance_info_.stages().end()) {
7319
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7320
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7321
        return 1;
7322
    }
7323
7324
    const auto& object_store_info = stage_it->obj_info();
7325
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7326
7327
    S3Conf s3_conf;
7328
    if (stage_type == StagePB::EXTERNAL) {
7329
        if (stage_access_type == StagePB::AKSK) {
7330
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7331
            if (!conf) {
7332
                return -1;
7333
            }
7334
7335
            s3_conf = std::move(*conf);
7336
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7337
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7338
            if (!conf) {
7339
                return -1;
7340
            }
7341
7342
            s3_conf = std::move(*conf);
7343
            if (instance_info_.ram_user().has_encryption_info()) {
7344
                AkSkPair plain_ak_sk_pair;
7345
                int ret = decrypt_ak_sk_helper(
7346
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7347
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7348
                if (ret != 0) {
7349
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7350
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7351
                    return -1;
7352
                }
7353
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7354
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7355
            } else {
7356
                s3_conf.ak = instance_info_.ram_user().ak();
7357
                s3_conf.sk = instance_info_.ram_user().sk();
7358
            }
7359
        } else {
7360
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7361
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7362
            return -1;
7363
        }
7364
    } else if (stage_type == StagePB::INTERNAL) {
7365
        int idx = stoi(object_store_info.id());
7366
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7367
            LOG(WARNING) << "invalid idx: " << idx;
7368
            return -1;
7369
        }
7370
7371
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7372
        auto conf = S3Conf::from_obj_store_info(old_obj);
7373
        if (!conf) {
7374
            return -1;
7375
        }
7376
7377
        s3_conf = std::move(*conf);
7378
        s3_conf.prefix = object_store_info.prefix();
7379
    } else {
7380
        LOG(WARNING) << "unknown stage type " << stage_type;
7381
        return -1;
7382
    }
7383
7384
    std::shared_ptr<S3Accessor> s3_accessor;
7385
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7386
    if (ret != 0) {
7387
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7388
        return -1;
7389
    }
7390
7391
    *accessor = std::move(s3_accessor);
7392
#endif
7393
3
    return 0;
7394
5
}
7395
7396
11
int InstanceRecycler::recycle_stage() {
7397
11
    int64_t num_scanned = 0;
7398
11
    int64_t num_recycled = 0;
7399
11
    const std::string task_name = "recycle_stage";
7400
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7401
7402
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7403
7404
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7405
11
    register_recycle_task(task_name, start_time);
7406
7407
11
    DORIS_CLOUD_DEFER {
7408
11
        unregister_recycle_task(task_name);
7409
11
        int64_t cost =
7410
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7411
11
        metrics_context.finish_report();
7412
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7413
11
                .tag("instance_id", instance_id_)
7414
11
                .tag("num_scanned", num_scanned)
7415
11
                .tag("num_recycled", num_recycled);
7416
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7407
11
    DORIS_CLOUD_DEFER {
7408
11
        unregister_recycle_task(task_name);
7409
11
        int64_t cost =
7410
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7411
11
        metrics_context.finish_report();
7412
        LOG_WARNING("recycle stage, cost={}s", cost)
7413
11
                .tag("instance_id", instance_id_)
7414
11
                .tag("num_scanned", num_scanned)
7415
11
                .tag("num_recycled", num_recycled);
7416
11
    };
7417
7418
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7419
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7420
11
    std::string key0 = recycle_stage_key(key_info0);
7421
11
    std::string key1 = recycle_stage_key(key_info1);
7422
7423
11
    std::vector<std::string_view> stage_keys;
7424
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7425
11
                         this](std::string_view k, std::string_view v) -> int {
7426
1
        ++num_scanned;
7427
1
        RecycleStagePB recycle_stage;
7428
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7429
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7430
0
            return -1;
7431
0
        }
7432
7433
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7434
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7435
0
            LOG(WARNING) << "invalid idx: " << idx;
7436
0
            return -1;
7437
0
        }
7438
7439
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7440
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7441
1
                [&] {
7442
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7443
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7444
1
                    if (!s3_conf) {
7445
1
                        return -1;
7446
1
                    }
7447
7448
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7449
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7450
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7451
1
                    if (ret != 0) {
7452
1
                        return -1;
7453
1
                    }
7454
7455
1
                    accessor = std::move(s3_accessor);
7456
1
                    return 0;
7457
1
                }(),
7458
1
                "recycle_stage:get_accessor", &accessor);
7459
7460
1
        if (ret != 0) {
7461
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7462
0
            return ret;
7463
0
        }
7464
7465
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7466
1
                .tag("instance_id", instance_id_)
7467
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7468
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7469
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7470
1
                .tag("obj_info_id", idx)
7471
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7472
1
        ret = accessor->delete_all();
7473
1
        if (ret != 0) {
7474
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7475
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7476
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7477
0
                         << ", ret=" << ret;
7478
0
            return -1;
7479
0
        }
7480
1
        metrics_context.total_recycled_num = ++num_recycled;
7481
1
        metrics_context.report();
7482
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7483
1
        stage_keys.push_back(k);
7484
1
        return 0;
7485
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7425
1
                         this](std::string_view k, std::string_view v) -> int {
7426
1
        ++num_scanned;
7427
1
        RecycleStagePB recycle_stage;
7428
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7429
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7430
0
            return -1;
7431
0
        }
7432
7433
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7434
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7435
0
            LOG(WARNING) << "invalid idx: " << idx;
7436
0
            return -1;
7437
0
        }
7438
7439
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7440
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7441
1
                [&] {
7442
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7443
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7444
1
                    if (!s3_conf) {
7445
1
                        return -1;
7446
1
                    }
7447
7448
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7449
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7450
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7451
1
                    if (ret != 0) {
7452
1
                        return -1;
7453
1
                    }
7454
7455
1
                    accessor = std::move(s3_accessor);
7456
1
                    return 0;
7457
1
                }(),
7458
1
                "recycle_stage:get_accessor", &accessor);
7459
7460
1
        if (ret != 0) {
7461
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7462
0
            return ret;
7463
0
        }
7464
7465
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7466
1
                .tag("instance_id", instance_id_)
7467
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7468
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7469
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7470
1
                .tag("obj_info_id", idx)
7471
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7472
1
        ret = accessor->delete_all();
7473
1
        if (ret != 0) {
7474
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7475
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7476
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7477
0
                         << ", ret=" << ret;
7478
0
            return -1;
7479
0
        }
7480
1
        metrics_context.total_recycled_num = ++num_recycled;
7481
1
        metrics_context.report();
7482
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7483
1
        stage_keys.push_back(k);
7484
1
        return 0;
7485
1
    };
7486
7487
11
    auto loop_done = [&stage_keys, this]() -> int {
7488
1
        if (stage_keys.empty()) return 0;
7489
1
        DORIS_CLOUD_DEFER {
7490
1
            stage_keys.clear();
7491
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7489
1
        DORIS_CLOUD_DEFER {
7490
1
            stage_keys.clear();
7491
1
        };
7492
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7493
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7494
0
            return -1;
7495
0
        }
7496
1
        return 0;
7497
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7487
1
    auto loop_done = [&stage_keys, this]() -> int {
7488
1
        if (stage_keys.empty()) return 0;
7489
1
        DORIS_CLOUD_DEFER {
7490
1
            stage_keys.clear();
7491
1
        };
7492
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7493
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7494
0
            return -1;
7495
0
        }
7496
1
        return 0;
7497
1
    };
7498
11
    if (config::enable_recycler_stats_metrics) {
7499
0
        scan_and_statistics_stage();
7500
0
    }
7501
    // recycle_func and loop_done for scan and recycle
7502
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7503
11
}
7504
7505
10
int InstanceRecycler::recycle_expired_stage_objects() {
7506
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7507
7508
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7509
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7510
7511
10
    DORIS_CLOUD_DEFER {
7512
10
        int64_t cost =
7513
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7514
10
        metrics_context.finish_report();
7515
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7516
10
                .tag("instance_id", instance_id_);
7517
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7511
10
    DORIS_CLOUD_DEFER {
7512
10
        int64_t cost =
7513
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7514
10
        metrics_context.finish_report();
7515
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7516
10
                .tag("instance_id", instance_id_);
7517
10
    };
7518
7519
10
    int ret = 0;
7520
7521
10
    if (config::enable_recycler_stats_metrics) {
7522
0
        scan_and_statistics_expired_stage_objects();
7523
0
    }
7524
7525
10
    for (const auto& stage : instance_info_.stages()) {
7526
0
        std::stringstream ss;
7527
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7528
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7529
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7530
0
           << ", prefix=" << stage.obj_info().prefix();
7531
7532
0
        if (stopped()) {
7533
0
            break;
7534
0
        }
7535
0
        if (stage.type() == StagePB::EXTERNAL) {
7536
0
            continue;
7537
0
        }
7538
0
        int idx = stoi(stage.obj_info().id());
7539
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7540
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7541
0
            continue;
7542
0
        }
7543
7544
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7545
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7546
0
        if (!s3_conf) {
7547
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7548
0
            continue;
7549
0
        }
7550
7551
0
        s3_conf->prefix = stage.obj_info().prefix();
7552
0
        std::shared_ptr<S3Accessor> accessor;
7553
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7554
0
        if (ret1 != 0) {
7555
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7556
0
            ret = -1;
7557
0
            continue;
7558
0
        }
7559
7560
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7561
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7562
0
            ret = -1;
7563
0
            continue;
7564
0
        }
7565
7566
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7567
0
        int64_t expiration_time =
7568
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7569
0
                config::internal_stage_objects_expire_time_second;
7570
0
        if (config::force_immediate_recycle) {
7571
0
            expiration_time = INT64_MAX;
7572
0
        }
7573
0
        ret1 = accessor->delete_all(expiration_time);
7574
0
        if (ret1 != 0) {
7575
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7576
0
                         << ss.str();
7577
0
            ret = -1;
7578
0
            continue;
7579
0
        }
7580
0
        metrics_context.total_recycled_num++;
7581
0
        metrics_context.report();
7582
0
    }
7583
10
    return ret;
7584
10
}
7585
7586
234
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7587
234
    std::lock_guard lock(recycle_tasks_mutex);
7588
234
    running_recycle_tasks[task_name] = start_time;
7589
234
}
7590
7591
234
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7592
234
    std::lock_guard lock(recycle_tasks_mutex);
7593
234
    DCHECK(running_recycle_tasks[task_name] > 0);
7594
234
    running_recycle_tasks.erase(task_name);
7595
234
}
7596
7597
21
bool InstanceRecycler::check_recycle_tasks() {
7598
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7599
21
    {
7600
21
        std::lock_guard lock(recycle_tasks_mutex);
7601
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7602
21
    }
7603
7604
21
    bool found = false;
7605
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7606
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7607
20
        int64_t cost = now - start_time;
7608
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7609
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7610
20
                    .tag("instance_id", instance_id_)
7611
20
                    .tag("task", task_name);
7612
20
            found = true;
7613
20
        }
7614
20
    }
7615
7616
21
    return found;
7617
21
}
7618
7619
// Scan and statistics indexes that need to be recycled
7620
0
int InstanceRecycler::scan_and_statistics_indexes() {
7621
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7622
7623
0
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7624
0
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7625
0
    std::string index_key0;
7626
0
    std::string index_key1;
7627
0
    recycle_index_key(index_key_info0, &index_key0);
7628
0
    recycle_index_key(index_key_info1, &index_key1);
7629
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7630
7631
0
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7632
0
        RecycleIndexPB index_pb;
7633
0
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7634
0
            return 0;
7635
0
        }
7636
0
        int64_t current_time = ::time(nullptr);
7637
0
        if (current_time <
7638
0
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7639
0
            return 0;
7640
0
        }
7641
        // decode index_id
7642
0
        auto k1 = k;
7643
0
        k1.remove_prefix(1);
7644
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7645
0
        decode_key(&k1, &out);
7646
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7647
0
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7648
0
        std::unique_ptr<Transaction> txn;
7649
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7650
0
        if (err != TxnErrorCode::TXN_OK) {
7651
0
            return 0;
7652
0
        }
7653
0
        std::string val;
7654
0
        err = txn->get(k, &val);
7655
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7656
0
            return 0;
7657
0
        }
7658
0
        if (err != TxnErrorCode::TXN_OK) {
7659
0
            return 0;
7660
0
        }
7661
0
        index_pb.Clear();
7662
0
        if (!index_pb.ParseFromString(val)) {
7663
0
            return 0;
7664
0
        }
7665
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7666
0
            return 0;
7667
0
        }
7668
0
        metrics_context.total_need_recycle_num++;
7669
0
        return 0;
7670
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_
7671
7672
0
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7673
0
    metrics_context.report(true);
7674
0
    segment_metrics_context_.report(true);
7675
0
    tablet_metrics_context_.report(true);
7676
0
    return ret;
7677
0
}
7678
7679
// Scan and statistics partitions that need to be recycled
7680
0
int InstanceRecycler::scan_and_statistics_partitions() {
7681
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7682
7683
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7684
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7685
0
    std::string part_key0;
7686
0
    std::string part_key1;
7687
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7688
7689
0
    recycle_partition_key(part_key_info0, &part_key0);
7690
0
    recycle_partition_key(part_key_info1, &part_key1);
7691
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7692
0
        RecyclePartitionPB part_pb;
7693
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7694
0
            return 0;
7695
0
        }
7696
0
        int64_t current_time = ::time(nullptr);
7697
0
        if (current_time <
7698
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7699
0
            return 0;
7700
0
        }
7701
        // decode partition_id
7702
0
        auto k1 = k;
7703
0
        k1.remove_prefix(1);
7704
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7705
0
        decode_key(&k1, &out);
7706
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7707
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7708
        // Change state to RECYCLING
7709
0
        std::unique_ptr<Transaction> txn;
7710
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7711
0
        if (err != TxnErrorCode::TXN_OK) {
7712
0
            return 0;
7713
0
        }
7714
0
        std::string val;
7715
0
        err = txn->get(k, &val);
7716
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7717
0
            return 0;
7718
0
        }
7719
0
        if (err != TxnErrorCode::TXN_OK) {
7720
0
            return 0;
7721
0
        }
7722
0
        part_pb.Clear();
7723
0
        if (!part_pb.ParseFromString(val)) {
7724
0
            return 0;
7725
0
        }
7726
        // Partitions with PREPARED state MUST have no data
7727
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
7728
0
        int ret = 0;
7729
0
        for (int64_t index_id : part_pb.index_id()) {
7730
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
7731
0
                                            partition_id, is_empty_tablet) != 0) {
7732
0
                ret = 0;
7733
0
            }
7734
0
        }
7735
0
        metrics_context.total_need_recycle_num++;
7736
0
        return ret;
7737
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_
7738
7739
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
7740
0
    metrics_context.report(true);
7741
0
    segment_metrics_context_.report(true);
7742
0
    tablet_metrics_context_.report(true);
7743
0
    return ret;
7744
0
}
7745
7746
// Scan and statistics rowsets that need to be recycled
7747
0
int InstanceRecycler::scan_and_statistics_rowsets() {
7748
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
7749
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
7750
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
7751
0
    std::string recyc_rs_key0;
7752
0
    std::string recyc_rs_key1;
7753
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
7754
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
7755
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7756
7757
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
7758
0
        RecycleRowsetPB rowset;
7759
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7760
0
            return 0;
7761
0
        }
7762
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
7763
0
        int64_t current_time = ::time(nullptr);
7764
0
        if (current_time <
7765
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
7766
0
            return 0;
7767
0
        }
7768
7769
0
        if (!rowset.has_type()) {
7770
0
            if (!rowset.has_resource_id()) [[unlikely]] {
7771
0
                return 0;
7772
0
            }
7773
0
            if (rowset.resource_id().empty()) [[unlikely]] {
7774
0
                return 0;
7775
0
            }
7776
0
            metrics_context.total_need_recycle_num++;
7777
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
7778
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
7779
0
            segment_metrics_context_.total_need_recycle_data_size +=
7780
0
                    rowset.rowset_meta().total_disk_size();
7781
0
            return 0;
7782
0
        }
7783
7784
0
        if (config::enable_mark_delete_rowset_before_recycle &&
7785
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
7786
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
7787
0
            return 0;
7788
0
        }
7789
7790
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
7791
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
7792
0
                return 0;
7793
0
            }
7794
0
        }
7795
0
        metrics_context.total_need_recycle_num++;
7796
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
7797
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
7798
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
7799
0
        return 0;
7800
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_
7801
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
7802
0
    metrics_context.report(true);
7803
0
    segment_metrics_context_.report(true);
7804
0
    return ret;
7805
0
}
7806
7807
// Scan and statistics tmp_rowsets that need to be recycled
7808
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
7809
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
7810
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
7811
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
7812
0
    std::string tmp_rs_key0;
7813
0
    std::string tmp_rs_key1;
7814
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
7815
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
7816
7817
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7818
7819
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
7820
0
        doris::RowsetMetaCloudPB rowset;
7821
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
7822
0
            return 0;
7823
0
        }
7824
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
7825
0
        int64_t current_time = ::time(nullptr);
7826
0
        if (current_time < expiration) {
7827
0
            return 0;
7828
0
        }
7829
7830
0
        DCHECK_GT(rowset.txn_id(), 0)
7831
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
7832
7833
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
7834
0
            return 0;
7835
0
        }
7836
7837
0
        if (!rowset.has_resource_id()) {
7838
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
7839
0
                return 0;
7840
0
            }
7841
0
            return 0;
7842
0
        }
7843
7844
0
        metrics_context.total_need_recycle_num++;
7845
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
7846
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
7847
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
7848
0
        return 0;
7849
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_
7850
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
7851
0
    metrics_context.report(true);
7852
0
    segment_metrics_context_.report(true);
7853
0
    return ret;
7854
0
}
7855
7856
// Scan and statistics abort_timeout_txn that need to be recycled
7857
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
7858
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
7859
7860
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
7861
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7862
0
    std::string begin_txn_running_key;
7863
0
    std::string end_txn_running_key;
7864
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
7865
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
7866
7867
0
    int64_t current_time =
7868
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7869
7870
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
7871
0
                                               std::string_view k, std::string_view v) -> int {
7872
0
        std::unique_ptr<Transaction> txn;
7873
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7874
0
        if (err != TxnErrorCode::TXN_OK) {
7875
0
            return 0;
7876
0
        }
7877
0
        std::string_view k1 = k;
7878
0
        k1.remove_prefix(1);
7879
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7880
0
        if (decode_key(&k1, &out) != 0) {
7881
0
            return 0;
7882
0
        }
7883
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7884
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7885
        // Update txn_info
7886
0
        std::string txn_inf_key, txn_inf_val;
7887
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
7888
0
        err = txn->get(txn_inf_key, &txn_inf_val);
7889
0
        if (err != TxnErrorCode::TXN_OK) {
7890
0
            return 0;
7891
0
        }
7892
0
        TxnInfoPB txn_info;
7893
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
7894
0
            return 0;
7895
0
        }
7896
7897
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
7898
0
            TxnRunningPB txn_running_pb;
7899
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
7900
0
                return 0;
7901
0
            }
7902
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
7903
0
                return 0;
7904
0
            }
7905
0
            metrics_context.total_need_recycle_num++;
7906
0
        }
7907
0
        return 0;
7908
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_
7909
7910
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7911
0
                               std::move(handle_abort_timeout_txn_kv));
7912
0
    metrics_context.report(true);
7913
0
    return ret;
7914
0
}
7915
7916
// Scan and statistics expired_txn_label that need to be recycled
7917
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
7918
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
7919
7920
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7921
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7922
0
    std::string begin_recycle_txn_key;
7923
0
    std::string end_recycle_txn_key;
7924
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7925
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7926
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7927
0
    int64_t current_time_ms =
7928
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7929
7930
    // for calculate the total num or bytes of recyled objects
7931
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
7932
0
        RecycleTxnPB recycle_txn_pb;
7933
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7934
0
            return 0;
7935
0
        }
7936
0
        if ((config::force_immediate_recycle) ||
7937
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7938
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7939
0
             current_time_ms)) {
7940
0
            metrics_context.total_need_recycle_num++;
7941
0
        }
7942
0
        return 0;
7943
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_
7944
7945
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7946
0
                               std::move(handle_expired_txn_label_kv));
7947
0
    metrics_context.report(true);
7948
0
    return ret;
7949
0
}
7950
7951
// Scan and statistics copy_jobs that need to be recycled
7952
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
7953
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
7954
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7955
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7956
0
    std::string key0;
7957
0
    std::string key1;
7958
0
    copy_job_key(key_info0, &key0);
7959
0
    copy_job_key(key_info1, &key1);
7960
7961
    // for calculate the total num or bytes of recyled objects
7962
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
7963
0
        CopyJobPB copy_job;
7964
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7965
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7966
0
            return 0;
7967
0
        }
7968
7969
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7970
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
7971
0
                int64_t current_time =
7972
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7973
0
                if (copy_job.finish_time_ms() > 0) {
7974
0
                    if (!config::force_immediate_recycle &&
7975
0
                        current_time < copy_job.finish_time_ms() +
7976
0
                                               config::copy_job_max_retention_second * 1000) {
7977
0
                        return 0;
7978
0
                    }
7979
0
                } else {
7980
0
                    if (!config::force_immediate_recycle &&
7981
0
                        current_time < copy_job.start_time_ms() +
7982
0
                                               config::copy_job_max_retention_second * 1000) {
7983
0
                        return 0;
7984
0
                    }
7985
0
                }
7986
0
            }
7987
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7988
0
            int64_t current_time =
7989
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7990
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7991
0
                return 0;
7992
0
            }
7993
0
        }
7994
0
        metrics_context.total_need_recycle_num++;
7995
0
        return 0;
7996
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_
7997
7998
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
7999
0
    metrics_context.report(true);
8000
0
    return ret;
8001
0
}
8002
8003
// Scan and statistics stage that need to be recycled
8004
0
int InstanceRecycler::scan_and_statistics_stage() {
8005
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8006
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8007
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8008
0
    std::string key0 = recycle_stage_key(key_info0);
8009
0
    std::string key1 = recycle_stage_key(key_info1);
8010
8011
    // for calculate the total num or bytes of recyled objects
8012
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8013
0
                                                        std::string_view v) -> int {
8014
0
        RecycleStagePB recycle_stage;
8015
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8016
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8017
0
            return 0;
8018
0
        }
8019
8020
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8021
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8022
0
            LOG(WARNING) << "invalid idx: " << idx;
8023
0
            return 0;
8024
0
        }
8025
8026
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8027
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8028
0
                [&] {
8029
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8030
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8031
0
                    if (!s3_conf) {
8032
0
                        return 0;
8033
0
                    }
8034
8035
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8036
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8037
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8038
0
                    if (ret != 0) {
8039
0
                        return 0;
8040
0
                    }
8041
8042
0
                    accessor = std::move(s3_accessor);
8043
0
                    return 0;
8044
0
                }(),
8045
0
                "recycle_stage:get_accessor", &accessor);
8046
8047
0
        if (ret != 0) {
8048
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8049
0
            return 0;
8050
0
        }
8051
8052
0
        metrics_context.total_need_recycle_num++;
8053
0
        return 0;
8054
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_
8055
8056
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8057
0
    metrics_context.report(true);
8058
0
    return ret;
8059
0
}
8060
8061
// Scan and statistics expired_stage_objects that need to be recycled
8062
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8063
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8064
8065
    // for calculate the total num or bytes of recyled objects
8066
0
    auto scan_and_statistics = [&metrics_context, this]() {
8067
0
        for (const auto& stage : instance_info_.stages()) {
8068
0
            if (stopped()) {
8069
0
                break;
8070
0
            }
8071
0
            if (stage.type() == StagePB::EXTERNAL) {
8072
0
                continue;
8073
0
            }
8074
0
            int idx = stoi(stage.obj_info().id());
8075
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8076
0
                continue;
8077
0
            }
8078
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8079
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8080
0
            if (!s3_conf) {
8081
0
                continue;
8082
0
            }
8083
0
            s3_conf->prefix = stage.obj_info().prefix();
8084
0
            std::shared_ptr<S3Accessor> accessor;
8085
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8086
0
            if (ret1 != 0) {
8087
0
                continue;
8088
0
            }
8089
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8090
0
                continue;
8091
0
            }
8092
0
            metrics_context.total_need_recycle_num++;
8093
0
        }
8094
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8095
8096
0
    scan_and_statistics();
8097
0
    metrics_context.report(true);
8098
0
    return 0;
8099
0
}
8100
8101
// Scan and statistics versions that need to be recycled
8102
0
int InstanceRecycler::scan_and_statistics_versions() {
8103
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8104
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8105
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8106
8107
0
    int64_t last_scanned_table_id = 0;
8108
0
    bool is_recycled = false; // Is last scanned kv recycled
8109
    // for calculate the total num or bytes of recyled objects
8110
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8111
0
                                       std::string_view k, std::string_view) {
8112
0
        auto k1 = k;
8113
0
        k1.remove_prefix(1);
8114
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8115
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8116
0
        decode_key(&k1, &out);
8117
0
        DCHECK_EQ(out.size(), 6) << k;
8118
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8119
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8120
0
            metrics_context.total_need_recycle_num +=
8121
0
                    is_recycled; // Version kv of this table has been recycled
8122
0
            return 0;
8123
0
        }
8124
0
        last_scanned_table_id = table_id;
8125
0
        is_recycled = false;
8126
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8127
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8128
0
        std::unique_ptr<Transaction> txn;
8129
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8130
0
        if (err != TxnErrorCode::TXN_OK) {
8131
0
            return 0;
8132
0
        }
8133
0
        std::unique_ptr<RangeGetIterator> iter;
8134
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8135
0
        if (err != TxnErrorCode::TXN_OK) {
8136
0
            return 0;
8137
0
        }
8138
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8139
0
            return 0;
8140
0
        }
8141
0
        metrics_context.total_need_recycle_num++;
8142
0
        is_recycled = true;
8143
0
        return 0;
8144
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_
8145
8146
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8147
0
    metrics_context.report(true);
8148
0
    return ret;
8149
0
}
8150
8151
// Scan and statistics restore jobs that need to be recycled
8152
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8153
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8154
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8155
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8156
0
    std::string restore_job_key0;
8157
0
    std::string restore_job_key1;
8158
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8159
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8160
8161
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8162
8163
    // for calculate the total num or bytes of recyled objects
8164
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8165
0
        RestoreJobCloudPB restore_job_pb;
8166
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8167
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8168
0
            return 0;
8169
0
        }
8170
0
        int64_t expiration =
8171
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8172
0
        int64_t current_time = ::time(nullptr);
8173
0
        if (current_time < expiration) { // not expired
8174
0
            return 0;
8175
0
        }
8176
0
        metrics_context.total_need_recycle_num++;
8177
0
        if (restore_job_pb.need_recycle_data()) {
8178
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8179
0
        }
8180
0
        return 0;
8181
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_
8182
8183
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8184
0
    metrics_context.report(true);
8185
0
    return ret;
8186
0
}
8187
8188
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8189
3
    if (!should_recycle_versioned_keys()) {
8190
0
        return;
8191
0
    }
8192
8193
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8194
8195
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8196
3
    if (recycle_checker.init() != 0) {
8197
0
        return;
8198
0
    }
8199
8200
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8201
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8202
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8203
8204
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8205
8
    for (; iter->valid(); iter->next()) {
8206
5
        OperationLogPB operation_log;
8207
5
        if (!iter->parse_value(&operation_log)) {
8208
0
            continue;
8209
0
        }
8210
8211
5
        std::string_view key = iter->key();
8212
5
        Versionstamp log_versionstamp;
8213
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8214
0
            continue;
8215
0
        }
8216
8217
5
        OperationLogReferenceInfo ref_info;
8218
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8219
5
                                        &ref_info)) {
8220
4
            metrics_context.total_need_recycle_num++;
8221
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8222
4
        }
8223
5
    }
8224
8225
3
    metrics_context.report(true);
8226
3
}
8227
8228
int InstanceRecycler::classify_rowset_task_by_ref_count(
8229
61
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8230
61
    constexpr int MAX_RETRY = 10;
8231
61
    const auto& rowset_meta = task.rowset_meta;
8232
61
    int64_t tablet_id = rowset_meta.tablet_id();
8233
61
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8234
61
    std::string_view reference_instance_id = instance_id_;
8235
61
    if (rowset_meta.has_reference_instance_id()) {
8236
5
        reference_instance_id = rowset_meta.reference_instance_id();
8237
5
    }
8238
8239
62
    for (int i = 0; i < MAX_RETRY; ++i) {
8240
62
        std::unique_ptr<Transaction> txn;
8241
62
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8242
62
        if (err != TxnErrorCode::TXN_OK) {
8243
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8244
0
                    .tag("instance_id", instance_id_)
8245
0
                    .tag("tablet_id", tablet_id)
8246
0
                    .tag("rowset_id", rowset_id)
8247
0
                    .tag("err", err);
8248
0
            return -1;
8249
0
        }
8250
8251
62
        std::string rowset_ref_count_key =
8252
62
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8253
62
        task.rowset_ref_count_key = rowset_ref_count_key;
8254
8255
62
        int64_t ref_count = 0;
8256
62
        {
8257
62
            std::string value;
8258
62
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8259
62
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8260
0
                ref_count = 1;
8261
62
            } else if (err != TxnErrorCode::TXN_OK) {
8262
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8263
0
                        .tag("instance_id", instance_id_)
8264
0
                        .tag("tablet_id", tablet_id)
8265
0
                        .tag("rowset_id", rowset_id)
8266
0
                        .tag("err", err);
8267
0
                return -1;
8268
62
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8269
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8270
0
                        .tag("instance_id", instance_id_)
8271
0
                        .tag("tablet_id", tablet_id)
8272
0
                        .tag("rowset_id", rowset_id)
8273
0
                        .tag("value", hex(value));
8274
0
                return -1;
8275
0
            }
8276
62
        }
8277
8278
62
        if (ref_count > 1) {
8279
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8280
12
            txn->atomic_add(rowset_ref_count_key, -1);
8281
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8282
12
                    .tag("instance_id", instance_id_)
8283
12
                    .tag("tablet_id", tablet_id)
8284
12
                    .tag("rowset_id", rowset_id)
8285
12
                    .tag("ref_count", ref_count - 1)
8286
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8287
8288
12
            if (!task.recycle_rowset_key.empty()) {
8289
0
                txn->remove(task.recycle_rowset_key);
8290
0
                LOG_INFO("remove recycle rowset key in classification phase")
8291
0
                        .tag("key", hex(task.recycle_rowset_key));
8292
0
            }
8293
12
            if (!task.non_versioned_rowset_key.empty()) {
8294
12
                txn->remove(task.non_versioned_rowset_key);
8295
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8296
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8297
12
            }
8298
8299
12
            err = txn->commit();
8300
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8301
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8302
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8303
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8304
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8305
1
                continue;
8306
11
            } else if (err != TxnErrorCode::TXN_OK) {
8307
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8308
0
                        .tag("instance_id", instance_id_)
8309
0
                        .tag("tablet_id", tablet_id)
8310
0
                        .tag("rowset_id", rowset_id)
8311
0
                        .tag("err", err);
8312
0
                return -1;
8313
0
            }
8314
11
            return 1; // handled, not added to batch delete
8315
50
        } else {
8316
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8317
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8318
50
            LOG_INFO("add rowset to batch delete plan")
8319
50
                    .tag("instance_id", instance_id_)
8320
50
                    .tag("tablet_id", tablet_id)
8321
50
                    .tag("rowset_id", rowset_id)
8322
50
                    .tag("resource_id", rowset_meta.resource_id())
8323
50
                    .tag("ref_count", ref_count);
8324
8325
50
            batch_delete_tasks.push_back(std::move(task));
8326
50
            return 0; // added to batch delete
8327
50
        }
8328
62
    }
8329
8330
0
    LOG_WARNING("failed to classify rowset task after retry")
8331
0
            .tag("instance_id", instance_id_)
8332
0
            .tag("tablet_id", tablet_id)
8333
0
            .tag("rowset_id", rowset_id)
8334
0
            .tag("retry", MAX_RETRY);
8335
0
    return -1;
8336
61
}
8337
8338
11
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8339
11
    int ret = 0;
8340
50
    for (const auto& task : tasks) {
8341
50
        int64_t tablet_id = task.rowset_meta.tablet_id();
8342
50
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8343
8344
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8345
        // so we don't need to call it again here.
8346
8347
        // Remove all metadata keys in one transaction
8348
50
        std::unique_ptr<Transaction> txn;
8349
50
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8350
50
        if (err != TxnErrorCode::TXN_OK) {
8351
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8352
0
                    .tag("instance_id", instance_id_)
8353
0
                    .tag("tablet_id", tablet_id)
8354
0
                    .tag("rowset_id", rowset_id)
8355
0
                    .tag("err", err);
8356
0
            ret = -1;
8357
0
            continue;
8358
0
        }
8359
8360
50
        std::string_view reference_instance_id = instance_id_;
8361
50
        if (task.rowset_meta.has_reference_instance_id()) {
8362
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
8363
5
        }
8364
8365
50
        txn->remove(task.rowset_ref_count_key);
8366
50
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8367
50
                .tag("instance_id", instance_id_)
8368
50
                .tag("tablet_id", tablet_id)
8369
50
                .tag("rowset_id", rowset_id)
8370
50
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8371
8372
50
        std::string dbm_start_key =
8373
50
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8374
50
        std::string dbm_end_key = meta_delete_bitmap_key(
8375
50
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8376
50
                 std::numeric_limits<int64_t>::max()});
8377
50
        txn->remove(dbm_start_key, dbm_end_key);
8378
50
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8379
50
                .tag("instance_id", instance_id_)
8380
50
                .tag("tablet_id", tablet_id)
8381
50
                .tag("rowset_id", rowset_id)
8382
50
                .tag("begin", hex(dbm_start_key))
8383
50
                .tag("end", hex(dbm_end_key));
8384
8385
50
        std::string versioned_dbm_start_key =
8386
50
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8387
50
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8388
50
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8389
50
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8390
50
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8391
50
                .tag("instance_id", instance_id_)
8392
50
                .tag("tablet_id", tablet_id)
8393
50
                .tag("rowset_id", rowset_id)
8394
50
                .tag("begin", hex(versioned_dbm_start_key))
8395
50
                .tag("end", hex(versioned_dbm_end_key));
8396
8397
        // Remove versioned meta rowset key
8398
50
        if (!task.versioned_rowset_key.empty()) {
8399
50
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8400
50
                                                          task.versionstamp);
8401
50
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8402
50
                    .tag("instance_id", instance_id_)
8403
50
                    .tag("tablet_id", tablet_id)
8404
50
                    .tag("rowset_id", rowset_id)
8405
50
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8406
50
        }
8407
8408
50
        if (!task.non_versioned_rowset_key.empty()) {
8409
50
            txn->remove(task.non_versioned_rowset_key);
8410
50
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8411
50
                    .tag("instance_id", instance_id_)
8412
50
                    .tag("tablet_id", tablet_id)
8413
50
                    .tag("rowset_id", rowset_id)
8414
50
                    .tag("key", hex(task.non_versioned_rowset_key));
8415
50
        }
8416
8417
        // Remove recycle_rowset_key last to ensure retry safety:
8418
        // if cleanup fails, this key remains and triggers next round retry.
8419
50
        if (!task.recycle_rowset_key.empty()) {
8420
0
            txn->remove(task.recycle_rowset_key);
8421
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8422
0
                    .tag("instance_id", instance_id_)
8423
0
                    .tag("tablet_id", tablet_id)
8424
0
                    .tag("rowset_id", rowset_id)
8425
0
                    .tag("key", hex(task.recycle_rowset_key));
8426
0
        }
8427
8428
50
        err = txn->commit();
8429
50
        if (err != TxnErrorCode::TXN_OK) {
8430
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8431
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8432
0
                    .tag("instance_id", instance_id_)
8433
0
                    .tag("tablet_id", tablet_id)
8434
0
                    .tag("rowset_id", rowset_id)
8435
0
                    .tag("err", err);
8436
0
            ret = -1;
8437
0
            continue;
8438
0
        }
8439
8440
50
        LOG_INFO("cleanup rowset metadata success")
8441
50
                .tag("instance_id", instance_id_)
8442
50
                .tag("tablet_id", tablet_id)
8443
50
                .tag("rowset_id", rowset_id);
8444
50
    }
8445
11
    return ret;
8446
11
}
8447
8448
} // namespace doris::cloud