Coverage Report

Created: 2025-07-06 19:59

/root/doris/cloud/src/recycler/recycler.h
Line
Count
Source (jump to first uncovered line)
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
#pragma once
19
20
#include <gen_cpp/cloud.pb.h>
21
22
#include <atomic>
23
#include <condition_variable>
24
#include <cstdint>
25
#include <deque>
26
#include <functional>
27
#include <memory>
28
#include <string>
29
#include <string_view>
30
#include <thread>
31
#include <utility>
32
33
#include "common/bvars.h"
34
#include "meta-service/txn_lazy_committer.h"
35
#include "recycler/storage_vault_accessor.h"
36
#include "recycler/white_black_list.h"
37
38
namespace brpc {
39
class Server;
40
} // namespace brpc
41
42
namespace doris::cloud {
43
class TxnKv;
44
class InstanceRecycler;
45
class StorageVaultAccessor;
46
class Checker;
47
class SimpleThreadPool;
48
class RecyclerMetricsContext;
49
struct RecyclerThreadPoolGroup {
50
6
    RecyclerThreadPoolGroup() = default;
51
    RecyclerThreadPoolGroup(std::shared_ptr<SimpleThreadPool> s3_producer_pool,
52
                            std::shared_ptr<SimpleThreadPool> recycle_tablet_pool,
53
                            std::shared_ptr<SimpleThreadPool> group_recycle_function_pool)
54
            : s3_producer_pool(std::move(s3_producer_pool)),
55
              recycle_tablet_pool(std::move(recycle_tablet_pool)),
56
8
              group_recycle_function_pool(std::move(group_recycle_function_pool)) {}
57
160
    ~RecyclerThreadPoolGroup() = default;
58
73
    RecyclerThreadPoolGroup(const RecyclerThreadPoolGroup&) = default;
59
    RecyclerThreadPoolGroup& operator=(RecyclerThreadPoolGroup& other) = default;
60
8
    RecyclerThreadPoolGroup& operator=(RecyclerThreadPoolGroup&& other) = default;
61
73
    RecyclerThreadPoolGroup(RecyclerThreadPoolGroup&&) = default;
62
    // used for accessor.delete_files, accessor.delete_directory
63
    std::shared_ptr<SimpleThreadPool> s3_producer_pool;
64
    // used for InstanceRecycler::recycle_tablet
65
    std::shared_ptr<SimpleThreadPool> recycle_tablet_pool;
66
    std::shared_ptr<SimpleThreadPool> group_recycle_function_pool;
67
};
68
69
class Recycler {
70
public:
71
    explicit Recycler(std::shared_ptr<TxnKv> txn_kv);
72
    ~Recycler();
73
74
    // returns 0 for success otherwise error
75
    int start(brpc::Server* server);
76
77
    void stop();
78
79
293
    bool stopped() const { return stopped_.load(std::memory_order_acquire); }
80
81
private:
82
    void recycle_callback();
83
84
    void instance_scanner_callback();
85
86
    void lease_recycle_jobs();
87
88
    void check_recycle_tasks();
89
90
private:
91
    friend class RecyclerServiceImpl;
92
93
    std::shared_ptr<TxnKv> txn_kv_;
94
    std::atomic_bool stopped_ {false};
95
96
    std::vector<std::thread> workers_;
97
98
    std::mutex mtx_;
99
    // notify recycle workers
100
    std::condition_variable pending_instance_cond_;
101
    std::deque<InstanceInfoPB> pending_instance_queue_;
102
    std::unordered_set<std::string> pending_instance_set_;
103
    std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map_;
104
    // notify instance scanner and lease thread
105
    std::condition_variable notifier_;
106
107
    std::string ip_port_;
108
109
    WhiteBlackList instance_filter_;
110
    std::unique_ptr<Checker> checker_;
111
112
    RecyclerThreadPoolGroup _thread_pool_group;
113
114
    std::shared_ptr<TxnLazyCommitter> txn_lazy_committer_;
115
};
116
117
enum class RowsetRecyclingState {
118
    FORMAL_ROWSET,
119
    TMP_ROWSET,
120
};
121
122
class InstanceRecycler {
123
public:
124
    explicit InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
125
                              RecyclerThreadPoolGroup thread_pool_group,
126
                              std::shared_ptr<TxnLazyCommitter> txn_lazy_committer);
127
    ~InstanceRecycler();
128
129
    // returns 0 for success otherwise error
130
    int init();
131
132
0
    void stop() { stopped_.store(true, std::memory_order_release); }
133
32
    bool stopped() const { return stopped_.load(std::memory_order_acquire); }
134
135
    // returns 0 for success otherwise error
136
    int do_recycle();
137
138
    // remove all kv and data in this instance, ONLY be called when instance has been deleted
139
    // returns 0 for success otherwise error
140
    int recycle_deleted_instance();
141
142
    // scan and recycle expired indexes:
143
    // 1. dropped table, dropped mv
144
    // 2. half-successtable/index when create
145
    // returns 0 for success otherwise error
146
    int recycle_indexes();
147
148
    // scan and recycle expired partitions:
149
    // 1. dropped parttion
150
    // 2. half-success partition when create
151
    // returns 0 for success otherwise error
152
    int recycle_partitions();
153
154
    // scan and recycle expired rowsets:
155
    // 1. prepare_rowset will produce recycle_rowset before uploading data to remote storage (memo)
156
    // 2. compaction will change the input rowsets to recycle_rowset
157
    // returns 0 for success otherwise error
158
    int recycle_rowsets();
159
160
    // scan and recycle expired tmp rowsets:
161
    // 1. commit_rowset will produce tmp_rowset when finish upload data (load or compaction) to remote storage
162
    // returns 0 for success otherwise error
163
    int recycle_tmp_rowsets();
164
165
    /**
166
     * recycle all tablets belonging to the index specified by `index_id`
167
     *
168
     * @param partition_id if positive, only recycle tablets in this partition belonging to the specified index
169
     * @param is_empty_tablet indicates whether the tablet has object files, can skip delete objects if tablet is empty
170
     * @return 0 for success otherwise error
171
     */
172
    int recycle_tablets(int64_t table_id, int64_t index_id, RecyclerMetricsContext& ctx,
173
                        int64_t partition_id = -1, bool is_empty_tablet = false);
174
175
    /**
176
     * recycle all rowsets belonging to the tablet specified by `tablet_id`
177
     *
178
     * @return 0 for success otherwise error
179
     */
180
    int recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context);
