Coverage Report

Created: 2026-04-10 04:05

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