Coverage Report

Created: 2026-03-25 13:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_warm_up_manager.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 "cloud/cloud_warm_up_manager.h"
19
20
#include <bthread/condition_variable.h>
21
#include <bthread/mutex.h>
22
#include <bthread/unstable.h>
23
#include <butil/time.h>
24
#include <bvar/bvar.h>
25
#include <bvar/reducer.h>
26
27
#include <algorithm>
28
#include <cstddef>
29
#include <tuple>
30
31
#include "bvar/bvar.h"
32
#include "cloud/cloud_tablet.h"
33
#include "cloud/cloud_tablet_mgr.h"
34
#include "cloud/config.h"
35
#include "common/cast_set.h"
36
#include "common/logging.h"
37
#include "io/cache/block_file_cache_downloader.h"
38
#include "runtime/exec_env.h"
39
#include "storage/index/inverted/inverted_index_desc.h"
40
#include "storage/rowset/beta_rowset.h"
41
#include "storage/tablet/tablet.h"
42
#include "util/brpc_client_cache.h" // BrpcClientCache
43
#include "util/client_cache.h"
44
#include "util/stack_util.h"
45
#include "util/thrift_rpc_helper.h"
46
#include "util/time.h"
47
48
namespace doris {
49
#include "common/compile_check_begin.h"
50
51
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_skipped_rowset_num(
52
        "file_cache_event_driven_warm_up_skipped_rowset_num");
53
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_segment_size(
54
        "file_cache_event_driven_warm_up_requested_segment_size");
55
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_segment_num(
56
        "file_cache_event_driven_warm_up_requested_segment_num");
57
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_index_size(
58
        "file_cache_event_driven_warm_up_requested_index_size");
59
bvar::Adder<uint64_t> g_file_cache_event_driven_warm_up_requested_index_num(
60
        "file_cache_event_driven_warm_up_requested_index_num");
61
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_tablet_num(
62
        "file_cache_once_or_periodic_warm_up_submitted_tablet_num");
63
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_tablet_num(
64
        "file_cache_once_or_periodic_warm_up_finished_tablet_num");
65
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_segment_size(
66
        "file_cache_once_or_periodic_warm_up_submitted_segment_size");
67
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_segment_num(
68
        "file_cache_once_or_periodic_warm_up_submitted_segment_num");
69
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_index_size(
70
        "file_cache_once_or_periodic_warm_up_submitted_index_size");
71
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_submitted_index_num(
72
        "file_cache_once_or_periodic_warm_up_submitted_index_num");
73
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_segment_size(
74
        "file_cache_once_or_periodic_warm_up_finished_segment_size");
75
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_segment_num(
76
        "file_cache_once_or_periodic_warm_up_finished_segment_num");
77
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_index_size(
78
        "file_cache_once_or_periodic_warm_up_finished_index_size");
79
bvar::Adder<uint64_t> g_file_cache_once_or_periodic_warm_up_finished_index_num(
80
        "file_cache_once_or_periodic_warm_up_finished_index_num");
81
bvar::Adder<uint64_t> g_file_cache_recycle_cache_requested_segment_num(
82
        "file_cache_recycle_cache_requested_segment_num");
83
bvar::Adder<uint64_t> g_file_cache_recycle_cache_requested_index_num(
84
        "file_cache_recycle_cache_requested_index_num");
85
bvar::Status<int64_t> g_file_cache_warm_up_rowset_last_call_unix_ts(
86
        "file_cache_warm_up_rowset_last_call_unix_ts", 0);
87
bvar::Adder<uint64_t> file_cache_warm_up_failed_task_num("file_cache_warm_up", "failed_task_num");
88
bvar::Adder<uint64_t> g_balance_tablet_be_mapping_size("balance_tablet_be_mapping_size");
89
90
bvar::LatencyRecorder g_file_cache_warm_up_rowset_wait_for_compaction_latency(
91
        "file_cache_warm_up_rowset_wait_for_compaction_latency");
92
93
1
CloudWarmUpManager::CloudWarmUpManager(CloudStorageEngine& engine) : _engine(engine) {
94
1
    _download_thread = std::thread(&CloudWarmUpManager::handle_jobs, this);
95
1
    static_cast<void>(ThreadPoolBuilder("CloudWarmUpManagerThreadPool")
96
1
                              .set_min_threads(1)
97
1
                              .set_max_threads(config::warm_up_manager_thread_pool_size)
98
1
                              .build(&_thread_pool));
99
1
    _thread_pool_token = _thread_pool->new_token(ThreadPool::ExecutionMode::CONCURRENT);
100
1
}
101
102
0
CloudWarmUpManager::~CloudWarmUpManager() {
103
0
    {
104
0
        std::lock_guard lock(_mtx);
105
0
        _closed = true;
106
0
    }
107
0
    _cond.notify_all();
108
0
    if (_download_thread.joinable()) {
109
0
        _download_thread.join();
110
0
    }
111
112
0
    for (auto& shard : _balanced_tablets_shards) {
113
0
        std::lock_guard<std::mutex> lock(shard.mtx);
114
0
        shard.tablets.clear();
115
0
    }
116
0
}
117
118
0
std::unordered_map<std::string, RowsetMetaSharedPtr> snapshot_rs_metas(BaseTablet* tablet) {
119
0
    std::unordered_map<std::string, RowsetMetaSharedPtr> id_to_rowset_meta_map;
120
0
    auto visitor = [&id_to_rowset_meta_map](const RowsetSharedPtr& r) {
121
0
        id_to_rowset_meta_map.emplace(r->rowset_meta()->rowset_id().to_string(), r->rowset_meta());
122
0
    };
123
0
    constexpr bool include_stale = false;
124
0
    tablet->traverse_rowsets(visitor, include_stale);
125
0
    return id_to_rowset_meta_map;
126
0
}
127
128
void CloudWarmUpManager::submit_download_tasks(io::Path path, int64_t file_size,
129
                                               io::FileSystemSPtr file_system,
130
                                               int64_t expiration_time,
131
                                               std::shared_ptr<bthread::CountdownEvent> wait,
132
                                               bool is_index, std::function<void(Status)> done_cb,
133
0
                                               int64_t tablet_id) {
134
0
    VLOG_DEBUG << "submit warm up task for file: " << path << ", file_size: " << file_size
135
0
               << ", expiration_time: " << expiration_time
136
0
               << ", is_index: " << (is_index ? "true" : "false");
137
0
    if (file_size < 0) {
138
0
        auto st = file_system->file_size(path, &file_size);
139
0
        if (!st.ok()) [[unlikely]] {
140
0
            LOG(WARNING) << "get file size failed: " << path;
141
0
            file_cache_warm_up_failed_task_num << 1;
142
0
            return;
143
0
        }
144
0
    }
145
0
    if (is_index) {
146
0
        g_file_cache_once_or_periodic_warm_up_submitted_index_num << 1;
147
0
        g_file_cache_once_or_periodic_warm_up_submitted_index_size << file_size;
148
0
    } else {
149
0
        g_file_cache_once_or_periodic_warm_up_submitted_segment_num << 1;
150
0
        g_file_cache_once_or_periodic_warm_up_submitted_segment_size << file_size;
151
0
    }
152
153
0
    const int64_t chunk_size = 10 * 1024 * 1024; // 10MB
154
0
    int64_t offset = 0;
155
0
    int64_t remaining_size = file_size;
156
157
0
    while (remaining_size > 0) {
158
0
        int64_t current_chunk_size = std::min(chunk_size, remaining_size);
159
0
        wait->add_count();
160
161
0
        _engine.file_cache_block_downloader().submit_download_task(io::DownloadFileMeta {
162
0
                .path = path,
163
0
                .file_size = file_size,
164
0
                .offset = offset,
165
0
                .download_size = current_chunk_size,
166
0
                .file_system = file_system,
167
0
                .ctx = {.expiration_time = expiration_time,
168
0
                        .is_dryrun = config::enable_reader_dryrun_when_download_file_cache,
169
0
                        .is_warmup = true},
170
0
                .download_done =
171
0
                        [=, done_cb = std::move(done_cb)](Status st) {
172
0
                            if (done_cb) done_cb(st);
173
0
                            if (!st) {
174
0
                                LOG_WARNING("Warm up error ").error(st);
175
0
                            } else if (is_index) {
176
0
                                g_file_cache_once_or_periodic_warm_up_finished_index_num
177
0
                                        << (offset == 0 ? 1 : 0);
178
0
                                g_file_cache_once_or_periodic_warm_up_finished_index_size
179
0
                                        << current_chunk_size;
180
0
                            } else {
181
0
                                g_file_cache_once_or_periodic_warm_up_finished_segment_num
182
0
                                        << (offset == 0 ? 1 : 0);
183
0
                                g_file_cache_once_or_periodic_warm_up_finished_segment_size
184
0
                                        << current_chunk_size;
185
0
                            }
186
0
                            wait->signal();
187
0
                        },
188
0
                .tablet_id = tablet_id,
189
0
        });
190
191
0
        offset += current_chunk_size;
192
0
        remaining_size -= current_chunk_size;
193
0
    }
194
0
}
195
196
1
void CloudWarmUpManager::handle_jobs() {
197
1
#ifndef BE_TEST
198
1
    constexpr int WAIT_TIME_SECONDS = 600;
199
2
    while (true) {
200
1
        std::shared_ptr<JobMeta> cur_job = nullptr;
201
1
        {
202
1
            std::unique_lock lock(_mtx);
203
2
            while (!_closed && _pending_job_metas.empty()) {
204
1
                _cond.wait(lock);
205
1
            }
206
1
            if (_closed) break;
207
1
            if (!_pending_job_metas.empty()) {
208
0
                cur_job = _pending_job_metas.front();
209
0
            }
210
1
        }
211
212
1
        if (!cur_job) {
213
0
            LOG_WARNING("Warm up job is null");
214
0
            continue;
215
0
        }
216
217
1
        std::shared_ptr<bthread::CountdownEvent> wait =
218
1
                std::make_shared<bthread::CountdownEvent>(0);
219
220
1
        for (int64_t tablet_id : cur_job->tablet_ids) {
221
0
            VLOG_DEBUG << "Warm up tablet " << tablet_id << " stack: " << get_stack_trace();
222
0
            if (_cur_job_id == 0) { // The job is canceled
223
0
                break;
224
0
            }
225
0
            auto res = _engine.tablet_mgr().get_tablet(tablet_id);
226
0
            if (!res.has_value()) {
227
0
                LOG_WARNING("Warm up error ").tag("tablet_id", tablet_id).error(res.error());
228
0
                continue;
229
0
            }
230
0
            auto tablet = res.value();
231
0
            auto st = tablet->sync_rowsets();
232
0
            if (!st) {
233
0
                LOG_WARNING("Warm up error ").tag("tablet_id", tablet_id).error(st);
234
0
                continue;
235
0
            }
236
237
0
            auto tablet_meta = tablet->tablet_meta();
238
0
            auto rs_metas = snapshot_rs_metas(tablet.get());
239
0
            for (auto& [_, rs] : rs_metas) {
240
0
                auto storage_resource = rs->remote_storage_resource();
241
0
                if (!storage_resource) {
242
0
                    LOG(WARNING) << storage_resource.error();
243
0
                    continue;
244
0
                }
245
246
0
                int64_t expiration_time = tablet_meta->ttl_seconds();
247
0
                if (!tablet->add_rowset_warmup_state(*rs, WarmUpTriggerSource::JOB)) {
248
0
                    LOG(INFO) << "found duplicate warmup task for rowset " << rs->rowset_id()
249
0
                              << ", skip it";
250
0
                    continue;
251
0
                }
252
0
                for (int64_t seg_id = 0; seg_id < rs->num_segments(); seg_id++) {
253
                    // 1st. download segment files
254
                    // Use rs->fs() instead of storage_resource.value()->fs to support packed
255
                    // files. PackedFileSystem wrapper in RowsetMeta::fs() handles the index_map
256
                    // lookup and reads from the correct packed file.
257
0
                    if (!config::file_cache_enable_only_warm_up_idx) {
258
0
                        submit_download_tasks(
259
0
                                storage_resource.value()->remote_segment_path(*rs, seg_id),
260
0
                                rs->segment_file_size(cast_set<int>(seg_id)), rs->fs(),
261
0
                                expiration_time, wait, false,
262
0
                                [tablet, rs, seg_id](Status st) {
263
0
                                    VLOG_DEBUG << "warmup rowset " << rs->version() << " segment "
264
0
                                               << seg_id << " completed";
265
0
                                    if (tablet->complete_rowset_segment_warmup(
266
0
                                                      WarmUpTriggerSource::JOB, rs->rowset_id(), st,
267
0
                                                      1, 0)
268
0
                                                .trigger_source == WarmUpTriggerSource::JOB) {
269
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
270
0
                                                   << " completed";
271
0
                                    }
272
0
                                },
273
0
                                tablet_id);
274
0
                    }
275
276
                    // 2nd. download inverted index files
277
0
                    int64_t file_size = -1;
278
0
                    auto schema_ptr = rs->tablet_schema();
279
0
                    auto idx_version = schema_ptr->get_inverted_index_storage_format();
280
0
                    const auto& idx_file_info = rs->inverted_index_file_info(cast_set<int>(seg_id));
281
0
                    if (idx_version == InvertedIndexStorageFormatPB::V1) {
282
0
                        auto&& inverted_index_info =
283
0
                                rs->inverted_index_file_info(cast_set<int>(seg_id));
284
0
                        std::unordered_map<int64_t, int64_t> index_size_map;
285
0
                        for (const auto& info : inverted_index_info.index_info()) {
286
0
                            if (info.index_file_size() != -1) {
287
0
                                index_size_map[info.index_id()] = info.index_file_size();
288
0
                            } else {
289
0
                                VLOG_DEBUG << "Invalid index_file_size for segment_id " << seg_id
290
0
                                           << ", index_id " << info.index_id();
291
0
                            }
292
0
                        }
293
0
                        for (const auto& index : schema_ptr->inverted_indexes()) {
294
0
                            auto idx_path = storage_resource.value()->remote_idx_v1_path(
295
0
                                    *rs, seg_id, index->index_id(), index->get_index_suffix());
296
0
                            if (idx_file_info.index_info_size() > 0) {
297
0
                                for (const auto& idx_info : idx_file_info.index_info()) {
298
0
                                    if (index->index_id() == idx_info.index_id() &&
299
0
                                        index->get_index_suffix() == idx_info.index_suffix()) {
300
0
                                        file_size = idx_info.index_file_size();
301
0
                                        break;
302
0
                                    }
303
0
                                }
304
0
                            }
305
0
                            tablet->update_rowset_warmup_state_inverted_idx_num(
306
0
                                    WarmUpTriggerSource::JOB, rs->rowset_id(), 1);
307
0
                            submit_download_tasks(
308
0
                                    idx_path, file_size, rs->fs(), expiration_time, wait, true,
309
0
                                    [=](Status st) {
310
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
311
0
                                                   << " segment " << seg_id
312
0
                                                   << "inverted idx:" << idx_path << " completed";
313
0
                                        if (tablet->complete_rowset_segment_warmup(
314
0
                                                          WarmUpTriggerSource::JOB, rs->rowset_id(),
315
0
                                                          st, 0, 1)
316
0
                                                    .trigger_source == WarmUpTriggerSource::JOB) {
317
0
                                            VLOG_DEBUG << "warmup rowset " << rs->version()
318
0
                                                       << " completed";
319
0
                                        }
320
0
                                    },
321
0
                                    tablet_id);
322
0
                        }
323
0
                    } else {
324
0
                        if (schema_ptr->has_inverted_index() || schema_ptr->has_ann_index()) {
325
0
                            auto idx_path =
326
0
                                    storage_resource.value()->remote_idx_v2_path(*rs, seg_id);
327
0
                            file_size = idx_file_info.has_index_size() ? idx_file_info.index_size()
328
0
                                                                       : -1;
329
0
                            tablet->update_rowset_warmup_state_inverted_idx_num(
330
0
                                    WarmUpTriggerSource::JOB, rs->rowset_id(), 1);
331
0
                            submit_download_tasks(
332
0
                                    idx_path, file_size, rs->fs(), expiration_time, wait, true,
333
0
                                    [=](Status st) {
334
0
                                        VLOG_DEBUG << "warmup rowset " << rs->version()
335
0
                                                   << " segment " << seg_id
336
0
                                                   << "inverted idx:" << idx_path << " completed";
337
0
                                        if (tablet->complete_rowset_segment_warmup(
338
0
                                                          WarmUpTriggerSource::JOB, rs->rowset_id(),
339
0
                                                          st, 0, 1)
340
0
                                                    .trigger_source == WarmUpTriggerSource::JOB) {
341
0
                                            VLOG_DEBUG << "warmup rowset " << rs->version()
342
0
                                                       << " completed";
343
0
                                        }
344
0
                                    },
345
0
                                    tablet_id);
346
0
                        }
347
0
                    }
348
0
                }
349
0
            }
350
0
            g_file_cache_once_or_periodic_warm_up_finished_tablet_num << 1;
351
0
        }
352
353
1
        timespec time;
354
1
        time.tv_sec = UnixSeconds() + WAIT_TIME_SECONDS;
355
1
        if (wait->timed_wait(time)) {
356
0
            LOG_WARNING("Warm up {} tablets take a long time", cur_job->tablet_ids.size());
357
0
        }
358
1
        {
359
1
            std::unique_lock lock(_mtx);
360
1
            _finish_job.push_back(cur_job);
361
            // _pending_job_metas may be cleared by a CLEAR_JOB request
362
            // so we need to check it again.
363
1
            if (!_pending_job_metas.empty()) {
364
                // We can not call pop_front before the job is finished,
365
                // because GET_CURRENT_JOB_STATE_AND_LEASE is relying on the pending job size.
366
0
                _pending_job_metas.pop_front();
367
0
            }
368
1
        }
369
1
    }
370
1
#endif
371
1
}
372
373
JobMeta::JobMeta(const TJobMeta& meta)
374
0
        : be_ip(meta.be_ip), brpc_port(meta.brpc_port), tablet_ids(meta.tablet_ids) {
375
0
    switch (meta.download_type) {
376
0
    case TDownloadType::BE:
377
0
        download_type = DownloadType::BE;
378
0
        break;
379
0
    case TDownloadType::S3:
380
0
        download_type = DownloadType::S3;
381
0
        break;
382
0
    }
383
0
}
384
385
0
Status CloudWarmUpManager::check_and_set_job_id(int64_t job_id) {
386
0
    std::lock_guard lock(_mtx);
387
0
    if (_cur_job_id == 0) {
388
0
        _cur_job_id = job_id;
389
0
    }
390
0
    Status st = Status::OK();
391
0
    if (_cur_job_id != job_id) {
392
0
        st = Status::InternalError("The job {} is running", _cur_job_id);
393
0
    }
394
0
    return st;
395
0
}
396
397
0
Status CloudWarmUpManager::check_and_set_batch_id(int64_t job_id, int64_t batch_id, bool* retry) {
398
0
    std::lock_guard lock(_mtx);
399
0
    Status st = Status::OK();
400
0
    if (_cur_job_id != 0 && _cur_job_id != job_id) {
401
0
        st = Status::InternalError("The job {} is not current job, current job is {}", job_id,
402
0
                                   _cur_job_id);
403
0
        return st;
404
0
    }
405
0
    if (_cur_job_id == 0) {
406
0
        _cur_job_id = job_id;
407
0
    }
408
0
    if (_cur_batch_id == batch_id) {
409
0
        *retry = true;
410
0
        return st;
411
0
    }
412
0
    if (_pending_job_metas.empty()) {
413
0
        _cur_batch_id = batch_id;
414
0
    } else {
415
0
        st = Status::InternalError("The batch {} is not finish", _cur_batch_id);
416
0
    }
417
0
    return st;
418
0
}
419
420
0
void CloudWarmUpManager::add_job(const std::vector<TJobMeta>& job_metas) {
421
0
    {
422
0
        std::lock_guard lock(_mtx);
423
0
        std::for_each(job_metas.begin(), job_metas.end(), [this](const TJobMeta& meta) {
424
0
            _pending_job_metas.emplace_back(std::make_shared<JobMeta>(meta));
425
0
            g_file_cache_once_or_periodic_warm_up_submitted_tablet_num << meta.tablet_ids.size();
426
0
        });
427
0
    }
428
0
    _cond.notify_all();
429
0
}
430
431
#ifdef BE_TEST
432
void CloudWarmUpManager::consumer_job() {
433
    {
434
        std::unique_lock lock(_mtx);
435
        _finish_job.push_back(_pending_job_metas.front());
436
        _pending_job_metas.pop_front();
437
    }
438
}
439
440
#endif
441
442
0
std::tuple<int64_t, int64_t, int64_t, int64_t> CloudWarmUpManager::get_current_job_state() {
443
0
    std::lock_guard lock(_mtx);
444
0
    return std::make_tuple(_cur_job_id, _cur_batch_id, _pending_job_metas.size(),
445
0
                           _finish_job.size());
446
0
}
447
448
0
Status CloudWarmUpManager::clear_job(int64_t job_id) {
449
0
    std::lock_guard lock(_mtx);
450
0
    Status st = Status::OK();
451
0
    if (job_id == _cur_job_id) {
452
0
        _cur_job_id = 0;
453
0
        _cur_batch_id = -1;
454
0
        _pending_job_metas.clear();
455
0
        _finish_job.clear();
456
0
    } else {
457
0
        st = Status::InternalError("The job {} is not current job, current job is {}", job_id,
458
0
                                   _cur_job_id);
459
0
    }
460
0
    return st;
461
0
}
462
463
0
Status CloudWarmUpManager::set_event(int64_t job_id, TWarmUpEventType::type event, bool clear) {
464
0
    DBUG_EXECUTE_IF("CloudWarmUpManager.set_event.ignore_all", {
465
0
        LOG(INFO) << "Ignore set_event request, job_id=" << job_id << ", event=" << event
466
0
                  << ", clear=" << clear;
467
0
        return Status::OK();
468
0
    });
469
0
    std::lock_guard lock(_mtx);
470
0
    Status st = Status::OK();
471
0
    if (event == TWarmUpEventType::type::LOAD) {
472
0
        if (clear) {
473
0
            _tablet_replica_cache.erase(job_id);
474
0
            LOG(INFO) << "Clear event driven sync, job_id=" << job_id << ", event=" << event;
475
0
        } else if (!_tablet_replica_cache.contains(job_id)) {
476
0
            static_cast<void>(_tablet_replica_cache[job_id]);
477
0
            LOG(INFO) << "Set event driven sync, job_id=" << job_id << ", event=" << event;
478
0
        }
479
0
    } else {
480
0
        st = Status::InternalError("The event {} is not supported yet", event);
481
0
    }
482
0
    return st;
483
0
}
484
485
std::vector<TReplicaInfo> CloudWarmUpManager::get_replica_info(int64_t tablet_id, bool bypass_cache,
486
206k
                                                               bool& cache_hit) {
487
206k
    std::vector<TReplicaInfo> replicas;
488
206k
    std::vector<int64_t> cancelled_jobs;
489
206k
    std::lock_guard<std::mutex> lock(_mtx);
490
206k
    cache_hit = false;
491
206k
    for (auto& [job_id, cache] : _tablet_replica_cache) {
492
0
        if (!bypass_cache) {
493
0
            auto it = cache.find(tablet_id);
494
0
            if (it != cache.end()) {
495
                // check ttl expire
496
0
                auto now = std::chrono::steady_clock::now();
497
0
                auto sec = std::chrono::duration_cast<std::chrono::seconds>(now - it->second.first);
498
0
                if (sec.count() < config::warmup_tablet_replica_info_cache_ttl_sec) {
499
0
                    replicas.push_back(it->second.second);
500
0
                    LOG(INFO) << "get_replica_info: cache hit, tablet_id=" << tablet_id
501
0
                              << ", job_id=" << job_id;
502
0
                    cache_hit = true;
503
0
                    continue;
504
0
                } else {
505
0
                    LOG(INFO) << "get_replica_info: cache expired, tablet_id=" << tablet_id
506
0
                              << ", job_id=" << job_id;
507
0
                    cache.erase(it);
508
0
                }
509
0
            }
510
0
            LOG(INFO) << "get_replica_info: cache miss, tablet_id=" << tablet_id
511
0
                      << ", job_id=" << job_id;
512
0
        }
513
514
0
        if (!cache_hit) {
515
            // We are trying to save one retry by refresh all the remaining caches
516
0
            bypass_cache = true;
517
0
        }
518
0
        ClusterInfo* cluster_info = ExecEnv::GetInstance()->cluster_info();
519
0
        if (cluster_info == nullptr) {
520
0
            LOG(WARNING) << "get_replica_info: have not get FE Master heartbeat yet, job_id="
521
0
                         << job_id;
522
0
            continue;
523
0
        }
524
0
        TNetworkAddress master_addr = cluster_info->master_fe_addr;
525
0
        if (master_addr.hostname == "" || master_addr.port == 0) {
526
0
            LOG(WARNING) << "get_replica_info: have not get FE Master heartbeat yet, job_id="
527
0
                         << job_id;
528
0
            continue;
529
0
        }
530
531
0
        TGetTabletReplicaInfosRequest request;
532
0
        TGetTabletReplicaInfosResult result;
533
0
        request.warm_up_job_id = job_id;
534
0
        request.__isset.warm_up_job_id = true;
535
0
        request.tablet_ids.emplace_back(tablet_id);
536
0
        Status rpc_st = ThriftRpcHelper::rpc<FrontendServiceClient>(
537
0
                master_addr.hostname, master_addr.port,
538
0
                [&request, &result](FrontendServiceConnection& client) {
539
0
                    client->getTabletReplicaInfos(result, request);
540
0
                });
541
542
0
        if (!rpc_st.ok()) {
543
0
            LOG(WARNING) << "get_replica_info: rpc failed error=" << rpc_st
544
0
                         << ", tablet id=" << tablet_id << ", job_id=" << job_id;
545
0
            continue;
546
0
        }
547
548
0
        auto st = Status::create(result.status);
549
0
        if (!st.ok()) {
550
0
            if (st.is<CANCELED>()) {
551
0
                LOG(INFO) << "get_replica_info: warm up job cancelled, tablet_id=" << tablet_id
552
0
                          << ", job_id=" << job_id;
553
0
                cancelled_jobs.push_back(job_id);
554
0
            } else {
555
0
                LOG(WARNING) << "get_replica_info: failed status=" << st
556
0
                             << ", tablet id=" << tablet_id << ", job_id=" << job_id;
557
0
            }
558
0
            continue;
559
0
        }
560
0
        VLOG_DEBUG << "get_replica_info: got " << result.tablet_replica_infos.size()
561
0
                   << " tablets, tablet id=" << tablet_id << ", job_id=" << job_id;
562
563
0
        for (const auto& it : result.tablet_replica_infos) {
564
0
            auto tid = it.first;
565
0
            VLOG_DEBUG << "get_replica_info: got " << it.second.size()
566
0
                       << " replica_infos, tablet id=" << tid << ", job_id=" << job_id;
567
0
            for (const auto& replica : it.second) {
568
0
                cache[tid] = std::make_pair(std::chrono::steady_clock::now(), replica);
569
0
                replicas.push_back(replica);
570
0
                LOG(INFO) << "get_replica_info: cache add, tablet_id=" << tid
571
0
                          << ", job_id=" << job_id;
572
0
            }
573
0
        }
574
0
    }
575
206k
    for (auto job_id : cancelled_jobs) {
576
0
        LOG(INFO) << "get_replica_info: erasing cancelled job, job_id=" << job_id;
577
0
        _tablet_replica_cache.erase(job_id);
578
0
    }
579
18.4E
    VLOG_DEBUG << "get_replica_info: return " << replicas.size()
580
18.4E
               << " replicas, tablet id=" << tablet_id;
581
206k
    return replicas;
582
206k
}
583
584
200k
void CloudWarmUpManager::warm_up_rowset(RowsetMeta& rs_meta, int64_t sync_wait_timeout_ms) {
585
200k
    bthread::Mutex mu;
586
200k
    bthread::ConditionVariable cv;
587
200k
    std::unique_lock<bthread::Mutex> lock(mu);
588
200k
    auto st = _thread_pool_token->submit_func([&, this]() {
589
200k
        std::unique_lock<bthread::Mutex> l(mu);
590
200k
        _warm_up_rowset(rs_meta, sync_wait_timeout_ms);
591
200k
        cv.notify_one();
592
200k
    });
593
200k
    if (!st.ok()) {
594
0
        LOG(WARNING) << "Failed to submit warm up rowset task: " << st;
595
0
        file_cache_warm_up_failed_task_num << 1;
596
200k
    } else {
597
200k
        cv.wait(lock);
598
200k
    }
599
200k
}
600
601
200k
void CloudWarmUpManager::_warm_up_rowset(RowsetMeta& rs_meta, int64_t sync_wait_timeout_ms) {
602
200k
    bool cache_hit = false;
603
200k
    auto replicas = get_replica_info(rs_meta.tablet_id(), false, cache_hit);
604
200k
    if (replicas.empty()) {
605
200k
        VLOG_DEBUG << "There is no need to warmup tablet=" << rs_meta.tablet_id()
606
0
                   << ", skipping rowset=" << rs_meta.rowset_id().to_string();
607
200k
        g_file_cache_event_driven_warm_up_skipped_rowset_num << 1;
608
200k
        return;
609
200k
    }
610
18.4E
    Status st = _do_warm_up_rowset(rs_meta, replicas, sync_wait_timeout_ms, !cache_hit);
611
18.4E
    if (cache_hit && !st.ok() && st.is<ErrorCode::TABLE_NOT_FOUND>()) {
612
0
        replicas = get_replica_info(rs_meta.tablet_id(), true, cache_hit);
613
0
        st = _do_warm_up_rowset(rs_meta, replicas, sync_wait_timeout_ms, true);
614
0
    }
615
18.4E
    if (!st.ok()) {
616
0
        LOG(WARNING) << "Failed to warm up rowset, tablet_id=" << rs_meta.tablet_id()
617
0
                     << ", rowset_id=" << rs_meta.rowset_id().to_string() << ", status=" << st;
618
0
    }
619
18.4E
}
620
621
Status CloudWarmUpManager::_do_warm_up_rowset(RowsetMeta& rs_meta,
622
                                              std::vector<TReplicaInfo>& replicas,
623
                                              int64_t sync_wait_timeout_ms,
624
0
                                              bool skip_existence_check) {
625
0
    auto tablet_id = rs_meta.tablet_id();
626
0
    int64_t now_ts = std::chrono::duration_cast<std::chrono::microseconds>(
627
0
                             std::chrono::system_clock::now().time_since_epoch())
628
0
                             .count();
629
0
    g_file_cache_warm_up_rowset_last_call_unix_ts.set_value(now_ts);
630
0
    auto ret_st = Status::OK();
631
632
0
    PWarmUpRowsetRequest request;
633
0
    request.add_rowset_metas()->CopyFrom(rs_meta.get_rowset_pb());
634
0
    request.set_unix_ts_us(now_ts);
635
0
    request.set_sync_wait_timeout_ms(sync_wait_timeout_ms);
636
0
    request.set_skip_existence_check(skip_existence_check);
637
0
    for (auto& replica : replicas) {
638
        // send sync request
639
0
        std::string host = replica.host;
640
0
        auto dns_cache = ExecEnv::GetInstance()->dns_cache();
641
0
        if (dns_cache == nullptr) {
642
0
            LOG(WARNING) << "DNS cache is not initialized, skipping hostname resolve";
643
0
        } else if (!is_valid_ip(replica.host)) {
644
0
            Status status = dns_cache->get(replica.host, &host);
645
0
            if (!status.ok()) {
646
0
                LOG(WARNING) << "failed to get ip from host " << replica.host << ": "
647
0
                             << status.to_string();
648
0
                continue;
649
0
            }
650
0
        }
651
0
        std::string brpc_addr = get_host_port(host, replica.brpc_port);
652
0
        Status st = Status::OK();
653
0
        std::shared_ptr<PBackendService_Stub> brpc_stub =
654
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->get_new_client_no_cache(
655
0
                        brpc_addr);
656
0
        if (!brpc_stub) {
657
0
            st = Status::RpcError("Address {} is wrong", brpc_addr);
658
0
            continue;
659
0
        }
660
661
        // update metrics
662
0
        auto schema_ptr = rs_meta.tablet_schema();
663
0
        auto idx_version = schema_ptr->get_inverted_index_storage_format();
664
0
        for (int64_t segment_id = 0; segment_id < rs_meta.num_segments(); segment_id++) {
665
0
            g_file_cache_event_driven_warm_up_requested_segment_num << 1;
666
0
            g_file_cache_event_driven_warm_up_requested_segment_size
667
0
                    << rs_meta.segment_file_size(cast_set<int>(segment_id));
668
669
0
            if (schema_ptr->has_inverted_index() || schema_ptr->has_ann_index()) {
670
0
                if (idx_version == InvertedIndexStorageFormatPB::V1) {
671
0
                    auto&& inverted_index_info =
672
0
                            rs_meta.inverted_index_file_info(cast_set<int>(segment_id));
673
0
                    if (inverted_index_info.index_info().empty()) {
674
0
                        VLOG_DEBUG << "No index info available for segment " << segment_id;
675
0
                        continue;
676
0
                    }
677
0
                    for (const auto& info : inverted_index_info.index_info()) {
678
0
                        g_file_cache_event_driven_warm_up_requested_index_num << 1;
679
0
                        if (info.index_file_size() != -1) {
680
0
                            g_file_cache_event_driven_warm_up_requested_index_size
681
0
                                    << info.index_file_size();
682
0
                        } else {
683
0
                            VLOG_DEBUG << "Invalid index_file_size for segment_id " << segment_id
684
0
                                       << ", index_id " << info.index_id();
685
0
                        }
686
0
                    }
687
0
                } else { // InvertedIndexStorageFormatPB::V2
688
0
                    auto&& inverted_index_info =
689
0
                            rs_meta.inverted_index_file_info(cast_set<int>(segment_id));
690
0
                    g_file_cache_event_driven_warm_up_requested_index_num << 1;
691
0
                    if (inverted_index_info.has_index_size()) {
692
0
                        g_file_cache_event_driven_warm_up_requested_index_size
693
0
                                << inverted_index_info.index_size();
694
0
                    } else {
695
0
                        VLOG_DEBUG << "index_size is not set for segment " << segment_id;
696
0
                    }
697
0
                }
698
0
            }
699
0
        }
700
701
0
        brpc::Controller cntl;
702
0
        if (sync_wait_timeout_ms > 0) {
703
0
            cntl.set_timeout_ms(sync_wait_timeout_ms + 1000);
704
0
        }
705
0
        PWarmUpRowsetResponse response;
706
0
        MonotonicStopWatch watch;
707
0
        watch.start();
708
0
        brpc_stub->warm_up_rowset(&cntl, &request, &response, nullptr);
709
0
        if (cntl.Failed()) {
710
0
            LOG_WARNING("warm up rowset {} for tablet {} failed, rpc error: {}",
711
0
                        rs_meta.rowset_id().to_string(), tablet_id, cntl.ErrorText());
712
0
            return Status::RpcError(cntl.ErrorText());
713
0
        }
714
0
        if (sync_wait_timeout_ms > 0) {
715
0
            auto cost_us = watch.elapsed_time_microseconds();
716
0
            VLOG_DEBUG << "warm up rowset wait for compaction: " << cost_us << " us";
717
0
            if (cost_us / 1000 > sync_wait_timeout_ms) {
718
0
                LOG_WARNING(
719
0
                        "Warm up rowset {} for tabelt {} wait for compaction timeout, takes {} ms",
720
0
                        rs_meta.rowset_id().to_string(), tablet_id, cost_us / 1000);
721
0
            }
722
0
            g_file_cache_warm_up_rowset_wait_for_compaction_latency << cost_us;
723
0
        }
724
0
        auto status = Status::create(response.status());
725
0
        if (response.has_status() && !status.ok()) {
726
0
            LOG(INFO) << "warm_up_rowset failed, tablet_id=" << rs_meta.tablet_id()
727
0
                      << ", rowset_id=" << rs_meta.rowset_id().to_string()
728
0
                      << ", target=" << replica.host << ", skip_existence_check"
729
0
                      << skip_existence_check << ", status=" << status;
730
0
            ret_st = status;
731
0
        }
732
0
    }
733
0
    return ret_st;
734
0
}
735
736
void CloudWarmUpManager::recycle_cache(int64_t tablet_id,
737
6.37k
                                       const std::vector<RecycledRowsets>& rowsets) {
738
6.37k
    bthread::Mutex mu;
739
6.37k
    bthread::ConditionVariable cv;
740
6.37k
    std::unique_lock<bthread::Mutex> lock(mu);
741
6.37k
    auto st = _thread_pool_token->submit_func([&, this]() {
742
6.37k
        std::unique_lock<bthread::Mutex> l(mu);
743
6.37k
        _recycle_cache(tablet_id, rowsets);
744
6.37k
        cv.notify_one();
745
6.37k
    });
746
6.37k
    if (!st.ok()) {
747
0
        LOG(WARNING) << "Failed to submit recycle cache task, tablet_id=" << tablet_id
748
0
                     << ", error=" << st;
749
6.37k
    } else {
750
6.37k
        cv.wait(lock);
751
6.37k
    }
752
6.37k
}
753
754
void CloudWarmUpManager::_recycle_cache(int64_t tablet_id,
755
6.37k
                                        const std::vector<RecycledRowsets>& rowsets) {
756
6.37k
    LOG(INFO) << "recycle_cache: tablet_id=" << tablet_id << ", num_rowsets=" << rowsets.size();
757
6.37k
    bool cache_hit = false;
758
6.37k
    auto replicas = get_replica_info(tablet_id, false, cache_hit);
759
6.37k
    if (replicas.empty()) {
760
6.37k
        return;
761
6.37k
    }
762
763
0
    PRecycleCacheRequest request;
764
0
    for (const auto& rowset : rowsets) {
765
0
        RecycleCacheMeta* meta = request.add_cache_metas();
766
0
        meta->set_tablet_id(tablet_id);
767
0
        meta->set_rowset_id(rowset.rowset_id.to_string());
768
0
        meta->set_num_segments(rowset.num_segments);
769
0
        for (const auto& name : rowset.index_file_names) {
770
0
            meta->add_index_file_names(name);
771
0
        }
772
0
        g_file_cache_recycle_cache_requested_segment_num << rowset.num_segments;
773
0
        g_file_cache_recycle_cache_requested_index_num << rowset.index_file_names.size();
774
0
    }
775
0
    auto dns_cache = ExecEnv::GetInstance()->dns_cache();
776
0
    for (auto& replica : replicas) {
777
        // send sync request
778
0
        std::string host = replica.host;
779
0
        if (dns_cache == nullptr) {
780
0
            LOG(WARNING) << "DNS cache is not initialized, skipping hostname resolve";
781
0
        } else if (!is_valid_ip(replica.host)) {
782
0
            Status status = dns_cache->get(replica.host, &host);
783
0
            if (!status.ok()) {
784
0
                LOG(WARNING) << "failed to get ip from host " << replica.host << ": "
785
0
                             << status.to_string();
786
0
                return;
787
0
            }
788
0
        }
789
0
        std::string brpc_addr = get_host_port(host, replica.brpc_port);
790
0
        Status st = Status::OK();
791
0
        std::shared_ptr<PBackendService_Stub> brpc_stub =
792
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->get_new_client_no_cache(
793
0
                        brpc_addr);
794
0
        if (!brpc_stub) {
795
0
            st = Status::RpcError("Address {} is wrong", brpc_addr);
796
0
            continue;
797
0
        }
798
0
        brpc::Controller cntl;
799
0
        PRecycleCacheResponse response;
800
0
        brpc_stub->recycle_cache(&cntl, &request, &response, nullptr);
801
0
    }
802
0
}
803
804
// Balance warm up cache management methods implementation
805
void CloudWarmUpManager::record_balanced_tablet(int64_t tablet_id, const std::string& host,
806
0
                                                int32_t brpc_port) {
807
0
    auto& shard = get_shard(tablet_id);
808
0
    std::lock_guard<std::mutex> lock(shard.mtx);
809
0
    JobMeta meta;
810
0
    meta.be_ip = host;
811
0
    meta.brpc_port = brpc_port;
812
0
    shard.tablets.emplace(tablet_id, std::move(meta));
813
0
    g_balance_tablet_be_mapping_size << 1;
814
0
    schedule_remove_balanced_tablet(tablet_id);
815
0
    VLOG_DEBUG << "Recorded balanced warm up cache tablet: tablet_id=" << tablet_id
816
0
               << ", host=" << host << ":" << brpc_port;
817
0
}
818
819
0
void CloudWarmUpManager::schedule_remove_balanced_tablet(int64_t tablet_id) {
820
    // Use std::make_unique to avoid raw pointer allocation
821
0
    auto tablet_id_ptr = std::make_unique<int64_t>(tablet_id);
822
0
    unsigned long expired_ms = g_tablet_report_inactive_duration_ms;
823
0
    if (doris::config::cache_read_from_peer_expired_seconds > 0 &&
824
0
        doris::config::cache_read_from_peer_expired_seconds <=
825
0
                g_tablet_report_inactive_duration_ms / 1000) {
826
0
        expired_ms = doris::config::cache_read_from_peer_expired_seconds * 1000;
827
0
    }
828
0
    bthread_timer_t timer_id;
829
    // ATTN: The timer callback will reclaim ownership of the tablet_id_ptr, so we need to release it after the timer is added.
830
0
    if (const int rc = bthread_timer_add(&timer_id, butil::milliseconds_from_now(expired_ms),
831
0
                                         clean_up_expired_mappings, tablet_id_ptr.get());
832
0
        rc == 0) {
833
0
        tablet_id_ptr.release();
834
0
    } else {
835
0
        LOG(WARNING) << "Fail to add timer for clean up expired mappings for tablet_id="
836
0
                     << tablet_id << " rc=" << rc;
837
0
    }
838
0
}
839
840
0
void CloudWarmUpManager::clean_up_expired_mappings(void* arg) {
841
0
    std::unique_ptr<int64_t> tid(static_cast<int64_t*>(arg));
842
0
    auto& manager = ExecEnv::GetInstance()->storage_engine().to_cloud().cloud_warm_up_manager();
843
0
    manager.remove_balanced_tablet(*tid);
844
0
    VLOG_DEBUG << "Removed expired balanced warm up cache tablet: tablet_id=" << *tid;
845
0
}
846
847
std::optional<std::pair<std::string, int32_t>> CloudWarmUpManager::get_balanced_tablet_info(
848
40.2k
        int64_t tablet_id) {
849
40.2k
    auto& shard = get_shard(tablet_id);
850
40.2k
    std::lock_guard<std::mutex> lock(shard.mtx);
851
40.2k
    auto it = shard.tablets.find(tablet_id);
852
40.2k
    if (it == shard.tablets.end()) {
853
40.2k
        return std::nullopt;
854
40.2k
    }
855
18.4E
    return std::make_pair(it->second.be_ip, it->second.brpc_port);
856
40.2k
}
857
858
0
void CloudWarmUpManager::remove_balanced_tablet(int64_t tablet_id) {
859
0
    auto& shard = get_shard(tablet_id);
860
0
    std::lock_guard<std::mutex> lock(shard.mtx);
861
0
    auto it = shard.tablets.find(tablet_id);
862
0
    if (it != shard.tablets.end()) {
863
0
        shard.tablets.erase(it);
864
0
        g_balance_tablet_be_mapping_size << -1;
865
0
        VLOG_DEBUG << "Removed balanced warm up cache tablet by timer, tablet_id=" << tablet_id;
866
0
    }
867
0
}
868
869
0
void CloudWarmUpManager::remove_balanced_tablets(const std::vector<int64_t>& tablet_ids) {
870
    // Group tablet_ids by shard to minimize lock contention
871
0
    std::array<std::vector<int64_t>, SHARD_COUNT> shard_groups;
872
0
    for (int64_t tablet_id : tablet_ids) {
873
0
        shard_groups[get_shard_index(tablet_id)].push_back(tablet_id);
874
0
    }
875
876
    // Process each shard
877
0
    for (size_t i = 0; i < SHARD_COUNT; ++i) {
878
0
        if (shard_groups[i].empty()) continue;
879
880
0
        auto& shard = _balanced_tablets_shards[i];
881
0
        std::lock_guard<std::mutex> lock(shard.mtx);
882
0
        for (int64_t tablet_id : shard_groups[i]) {
883
0
            auto it = shard.tablets.find(tablet_id);
884
0
            if (it != shard.tablets.end()) {
885
0
                shard.tablets.erase(it);
886
0
                g_balance_tablet_be_mapping_size << -1;
887
0
                VLOG_DEBUG << "Removed balanced warm up cache tablet: tablet_id=" << tablet_id;
888
0
            }
889
0
        }
890
0
    }
891
0
}
892
893
std::unordered_map<int64_t, std::pair<std::string, int32_t>>
894
0
CloudWarmUpManager::get_all_balanced_tablets() const {
895
0
    std::unordered_map<int64_t, std::pair<std::string, int32_t>> result;
896
897
    // Lock all shards to get consistent snapshot
898
0
    std::array<std::unique_lock<std::mutex>, SHARD_COUNT> locks;
899
0
    for (size_t i = 0; i < SHARD_COUNT; ++i) {
900
0
        locks[i] = std::unique_lock<std::mutex>(_balanced_tablets_shards[i].mtx);
901
0
    }
902
903
0
    for (const auto& shard : _balanced_tablets_shards) {
904
0
        for (const auto& [tablet_id, entry] : shard.tablets) {
905
0
            result.emplace(tablet_id, std::make_pair(entry.be_ip, entry.brpc_port));
906
0
        }
907
0
    }
908
0
    return result;
909
0
}
910
911
#include "common/compile_check_end.h"
912
} // namespace doris