181
182
    // scan and recycle useless partition version kv
183
    int recycle_versions();
184
185
    // scan and abort timeout txn label
186
    // returns 0 for success otherwise error
187
    int abort_timeout_txn();
188
189
    //scan and recycle expire txn label
190
    // returns 0 for success otherwise error
191
    int recycle_expired_txn_label();
192
193
    // scan and recycle finished or timeout copy jobs
194
    // returns 0 for success otherwise error
195
    int recycle_copy_jobs();
196
197
    // scan and recycle dropped internal stage
198
    // returns 0 for success otherwise error
199
    int recycle_stage();
200
201
    // scan and recycle expired stage objects
202
    // returns 0 for success otherwise error
203
    int recycle_expired_stage_objects();
204
205
    bool check_recycle_tasks();
206
207
private:
208
    // returns 0 for success otherwise error
209
    int init_obj_store_accessors();
210
211
    // returns 0 for success otherwise error
212
    int init_storage_vault_accessors();
213
214
    /**
215
     * Scan key-value pairs between [`begin`, `end`), and perform `recycle_func` on each key-value pair.
216
     *
217
     * @param recycle_func defines how to recycle resources corresponding to a key-value pair. Returns 0 if the recycling is successful.
218
     * @param loop_done is called after `RangeGetIterator` has no next kv. Usually used to perform a batch recycling. Returns 0 if success. 
219
     * @return 0 if all corresponding resources are recycled successfully, otherwise non-zero
220
     */
221
    int scan_and_recycle(std::string begin, std::string_view end,
222
                         std::function<int(std::string_view k, std::string_view v)> recycle_func,
223
                         std::function<int()> loop_done = nullptr);
224
225
    int scan_for_recycle_and_statistics(
226
            std::string begin, std::string_view end, std::string task_name,
227
            RecyclerMetricsContext& metrics_context,
228
            std::function<int(std::string_view k, std::string_view v)> statistics_func,
229
            std::function<int(std::string_view k, std::string_view v)> recycle_func,
230
            std::function<int()> loop_done = nullptr);
231
232
    // return 0 for success otherwise error
233
    int delete_rowset_data(const doris::RowsetMetaCloudPB& rs_meta_pb);
234
235
    // return 0 for success otherwise error
236
    // NOTE: this function ONLY be called when the file paths cannot be calculated
237
    int delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
238
                           const std::string& rowset_id);
239
240
    // return 0 for success otherwise error
241
    int delete_rowset_data(const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets,
242
                           RowsetRecyclingState type, RecyclerMetricsContext& metrics_context);
243
244
    /**
245
     * Get stage storage info from instance and init StorageVaultAccessor
246
     * @return 0 if accessor is successfully inited, 1 if stage not found, negative for error
247
     */
248
    int init_copy_job_accessor(const std::string& stage_id, const StagePB::StageType& stage_type,
249
                               std::shared_ptr<StorageVaultAccessor>* accessor);
250
251
    void register_recycle_task(const std::string& task_name, int64_t start_time);
252
253
    void unregister_recycle_task(const std::string& task_name);
254
255
    // for scan all tablets and statistics metrics
256
    int scan_tablets_and_statistics(int64_t tablet_id, int64_t index_id,
257
                                    RecyclerMetricsContext& metrics_context,
258
                                    int64_t partition_id = -1, bool is_empty_tablet = false);
259
260
    // for scan all rs of tablet and statistics metrics
261
    int scan_tablet_and_statistics(int64_t tablet_id, RecyclerMetricsContext& metrics_context);
262
263
private:
264
    std::atomic_bool stopped_ {false};
265
    std::shared_ptr<TxnKv> txn_kv_;
266
    std::string instance_id_;
267
    InstanceInfoPB instance_info_;
268
269
    // TODO(plat1ko): Add new accessor to map in runtime for new created storage vaults
270
    std::unordered_map<std::string, std::shared_ptr<StorageVaultAccessor>> accessor_map_;
271
    using InvertedIndexInfo =
272
            std::pair<InvertedIndexStorageFormatPB, std::vector<std::pair<int64_t, std::string>>>;
273
274
    class InvertedIndexIdCache;
275
    std::unique_ptr<InvertedIndexIdCache> inverted_index_id_cache_;
276
277
    std::mutex recycled_tablets_mtx_;
278
    // Store recycled tablets, we can skip deleting rowset data of these tablets because these data has already been deleted.
279
    std::unordered_set<int64_t> recycled_tablets_;
280
281
    std::mutex recycle_tasks_mutex;
282
    // <task_name, start_time>>
283
    std::map<std::string, int64_t> running_recycle_tasks;
284
285
    RecyclerThreadPoolGroup _thread_pool_group;
286
287
    std::shared_ptr<TxnLazyCommitter> txn_lazy_committer_;
288
};
289
290
class RecyclerMetricsContext {
291
public:
292
1
    RecyclerMetricsContext() = default;
293
294
    RecyclerMetricsContext(std::string instance_id, std::string operation_type)
295
146
            : operation_type(std::move(operation_type)), instance_id(std::move(instance_id)) {
296
146
        start();
297
146
    }
298
299
143
    ~RecyclerMetricsContext() = default;
300
301
    int64_t total_need_recycle_data_size = 0;
302
    int64_t total_need_recycle_num = 0;
303
304
    std::atomic_long total_recycled_data_size {0};
305
    std::atomic_long total_recycled_num {0};
306
307
    std::string operation_type {};
308
    std::string instance_id {};
309
310
    double start_time = 0;
311
312
147
    void start() {
313
147
        start_time = duration_cast<std::chrono::milliseconds>(
314
147
                             std::chrono::system_clock::now().time_since_epoch())
315
147
                             .count();
316
147
    }
317
318
163
    double duration() const {
319
163
        return duration_cast<std::chrono::milliseconds>(
320
163
                       std::chrono::system_clock::now().time_since_epoch())
321
163
                       .count() -
322
163
               start_time;
323
163
    }
324
325
20
    void reset() {
326
20
        total_need_recycle_data_size = 0;
327
20
        total_need_recycle_num = 0;
328
20
        total_recycled_data_size.store(0);
329
20
        total_recycled_num.store(0);
330
20
        start_time = duration_cast<std::chrono::milliseconds>(
331
20
                             std::chrono::system_clock::now().time_since_epoch())
332
20
                             .count();
333
20
    }
334
335
163
    void finish_report() {
336
163
        if (!operation_type.empty()) {
337
163
            double cost = duration();
338
163
            g_bvar_recycler_instance_last_round_recycle_elpased_ts.put(
339
163
                    {instance_id, operation_type}, cost);
340
163
            g_bvar_recycler_instance_recycle_round.put({instance_id, operation_type}, 1);
341
163
            LOG(INFO) << "recycle instance: " << instance_id
342
163
                      << ", operation type: " << operation_type << ", cost: " << cost
343
163
                      << " ms, total recycled num: " << total_recycled_num.load()
344
163
                      << ", total recycled data size: " << total_recycled_data_size.load()
345
163
                      << " bytes";
346
163
            if (total_recycled_num.load()) {
347
23
                g_bvar_recycler_instance_recycle_time_per_resource.put(
348
23
                        {instance_id, operation_type}, cost / total_recycled_num.load());
349
140
            } else {
350
140
                g_bvar_recycler_instance_recycle_time_per_resource.put(
351
140
                        {instance_id, operation_type}, -1);
352
140
            }
353
163
            if (total_recycled_data_size.load()) {
354
0
                g_bvar_recycler_instance_recycle_bytes_per_ms.put(
355
0
                        {instance_id, operation_type}, total_recycled_data_size.load() / cost);
356
163
            } else {
357
163
                g_bvar_recycler_instance_recycle_bytes_per_ms.put({instance_id, operation_type},
358
163
                                                                  -1);
359
163
            }
360
163
        }
361
163
    }
362
363
    // `is_begin` is used to initialize total num of items need to be recycled
364
26.0k
    void report(bool is_begin = false) {
365
26.0k
        if (!operation_type.empty()) {
366
25.5k
            if (total_need_recycle_data_size > 0) {
367
                // is init
368
0
                if (is_begin) {
369
0
                    g_bvar_recycler_instance_last_round_to_recycle_bytes.put(
370
0
                            {instance_id, operation_type}, total_need_recycle_data_size);
371
0
                } else {
372
0
                    g_bvar_recycler_instance_last_round_recycled_bytes.put(
373
0
                            {instance_id, operation_type}, total_recycled_data_size.load());
374
0
                    g_bvar_recycler_instance_recycle_total_bytes_since_started.put(
375
0
                            {instance_id, operation_type}, total_recycled_data_size.load());
376
0
                }
377
0
            }
378
379
25.5k
            if (total_need_recycle_num > 0) {
380
                // is init
381
0
                if (is_begin) {
382
0
                    g_bvar_recycler_instance_last_round_to_recycle_num.put(
383
0
                            {instance_id, operation_type}, total_need_recycle_num);
384
0
                } else {
385
0
                    g_bvar_recycler_instance_last_round_recycled_num.put(
386
0
                            {instance_id, operation_type}, total_recycled_num.load());
387
0
                    g_bvar_recycler_instance_recycle_total_num_since_started.put(
388
0
                            {instance_id, operation_type}, total_recycled_num.load());
389
0
                }
390
0
            }
391
25.5k
        }
392
26.0k
    }
393
};
394
395
} // namespace doris::cloud