Coverage Report

Created: 2026-03-18 11:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/cache/block_file_cache.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
// This file is copied from
18
// https://github.com/ClickHouse/ClickHouse/blob/master/src/Interpreters/Cache/FileCache.cpp
19
// and modified by Doris
20
21
#include "io/cache/block_file_cache.h"
22
23
#include <gen_cpp/file_cache.pb.h>
24
25
#include <cstdio>
26
#include <exception>
27
#include <fstream>
28
#include <unordered_set>
29
30
#include "common/status.h"
31
#include "cpp/sync_point.h"
32
#include "runtime/exec_env.h"
33
34
#if defined(__APPLE__)
35
#include <sys/mount.h>
36
#else
37
#include <sys/statfs.h>
38
#endif
39
40
#include <chrono> // IWYU pragma: keep
41
#include <mutex>
42
#include <ranges>
43
44
#include "common/cast_set.h"
45
#include "common/config.h"
46
#include "common/logging.h"
47
#include "core/uint128.h"
48
#include "exec/common/sip_hash.h"
49
#include "io/cache/block_file_cache_ttl_mgr.h"
50
#include "io/cache/file_block.h"
51
#include "io/cache/file_cache_common.h"
52
#include "io/cache/fs_file_cache_storage.h"
53
#include "io/cache/mem_file_cache_storage.h"
54
#include "runtime/runtime_profile.h"
55
#include "util/concurrency_stats.h"
56
#include "util/stack_util.h"
57
#include "util/stopwatch.hpp"
58
#include "util/thread.h"
59
#include "util/time.h"
60
namespace doris::io {
61
#include "common/compile_check_begin.h"
62
63
// Insert a block pointer into one shard while swallowing allocation failures.
64
9.55k
bool NeedUpdateLRUBlocks::insert(FileBlockSPtr block) {
65
9.55k
    if (!block) {
66
1
        return false;
67
1
    }
68
9.55k
    try {
69
9.55k
        auto* raw_ptr = block.get();
70
9.55k
        auto idx = shard_index(raw_ptr);
71
9.55k
        auto& shard = _shards[idx];
72
9.55k
        std::lock_guard lock(shard.mutex);
73
9.55k
        auto [_, inserted] = shard.entries.emplace(raw_ptr, std::move(block));
74
9.55k
        if (inserted) {
75
1.02k
            _size.fetch_add(1, std::memory_order_relaxed);
76
1.02k
        }
77
9.55k
        return inserted;
78
9.55k
    } catch (const std::exception& e) {
79
0
        LOG(WARNING) << "Failed to enqueue block for LRU update: " << e.what();
80
0
    } catch (...) {
81
0
        LOG(WARNING) << "Failed to enqueue block for LRU update: unknown error";
82
0
    }
83
0
    return false;
84
9.55k
}
85
86
// Drain up to `limit` unique blocks to the caller, keeping the structure consistent on failures.
87
5.78k
size_t NeedUpdateLRUBlocks::drain(size_t limit, std::vector<FileBlockSPtr>* output) {
88
5.78k
    if (limit == 0 || output == nullptr) {
89
2
        return 0;
90
2
    }
91
5.77k
    size_t drained = 0;
92
5.77k
    try {
93
5.77k
        output->reserve(output->size() + std::min(limit, size()));
94
371k
        for (auto& shard : _shards) {
95
371k
            if (drained >= limit) {
96
1
                break;
97
1
            }
98
371k
            std::lock_guard lock(shard.mutex);
99
371k
            auto it = shard.entries.begin();
100
371k
            size_t shard_drained = 0;
101
372k
            while (it != shard.entries.end() && drained + shard_drained < limit) {
102
487
                output->emplace_back(std::move(it->second));
103
487
                it = shard.entries.erase(it);
104
487
                ++shard_drained;
105
487
            }
106
371k
            if (shard_drained > 0) {
107
6
                _size.fetch_sub(shard_drained, std::memory_order_relaxed);
108
6
                drained += shard_drained;
109
6
            }
110
371k
        }
111
5.77k
    } catch (const std::exception& e) {
112
0
        LOG(WARNING) << "Failed to drain LRU update blocks: " << e.what();
113
0
    } catch (...) {
114
0
        LOG(WARNING) << "Failed to drain LRU update blocks: unknown error";
115
0
    }
116
5.81k
    return drained;
117
5.77k
}
118
119
// Remove every pending block, guarding against unexpected exceptions.
120
32
void NeedUpdateLRUBlocks::clear() {
121
32
    try {
122
2.04k
        for (auto& shard : _shards) {
123
2.04k
            std::lock_guard lock(shard.mutex);
124
2.04k
            if (!shard.entries.empty()) {
125
1
                auto removed = shard.entries.size();
126
1
                shard.entries.clear();
127
1
                _size.fetch_sub(removed, std::memory_order_relaxed);
128
1
            }
129
2.04k
        }
130
32
    } catch (const std::exception& e) {
131
0
        LOG(WARNING) << "Failed to clear LRU update blocks: " << e.what();
132
0
    } catch (...) {
133
0
        LOG(WARNING) << "Failed to clear LRU update blocks: unknown error";
134
0
    }
135
32
}
136
137
9.54k
size_t NeedUpdateLRUBlocks::shard_index(FileBlock* ptr) const {
138
9.54k
    DCHECK(ptr != nullptr);
139
9.54k
    return std::hash<FileBlock*> {}(ptr)&kShardMask;
140
9.54k
}
141
142
BlockFileCache::BlockFileCache(const std::string& cache_base_path,
143
                               const FileCacheSettings& cache_settings)
144
166
        : _cache_base_path(cache_base_path),
145
166
          _capacity(cache_settings.capacity),
146
166
          _max_file_block_size(cache_settings.max_file_block_size) {
147
166
    _cur_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(_cache_base_path.c_str(),
148
166
                                                                     "file_cache_cache_size", 0);
149
166
    _cache_capacity_metrics = std::make_shared<bvar::Status<size_t>>(
150
166
            _cache_base_path.c_str(), "file_cache_capacity", _capacity);
151
166
    _cur_ttl_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
152
166
            _cache_base_path.c_str(), "file_cache_ttl_cache_size", 0);
153
166
    _cur_normal_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
154
166
            _cache_base_path.c_str(), "file_cache_normal_queue_element_count", 0);
155
166
    _cur_ttl_cache_lru_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
156
166
            _cache_base_path.c_str(), "file_cache_ttl_cache_lru_queue_size", 0);
157
166
    _cur_ttl_cache_lru_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
158
166
            _cache_base_path.c_str(), "file_cache_ttl_cache_lru_queue_element_count", 0);
159
166
    _cur_normal_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
160
166
            _cache_base_path.c_str(), "file_cache_normal_queue_cache_size", 0);
161
166
    _cur_index_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
162
166
            _cache_base_path.c_str(), "file_cache_index_queue_element_count", 0);
163
166
    _cur_index_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
164
166
            _cache_base_path.c_str(), "file_cache_index_queue_cache_size", 0);
165
166
    _cur_disposable_queue_element_count_metrics = std::make_shared<bvar::Status<size_t>>(
166
166
            _cache_base_path.c_str(), "file_cache_disposable_queue_element_count", 0);
167
166
    _cur_disposable_queue_cache_size_metrics = std::make_shared<bvar::Status<size_t>>(
168
166
            _cache_base_path.c_str(), "file_cache_disposable_queue_cache_size", 0);
169
170
166
    _queue_evict_size_metrics[0] = std::make_shared<bvar::Adder<size_t>>(
171
166
            _cache_base_path.c_str(), "file_cache_index_queue_evict_size");
172
166
    _queue_evict_size_metrics[1] = std::make_shared<bvar::Adder<size_t>>(
173
166
            _cache_base_path.c_str(), "file_cache_normal_queue_evict_size");
174
166
    _queue_evict_size_metrics[2] = std::make_shared<bvar::Adder<size_t>>(
175
166
            _cache_base_path.c_str(), "file_cache_disposable_queue_evict_size");
176
166
    _queue_evict_size_metrics[3] = std::make_shared<bvar::Adder<size_t>>(
177
166
            _cache_base_path.c_str(), "file_cache_ttl_cache_evict_size");
178
166
    _total_evict_size_metrics = std::make_shared<bvar::Adder<size_t>>(
179
166
            _cache_base_path.c_str(), "file_cache_total_evict_size");
180
166
    _total_read_size_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
181
166
                                                                     "file_cache_total_read_size");
182
166
    _total_hit_size_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
183
166
                                                                    "file_cache_total_hit_size");
184
166
    _gc_evict_bytes_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
185
166
                                                                    "file_cache_gc_evict_bytes");
186
166
    _gc_evict_count_metrics = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
187
166
                                                                    "file_cache_gc_evict_count");
188
189
166
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::NORMAL] =
190
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
191
166
                                                  "file_cache_evict_by_time_disposable_to_normal");
192
166
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::INDEX] =
193
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
194
166
                                                  "file_cache_evict_by_time_disposable_to_index");
195
166
    _evict_by_time_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::TTL] =
196
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
197
166
                                                  "file_cache_evict_by_time_disposable_to_ttl");
198
166
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::DISPOSABLE] =
199
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
200
166
                                                  "file_cache_evict_by_time_normal_to_disposable");
201
166
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::INDEX] =
202
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
203
166
                                                  "file_cache_evict_by_time_normal_to_index");
204
166
    _evict_by_time_metrics_matrix[FileCacheType::NORMAL][FileCacheType::TTL] =
205
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
206
166
                                                  "file_cache_evict_by_time_normal_to_ttl");
207
166
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::DISPOSABLE] =
208
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
209
166
                                                  "file_cache_evict_by_time_index_to_disposable");
210
166
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::NORMAL] =
211
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
212
166
                                                  "file_cache_evict_by_time_index_to_normal");
213
166
    _evict_by_time_metrics_matrix[FileCacheType::INDEX][FileCacheType::TTL] =
214
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
215
166
                                                  "file_cache_evict_by_time_index_to_ttl");
216
166
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::DISPOSABLE] =
217
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
218
166
                                                  "file_cache_evict_by_time_ttl_to_disposable");
219
166
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::NORMAL] =
220
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
221
166
                                                  "file_cache_evict_by_time_ttl_to_normal");
222
166
    _evict_by_time_metrics_matrix[FileCacheType::TTL][FileCacheType::INDEX] =
223
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
224
166
                                                  "file_cache_evict_by_time_ttl_to_index");
225
226
166
    _evict_by_self_lru_metrics_matrix[FileCacheType::DISPOSABLE] =
227
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
228
166
                                                  "file_cache_evict_by_self_lru_disposable");
229
166
    _evict_by_self_lru_metrics_matrix[FileCacheType::NORMAL] =
230
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
231
166
                                                  "file_cache_evict_by_self_lru_normal");
232
166
    _evict_by_self_lru_metrics_matrix[FileCacheType::INDEX] = std::make_shared<bvar::Adder<size_t>>(
233
166
            _cache_base_path.c_str(), "file_cache_evict_by_self_lru_index");
234
166
    _evict_by_self_lru_metrics_matrix[FileCacheType::TTL] = std::make_shared<bvar::Adder<size_t>>(
235
166
            _cache_base_path.c_str(), "file_cache_evict_by_self_lru_ttl");
236
237
166
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::NORMAL] =
238
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
239
166
                                                  "file_cache_evict_by_size_disposable_to_normal");
240
166
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::INDEX] =
241
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
242
166
                                                  "file_cache_evict_by_size_disposable_to_index");
243
166
    _evict_by_size_metrics_matrix[FileCacheType::DISPOSABLE][FileCacheType::TTL] =
244
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
245
166
                                                  "file_cache_evict_by_size_disposable_to_ttl");
246
166
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::DISPOSABLE] =
247
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
248
166
                                                  "file_cache_evict_by_size_normal_to_disposable");
249
166
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::INDEX] =
250
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
251
166
                                                  "file_cache_evict_by_size_normal_to_index");
252
166
    _evict_by_size_metrics_matrix[FileCacheType::NORMAL][FileCacheType::TTL] =
253
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
254
166
                                                  "file_cache_evict_by_size_normal_to_ttl");
255
166
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::DISPOSABLE] =
256
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
257
166
                                                  "file_cache_evict_by_size_index_to_disposable");
258
166
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::NORMAL] =
259
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
260
166
                                                  "file_cache_evict_by_size_index_to_normal");
261
166
    _evict_by_size_metrics_matrix[FileCacheType::INDEX][FileCacheType::TTL] =
262
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
263
166
                                                  "file_cache_evict_by_size_index_to_ttl");
264
166
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::DISPOSABLE] =
265
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
266
166
                                                  "file_cache_evict_by_size_ttl_to_disposable");
267
166
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::NORMAL] =
268
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
269
166
                                                  "file_cache_evict_by_size_ttl_to_normal");
270
166
    _evict_by_size_metrics_matrix[FileCacheType::TTL][FileCacheType::INDEX] =
271
166
            std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
272
166
                                                  "file_cache_evict_by_size_ttl_to_index");
273
274
166
    _evict_by_try_release = std::make_shared<bvar::Adder<size_t>>(
275
166
            _cache_base_path.c_str(), "file_cache_evict_by_try_release");
276
277
166
    _num_read_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
278
166
                                                             "file_cache_num_read_blocks");
279
166
    _num_hit_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
280
166
                                                            "file_cache_num_hit_blocks");
281
166
    _num_removed_blocks = std::make_shared<bvar::Adder<size_t>>(_cache_base_path.c_str(),
282
166
                                                                "file_cache_num_removed_blocks");
283
284
166
    _no_warmup_num_read_blocks = std::make_shared<bvar::Adder<size_t>>(
285
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks");
286
166
    _no_warmup_num_hit_blocks = std::make_shared<bvar::Adder<size_t>>(
287
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks");
288
289
166
#ifndef BE_TEST
290
166
    _num_hit_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
291
166
            _cache_base_path.c_str(), "file_cache_num_hit_blocks_5m", _num_hit_blocks.get(), 300);
292
166
    _num_read_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
293
166
            _cache_base_path.c_str(), "file_cache_num_read_blocks_5m", _num_read_blocks.get(), 300);
294
166
    _num_hit_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
295
166
            _cache_base_path.c_str(), "file_cache_num_hit_blocks_1h", _num_hit_blocks.get(), 3600);
296
166
    _num_read_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
297
166
            _cache_base_path.c_str(), "file_cache_num_read_blocks_1h", _num_read_blocks.get(),
298
166
            3600);
299
166
    _no_warmup_num_hit_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
300
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks_5m",
301
166
            _no_warmup_num_hit_blocks.get(), 300);
302
166
    _no_warmup_num_read_blocks_5m = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
303
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks_5m",
304
166
            _no_warmup_num_read_blocks.get(), 300);
305
166
    _no_warmup_num_hit_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
306
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_hit_blocks_1h",
307
166
            _no_warmup_num_hit_blocks.get(), 3600);
308
166
    _no_warmup_num_read_blocks_1h = std::make_shared<bvar::Window<bvar::Adder<size_t>>>(
309
166
            _cache_base_path.c_str(), "file_cache_no_warmup_num_read_blocks_1h",
310
166
            _no_warmup_num_read_blocks.get(), 3600);
311
166
#endif
312
313
166
    _hit_ratio = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
314
166
                                                        "file_cache_hit_ratio", 0.0);
315
166
    _hit_ratio_5m = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
316
166
                                                           "file_cache_hit_ratio_5m", 0.0);
317
166
    _hit_ratio_1h = std::make_shared<bvar::Status<double>>(_cache_base_path.c_str(),
318
166
                                                           "file_cache_hit_ratio_1h", 0.0);
319
320
166
    _no_warmup_hit_ratio = std::make_shared<bvar::Status<double>>(
321
166
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio", 0.0);
322
166
    _no_warmup_hit_ratio_5m = std::make_shared<bvar::Status<double>>(
323
166
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio_5m", 0.0);
324
166
    _no_warmup_hit_ratio_1h = std::make_shared<bvar::Status<double>>(
325
166
            _cache_base_path.c_str(), "file_cache_no_warmup_hit_ratio_1h", 0.0);
326
327
166
    _disk_limit_mode_metrics = std::make_shared<bvar::Status<size_t>>(
328
166
            _cache_base_path.c_str(), "file_cache_disk_limit_mode", 0);
329
166
    _need_evict_cache_in_advance_metrics = std::make_shared<bvar::Status<size_t>>(
330
166
            _cache_base_path.c_str(), "file_cache_need_evict_cache_in_advance", 0);
331
166
    _meta_store_write_queue_size_metrics = std::make_shared<bvar::Status<size_t>>(
332
166
            _cache_base_path.c_str(), "file_cache_meta_store_write_queue_size", 0);
333
334
166
    _cache_lock_wait_time_us = std::make_shared<bvar::LatencyRecorder>(
335
166
            _cache_base_path.c_str(), "file_cache_cache_lock_wait_time_us");
336
166
    _get_or_set_latency_us = std::make_shared<bvar::LatencyRecorder>(
337
166
            _cache_base_path.c_str(), "file_cache_get_or_set_latency_us");
338
166
    _storage_sync_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
339
166
            _cache_base_path.c_str(), "file_cache_storage_sync_remove_latency_us");
340
166
    _storage_retry_sync_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
341
166
            _cache_base_path.c_str(), "file_cache_storage_retry_sync_remove_latency_us");
342
166
    _storage_async_remove_latency_us = std::make_shared<bvar::LatencyRecorder>(
343
166
            _cache_base_path.c_str(), "file_cache_storage_async_remove_latency_us");
344
166
    _evict_in_advance_latency_us = std::make_shared<bvar::LatencyRecorder>(
345
166
            _cache_base_path.c_str(), "file_cache_evict_in_advance_latency_us");
346
166
    _lru_dump_latency_us = std::make_shared<bvar::LatencyRecorder>(
347
166
            _cache_base_path.c_str(), "file_cache_lru_dump_latency_us");
348
166
    _recycle_keys_length_recorder = std::make_shared<bvar::LatencyRecorder>(
349
166
            _cache_base_path.c_str(), "file_cache_recycle_keys_length");
350
166
    _need_update_lru_blocks_length_recorder = std::make_shared<bvar::LatencyRecorder>(
351
166
            _cache_base_path.c_str(), "file_cache_need_update_lru_blocks_length");
352
166
    _update_lru_blocks_latency_us = std::make_shared<bvar::LatencyRecorder>(
353
166
            _cache_base_path.c_str(), "file_cache_update_lru_blocks_latency_us");
354
166
    _ttl_gc_latency_us = std::make_shared<bvar::LatencyRecorder>(_cache_base_path.c_str(),
355
166
                                                                 "file_cache_ttl_gc_latency_us");
356
166
    _shadow_queue_levenshtein_distance = std::make_shared<bvar::LatencyRecorder>(
357
166
            _cache_base_path.c_str(), "file_cache_shadow_queue_levenshtein_distance");
358
359
166
    _disposable_queue = LRUQueue(cache_settings.disposable_queue_size,
360
166
                                 cache_settings.disposable_queue_elements, 60 * 60);
361
166
    _index_queue = LRUQueue(cache_settings.index_queue_size, cache_settings.index_queue_elements,
362
166
                            7 * 24 * 60 * 60);
363
166
    _normal_queue = LRUQueue(cache_settings.query_queue_size, cache_settings.query_queue_elements,
364
166
                             24 * 60 * 60);
365
166
    _ttl_queue = LRUQueue(cache_settings.ttl_queue_size, cache_settings.ttl_queue_elements,
366
166
                          std::numeric_limits<int>::max());
367
368
166
    _lru_recorder = std::make_unique<LRUQueueRecorder>(this);
369
166
    _lru_dumper = std::make_unique<CacheLRUDumper>(this, _lru_recorder.get());
370
166
    if (cache_settings.storage == "memory") {
371
18
        _storage = std::make_unique<MemFileCacheStorage>();
372
18
        _cache_base_path = "memory";
373
148
    } else {
374
148
        _storage = std::make_unique<FSFileCacheStorage>();
375
148
    }
376
377
166
    LOG(INFO) << "file cache path= " << _cache_base_path << " " << cache_settings.to_string();
378
166
}
379
380
2.17M
UInt128Wrapper BlockFileCache::hash(const std::string& path) {
381
2.17M
    uint128_t value;
382
2.17M
    sip_hash128(path.data(), path.size(), reinterpret_cast<char*>(&value));
383
2.17M
    return UInt128Wrapper(value);
384
2.17M
}
385
386
BlockFileCache::QueryFileCacheContextHolderPtr BlockFileCache::get_query_context_holder(
387
8
        const TUniqueId& query_id, int file_cache_query_limit_percent) {
388
8
    SCOPED_CACHE_LOCK(_mutex, this);
389
8
    if (!config::enable_file_cache_query_limit) {
390
1
        return {};
391
1
    }
392
393
    /// if enable_filesystem_query_cache_limit is true,
394
    /// we create context query for current query.
395
7
    auto context = get_or_set_query_context(query_id, cache_lock, file_cache_query_limit_percent);
396
7
    return std::make_unique<QueryFileCacheContextHolder>(query_id, this, context);
397
8
}
398
399
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_query_context(
400
5.56k
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock) {
401
5.56k
    auto query_iter = _query_map.find(query_id);
402
5.56k
    return (query_iter == _query_map.end()) ? nullptr : query_iter->second;
403
5.56k
}
404
405
6
void BlockFileCache::remove_query_context(const TUniqueId& query_id) {
406
6
    SCOPED_CACHE_LOCK(_mutex, this);
407
6
    const auto& query_iter = _query_map.find(query_id);
408
409
6
    if (query_iter != _query_map.end() && query_iter->second.use_count() <= 1) {
410
5
        _query_map.erase(query_iter);
411
5
    }
412
6
}
413
414
BlockFileCache::QueryFileCacheContextPtr BlockFileCache::get_or_set_query_context(
415
        const TUniqueId& query_id, std::lock_guard<std::mutex>& cache_lock,
416
7
        int file_cache_query_limit_percent) {
417
7
    if (query_id.lo == 0 && query_id.hi == 0) {
418
1
        return nullptr;
419
1
    }
420
421
6
    auto context = get_query_context(query_id, cache_lock);
422
6
    if (context) {
423
1
        return context;
424
1
    }
425
426
5
    size_t file_cache_query_limit_size = _capacity * file_cache_query_limit_percent / 100;
427
5
    if (file_cache_query_limit_size < 268435456) {
428
5
        LOG(WARNING) << "The user-set file cache query limit (" << file_cache_query_limit_size
429
5
                     << " bytes) is less than the 256MB recommended minimum. "
430
5
                     << "Consider increasing the session variable 'file_cache_query_limit_percent'"
431
5
                     << " from its current value " << file_cache_query_limit_percent << "%.";
432
5
    }
433
5
    auto query_context = std::make_shared<QueryFileCacheContext>(file_cache_query_limit_size);
434
5
    auto query_iter = _query_map.emplace(query_id, query_context).first;
435
5
    return query_iter->second;
436
6
}
437
438
void BlockFileCache::QueryFileCacheContext::remove(const UInt128Wrapper& hash, size_t offset,
439
20
                                                   std::lock_guard<std::mutex>& cache_lock) {
440
20
    auto pair = std::make_pair(hash, offset);
441
20
    auto record = records.find(pair);
442
20
    DCHECK(record != records.end());
443
20
    auto iter = record->second;
444
20
    records.erase(pair);
445
20
    lru_queue.remove(iter, cache_lock);
446
20
}
447
448
void BlockFileCache::QueryFileCacheContext::reserve(const UInt128Wrapper& hash, size_t offset,
449
                                                    size_t size,
450
30
                                                    std::lock_guard<std::mutex>& cache_lock) {
451
30
    auto pair = std::make_pair(hash, offset);
452
30
    if (records.find(pair) == records.end()) {
453
29
        auto queue_iter = lru_queue.add(hash, offset, size, cache_lock);
454
29
        records.insert({pair, queue_iter});
455
29
    }
456
30
}
457
458
145
Status BlockFileCache::initialize() {
459
145
    SCOPED_CACHE_LOCK(_mutex, this);
460
145
    return initialize_unlocked(cache_lock);
461
145
}
462
463
145
Status BlockFileCache::initialize_unlocked(std::lock_guard<std::mutex>& cache_lock) {
464
145
    DCHECK(!_is_initialized);
465
145
    _is_initialized = true;
466
145
    if (config::file_cache_background_lru_dump_tail_record_num > 0) {
467
        // requirements:
468
        // 1. restored data should not overwrite the last dump
469
        // 2. restore should happen before load and async load
470
        // 3. all queues should be restored sequencially to avoid conflict
471
        // TODO(zhengyu): we can parralize them but will increase complexity, so lets check the time cost
472
        // to see if any improvement is a necessary
473
145
        restore_lru_queues_from_disk(cache_lock);
474
145
    }
475
145
    RETURN_IF_ERROR(_storage->init(this));
476
477
145
    if (auto* fs_storage = dynamic_cast<FSFileCacheStorage*>(_storage.get())) {
478
129
        if (auto* meta_store = fs_storage->get_meta_store()) {
479
129
            _ttl_mgr = std::make_unique<BlockFileCacheTtlMgr>(this, meta_store);
480
129
        }
481
129
    }
482
483
145
    _cache_background_monitor_thread = std::thread(&BlockFileCache::run_background_monitor, this);
484
145
    _cache_background_gc_thread = std::thread(&BlockFileCache::run_background_gc, this);
485
145
    _cache_background_evict_in_advance_thread =
486
145
            std::thread(&BlockFileCache::run_background_evict_in_advance, this);
487
145
    _cache_background_block_lru_update_thread =
488
145
            std::thread(&BlockFileCache::run_background_block_lru_update, this);
489
490
    // Initialize LRU dump thread and restore queues
491
145
    _cache_background_lru_dump_thread = std::thread(&BlockFileCache::run_background_lru_dump, this);
492
145
    _cache_background_lru_log_replay_thread =
493
145
            std::thread(&BlockFileCache::run_background_lru_log_replay, this);
494
495
145
    return Status::OK();
496
145
}
497
498
void BlockFileCache::update_block_lru(FileBlockSPtr block,
499
484
                                      std::lock_guard<std::mutex>& cache_lock) {
500
484
    if (!block) {
501
1
        return;
502
1
    }
503
504
483
    FileBlockCell* cell = get_cell(block->get_hash_value(), block->offset(), cache_lock);
505
483
    if (!cell || cell->file_block.get() != block.get()) {
506
1
        return;
507
1
    }
508
509
482
    if (cell->queue_iterator) {
510
482
        auto& queue = get_queue(block->cache_type());
511
482
        queue.move_to_end(*cell->queue_iterator, cache_lock);
512
482
        _lru_recorder->record_queue_event(block->cache_type(), CacheLRULogType::MOVETOBACK,
513
482
                                          block->_key.hash, block->_key.offset,
514
482
                                          block->_block_range.size());
515
482
    }
516
482
    cell->update_atime();
517
482
}
518
519
void BlockFileCache::use_cell(const FileBlockCell& cell, FileBlocks* result, bool move_iter_flag,
520
25.0M
                              std::lock_guard<std::mutex>& cache_lock) {
521
25.0M
    if (result) {
522
25.0M
        result->push_back(cell.file_block);
523
25.0M
    }
524
525
25.0M
    auto& queue = get_queue(cell.file_block->cache_type());
526
    /// Move to the end of the queue. The iterator remains valid.
527
25.0M
    if (cell.queue_iterator && move_iter_flag) {
528
24.1M
        queue.move_to_end(*cell.queue_iterator, cache_lock);
529
24.1M
        _lru_recorder->record_queue_event(cell.file_block->cache_type(),
530
24.1M
                                          CacheLRULogType::MOVETOBACK, cell.file_block->_key.hash,
531
24.1M
                                          cell.file_block->_key.offset, cell.size());
532
24.1M
    }
533
534
25.0M
    cell.update_atime();
535
25.0M
}
536
537
template <class T>
538
    requires IsXLock<T>
539
FileBlockCell* BlockFileCache::get_cell(const UInt128Wrapper& hash, size_t offset,
540
733k
                                        T& /* cache_lock */) {
541
733k
    auto it = _files.find(hash);
542
733k
    if (it == _files.end()) {
543
2
        return nullptr;
544
2
    }
545
546
733k
    auto& offsets = it->second;
547
733k
    auto cell_it = offsets.find(offset);
548
733k
    if (cell_it == offsets.end()) {
549
3
        return nullptr;
550
3
    }
551
552
733k
    return &cell_it->second;
553
733k
}
554
555
25.0M
bool BlockFileCache::need_to_move(FileCacheType cell_type, FileCacheType query_type) const {
556
25.0M
    return query_type != FileCacheType::DISPOSABLE && cell_type != FileCacheType::DISPOSABLE;
557
25.0M
}
558
559
FileBlocks BlockFileCache::get_impl(const UInt128Wrapper& hash, const CacheContext& context,
560
                                    const FileBlock::Range& range,
561
25.1M
                                    std::lock_guard<std::mutex>& cache_lock) {
562
    /// Given range = [left, right] and non-overlapping ordered set of file blocks,
563
    /// find list [block1, ..., blockN] of blocks which intersect with given range.
564
25.1M
    auto it = _files.find(hash);
565
25.1M
    if (it == _files.end()) {
566
118k
        if (_async_open_done) {
567
117k
            return {};
568
117k
        }
569
1.00k
        FileCacheKey key;
570
1.00k
        key.hash = hash;
571
1.00k
        key.meta.type = context.cache_type;
572
1.00k
        key.meta.expiration_time = context.expiration_time;
573
1.00k
        key.meta.tablet_id = context.tablet_id;
574
1.00k
        _storage->load_blocks_directly_unlocked(this, key, cache_lock);
575
576
1.00k
        it = _files.find(hash);
577
1.00k
        if (it == _files.end()) [[unlikely]] {
578
1.00k
            return {};
579
1.00k
        }
580
1.00k
    }
581
582
25.0M
    auto& file_blocks = it->second;
583
25.0M
    if (file_blocks.empty()) {
584
0
        LOG(WARNING) << "file_blocks is empty for hash=" << hash.to_string()
585
0
                     << " cache type=" << context.cache_type
586
0
                     << " cache expiration time=" << context.expiration_time
587
0
                     << " cache range=" << range.left << " " << range.right
588
0
                     << " query id=" << context.query_id;
589
0
        DCHECK(false);
590
0
        _files.erase(hash);
591
0
        return {};
592
0
    }
593
594
25.0M
    FileBlocks result;
595
25.0M
    auto block_it = file_blocks.lower_bound(range.left);
596
25.0M
    if (block_it == file_blocks.end()) {
597
        /// N - last cached block for given file hash, block{N}.offset < range.left:
598
        ///   block{N}                       block{N}
599
        /// [________                         [_______]
600
        ///     [__________]         OR                  [________]
601
        ///     ^                                        ^
602
        ///     range.left                               range.left
603
604
6.68k
        const auto& cell = file_blocks.rbegin()->second;
605
6.68k
        if (cell.file_block->range().right < range.left) {
606
6.66k
            return {};
607
6.66k
        }
608
609
14
        use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
610
14
                 cache_lock);
611
24.9M
    } else { /// block_it <-- segmment{k}
612
24.9M
        if (block_it != file_blocks.begin()) {
613
97.6k
            const auto& prev_cell = std::prev(block_it)->second;
614
97.6k
            const auto& prev_cell_range = prev_cell.file_block->range();
615
616
97.6k
            if (range.left <= prev_cell_range.right) {
617
                ///   block{k-1}  block{k}
618
                ///   [________]   [_____
619
                ///       [___________
620
                ///       ^
621
                ///       range.left
622
623
137
                use_cell(prev_cell, &result,
624
137
                         need_to_move(prev_cell.file_block->cache_type(), context.cache_type),
625
137
                         cache_lock);
626
137
            }
627
97.6k
        }
628
629
        ///  block{k} ...       block{k-1}  block{k}                      block{k}
630
        ///  [______              [______]     [____                        [________
631
        ///  [_________     OR              [________      OR    [______]   ^
632
        ///  ^                              ^                           ^   block{k}.offset
633
        ///  range.left                     range.left                  range.right
634
635
50.0M
        while (block_it != file_blocks.end()) {
636
25.1M
            const auto& cell = block_it->second;
637
25.1M
            if (range.right < cell.file_block->range().left) {
638
99.1k
                break;
639
99.1k
            }
640
641
25.0M
            use_cell(cell, &result, need_to_move(cell.file_block->cache_type(), context.cache_type),
642
25.0M
                     cache_lock);
643
25.0M
            ++block_it;
644
25.0M
        }
645
24.9M
    }
646
647
24.9M
    return result;
648
25.0M
}
649
650
9.54k
void BlockFileCache::add_need_update_lru_block(FileBlockSPtr block) {
651
9.54k
    if (_need_update_lru_blocks.insert(std::move(block))) {
652
1.01k
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
653
1.01k
    }
654
9.54k
}
655
656
4
std::string BlockFileCache::clear_file_cache_async() {
657
4
    LOG(INFO) << "start clear_file_cache_async, path=" << _cache_base_path;
658
4
    _lru_dumper->remove_lru_dump_files();
659
4
    int64_t num_cells_all = 0;
660
4
    int64_t num_cells_to_delete = 0;
661
4
    int64_t num_cells_wait_recycle = 0;
662
4
    int64_t num_files_all = 0;
663
4
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::clear_file_cache_async");
664
4
    {
665
4
        SCOPED_CACHE_LOCK(_mutex, this);
666
667
4
        std::vector<FileBlockCell*> deleting_cells;
668
4
        for (auto& [_, offset_to_cell] : _files) {
669
4
            ++num_files_all;
670
48
            for (auto& [_1, cell] : offset_to_cell) {
671
48
                ++num_cells_all;
672
48
                deleting_cells.push_back(&cell);
673
48
            }
674
4
        }
675
676
        // we cannot delete the element in the loop above, because it will break the iterator
677
48
        for (auto& cell : deleting_cells) {
678
48
            if (!cell->releasable()) {
679
2
                LOG(INFO) << "cell is not releasable, hash="
680
2
                          << " offset=" << cell->file_block->offset();
681
2
                cell->file_block->set_deleting();
682
2
                ++num_cells_wait_recycle;
683
2
                continue;
684
2
            }
685
46
            FileBlockSPtr file_block = cell->file_block;
686
46
            if (file_block) {
687
46
                std::lock_guard block_lock(file_block->_mutex);
688
46
                remove(file_block, cache_lock, block_lock, false);
689
46
                ++num_cells_to_delete;
690
46
            }
691
46
        }
692
4
        clear_need_update_lru_blocks();
693
4
    }
694
695
4
    std::stringstream ss;
696
4
    ss << "finish clear_file_cache_async, path=" << _cache_base_path
697
4
       << " num_files_all=" << num_files_all << " num_cells_all=" << num_cells_all
698
4
       << " num_cells_to_delete=" << num_cells_to_delete
699
4
       << " num_cells_wait_recycle=" << num_cells_wait_recycle;
700
4
    auto msg = ss.str();
701
4
    LOG(INFO) << msg;
702
4
    _lru_dumper->remove_lru_dump_files();
703
4
    return msg;
704
4
}
705
706
FileBlocks BlockFileCache::split_range_into_cells(const UInt128Wrapper& hash,
707
                                                  const CacheContext& context, size_t offset,
708
                                                  size_t size, FileBlock::State state,
709
127k
                                                  std::lock_guard<std::mutex>& cache_lock) {
710
127k
    DCHECK(size > 0);
711
712
127k
    auto current_pos = offset;
713
127k
    auto end_pos_non_included = offset + size;
714
715
127k
    size_t current_size = 0;
716
127k
    size_t remaining_size = size;
717
718
127k
    FileBlocks file_blocks;
719
488k
    while (current_pos < end_pos_non_included) {
720
361k
        current_size = std::min(remaining_size, _max_file_block_size);
721
361k
        remaining_size -= current_size;
722
361k
        state = try_reserve(hash, context, current_pos, current_size, cache_lock)
723
361k
                        ? state
724
361k
                        : FileBlock::State::SKIP_CACHE;
725
361k
        if (state == FileBlock::State::SKIP_CACHE) [[unlikely]] {
726
3.19k
            FileCacheKey key;
727
3.19k
            key.hash = hash;
728
3.19k
            key.offset = current_pos;
729
3.19k
            key.meta.type = context.cache_type;
730
3.19k
            key.meta.expiration_time = context.expiration_time;
731
3.19k
            key.meta.tablet_id = context.tablet_id;
732
3.19k
            auto file_block = std::make_shared<FileBlock>(key, current_size, this,
733
3.19k
                                                          FileBlock::State::SKIP_CACHE);
734
3.19k
            file_blocks.push_back(std::move(file_block));
735
358k
        } else {
736
358k
            auto* cell = add_cell(hash, context, current_pos, current_size, state, cache_lock);
737
358k
            if (cell) {
738
358k
                file_blocks.push_back(cell->file_block);
739
358k
                if (!context.is_cold_data) {
740
358k
                    cell->update_atime();
741
358k
                }
742
358k
            }
743
358k
            if (_ttl_mgr && context.tablet_id != 0) {
744
351k
                _ttl_mgr->register_tablet_id(context.tablet_id);
745
351k
            }
746
358k
        }
747
748
361k
        current_pos += current_size;
749
361k
    }
750
751
127k
    DCHECK(file_blocks.empty() || offset + size - 1 == file_blocks.back()->range().right);
752
127k
    return file_blocks;
753
127k
}
754
755
void BlockFileCache::fill_holes_with_empty_file_blocks(FileBlocks& file_blocks,
756
                                                       const UInt128Wrapper& hash,
757
                                                       const CacheContext& context,
758
                                                       const FileBlock::Range& range,
759
24.9M
                                                       std::lock_guard<std::mutex>& cache_lock) {
760
    /// There are blocks [block1, ..., blockN]
761
    /// (non-overlapping, non-empty, ascending-ordered) which (maybe partially)
762
    /// intersect with given range.
763
764
    /// It can have holes:
765
    /// [____________________]         -- requested range
766
    ///     [____]  [_]   [_________]  -- intersecting cache [block1, ..., blockN]
767
    ///
768
    /// For each such hole create a cell with file block state EMPTY.
769
770
24.9M
    auto it = file_blocks.begin();
771
24.9M
    auto block_range = (*it)->range();
772
773
24.9M
    size_t current_pos = 0;
774
24.9M
    if (block_range.left < range.left) {
775
        ///    [_______     -- requested range
776
        /// [_______
777
        /// ^
778
        /// block1
779
780
151
        current_pos = block_range.right + 1;
781
151
        ++it;
782
24.9M
    } else {
783
24.9M
        current_pos = range.left;
784
24.9M
    }
785
786
50.0M
    while (current_pos <= range.right && it != file_blocks.end()) {
787
25.0M
        block_range = (*it)->range();
788
789
25.0M
        if (current_pos == block_range.left) {
790
25.0M
            current_pos = block_range.right + 1;
791
25.0M
            ++it;
792
25.0M
            continue;
793
25.0M
        }
794
795
25.0M
        DCHECK(current_pos < block_range.left);
796
797
140
        auto hole_size = block_range.left - current_pos;
798
799
140
        file_blocks.splice(it, split_range_into_cells(hash, context, current_pos, hole_size,
800
140
                                                      FileBlock::State::EMPTY, cache_lock));
801
802
140
        current_pos = block_range.right + 1;
803
140
        ++it;
804
140
    }
805
806
24.9M
    if (current_pos <= range.right) {
807
        ///   ________]     -- requested range
808
        ///   _____]
809
        ///        ^
810
        /// blockN
811
812
241
        auto hole_size = range.right - current_pos + 1;
813
814
241
        file_blocks.splice(file_blocks.end(),
815
241
                           split_range_into_cells(hash, context, current_pos, hole_size,
816
241
                                                  FileBlock::State::EMPTY, cache_lock));
817
241
    }
818
24.9M
}
819
820
FileBlocksHolder BlockFileCache::get_or_set(const UInt128Wrapper& hash, size_t offset, size_t size,
821
24.8M
                                            CacheContext& context) {
822
24.8M
    FileBlock::Range range(offset, offset + size - 1);
823
824
24.8M
    ReadStatistics* stats = context.stats;
825
24.8M
    DCHECK(stats != nullptr);
826
24.8M
    MonotonicStopWatch sw;
827
24.8M
    sw.start();
828
24.8M
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->increment();
829
24.8M
    std::lock_guard cache_lock(_mutex);
830
24.8M
    ConcurrencyStatsManager::instance().cached_remote_reader_get_or_set_wait_lock->decrement();
831
24.8M
    stats->lock_wait_timer += sw.elapsed_time();
832
24.8M
    FileBlocks file_blocks;
833
24.8M
    int64_t duration = 0;
834
24.8M
    {
835
24.8M
        SCOPED_RAW_TIMER(&duration);
836
        /// Get all blocks which intersect with the given range.
837
24.8M
        {
838
24.8M
            SCOPED_RAW_TIMER(&stats->get_timer);
839
24.8M
            file_blocks = get_impl(hash, context, range, cache_lock);
840
24.8M
        }
841
842
24.8M
        if (file_blocks.empty()) {
843
126k
            SCOPED_RAW_TIMER(&stats->set_timer);
844
126k
            file_blocks = split_range_into_cells(hash, context, offset, size,
845
126k
                                                 FileBlock::State::EMPTY, cache_lock);
846
24.7M
        } else {
847
24.7M
            SCOPED_RAW_TIMER(&stats->set_timer);
848
24.7M
            fill_holes_with_empty_file_blocks(file_blocks, hash, context, range, cache_lock);
849
24.7M
        }
850
24.8M
        DCHECK(!file_blocks.empty());
851
24.8M
        *_num_read_blocks << file_blocks.size();
852
25.0M
        if (!context.is_warmup) {
853
25.0M
            *_no_warmup_num_read_blocks << file_blocks.size();
854
25.0M
        }
855
25.4M
        for (auto& block : file_blocks) {
856
25.4M
            size_t block_size = block->range().size();
857
25.4M
            *_total_read_size_metrics << block_size;
858
25.4M
            if (block->state_unsafe() == FileBlock::State::DOWNLOADED) {
859
25.0M
                *_num_hit_blocks << 1;
860
25.0M
                *_total_hit_size_metrics << block_size;
861
25.0M
                if (!context.is_warmup) {
862
24.9M
                    *_no_warmup_num_hit_blocks << 1;
863
24.9M
                }
864
25.0M
            }
865
25.4M
        }
866
24.8M
    }
867
24.8M
    *_get_or_set_latency_us << (duration / 1000);
868
24.8M
    return FileBlocksHolder(std::move(file_blocks));
869
24.8M
}
870
871
FileBlockCell* BlockFileCache::add_cell(const UInt128Wrapper& hash, const CacheContext& context,
872
                                        size_t offset, size_t size, FileBlock::State state,
873
359k
                                        std::lock_guard<std::mutex>& cache_lock) {
874
    /// Create a file block cell and put it in `files` map by [hash][offset].
875
359k
    if (size == 0) {
876
0
        return nullptr; /// Empty files are not cached.
877
0
    }
878
879
359k
    VLOG_DEBUG << "Adding file block to cache. size=" << size << " hash=" << hash.to_string()
880
0
               << " offset=" << offset << " cache_type=" << cache_type_to_string(context.cache_type)
881
0
               << " expiration_time=" << context.expiration_time
882
0
               << " tablet_id=" << context.tablet_id;
883
884
359k
    if (size > 1024 * 1024 * 1024) {
885
0
        LOG(WARNING) << "File block size is too large for a block. size=" << size
886
0
                     << " hash=" << hash.to_string() << " offset=" << offset
887
0
                     << " stack:" << get_stack_trace();
888
0
    }
889
890
359k
    auto& offsets = _files[hash];
891
359k
    auto itr = offsets.find(offset);
892
359k
    if (itr != offsets.end()) {
893
45
        VLOG_DEBUG << "Cache already exists for hash: " << hash.to_string()
894
0
                   << ", offset: " << offset << ", size: " << size
895
0
                   << ".\nCurrent cache structure: " << dump_structure_unlocked(hash, cache_lock);
896
45
        return &(itr->second);
897
45
    }
898
899
359k
    FileCacheKey key;
900
359k
    key.hash = hash;
901
359k
    key.offset = offset;
902
359k
    key.meta.type = context.cache_type;
903
359k
    key.meta.expiration_time = context.expiration_time;
904
359k
    key.meta.tablet_id = context.tablet_id;
905
359k
    FileBlockCell cell(std::make_shared<FileBlock>(key, size, this, state), cache_lock);
906
359k
    Status st;
907
359k
    if (context.expiration_time == 0 && context.cache_type == FileCacheType::TTL) {
908
0
        st = cell.file_block->change_cache_type_lock(FileCacheType::NORMAL, cache_lock);
909
359k
    } else if (context.cache_type != FileCacheType::TTL && context.expiration_time != 0) {
910
1
        st = cell.file_block->change_cache_type_lock(FileCacheType::TTL, cache_lock);
911
1
    }
912
359k
    if (!st.ok()) {
913
0
        LOG(WARNING) << "Cannot change cache type. expiration_time=" << context.expiration_time
914
0
                     << " cache_type=" << cache_type_to_string(context.cache_type)
915
0
                     << " error=" << st.msg();
916
0
    }
917
918
359k
    auto& queue = get_queue(cell.file_block->cache_type());
919
359k
    cell.queue_iterator = queue.add(hash, offset, size, cache_lock);
920
359k
    _lru_recorder->record_queue_event(cell.file_block->cache_type(), CacheLRULogType::ADD,
921
359k
                                      cell.file_block->get_hash_value(), cell.file_block->offset(),
922
359k
                                      cell.size());
923
924
359k
    if (cell.file_block->cache_type() == FileCacheType::TTL) {
925
3.92k
        _cur_ttl_size += cell.size();
926
3.92k
    }
927
359k
    auto [it, _] = offsets.insert(std::make_pair(offset, std::move(cell)));
928
359k
    _cur_cache_size += size;
929
359k
    return &(it->second);
930
359k
}
931
932
0
size_t BlockFileCache::try_release() {
933
0
    SCOPED_CACHE_LOCK(_mutex, this);
934
0
    std::vector<FileBlockCell*> trash;
935
0
    for (auto& [hash, blocks] : _files) {
936
0
        for (auto& [offset, cell] : blocks) {
937
0
            if (cell.releasable()) {
938
0
                trash.emplace_back(&cell);
939
0
            } else {
940
0
                cell.file_block->set_deleting();
941
0
            }
942
0
        }
943
0
    }
944
0
    size_t remove_size = 0;
945
0
    for (auto& cell : trash) {
946
0
        FileBlockSPtr file_block = cell->file_block;
947
0
        std::lock_guard lc(cell->file_block->_mutex);
948
0
        remove_size += file_block->range().size();
949
0
        remove(file_block, cache_lock, lc);
950
0
        VLOG_DEBUG << "try_release " << _cache_base_path
951
0
                   << " hash=" << file_block->get_hash_value().to_string()
952
0
                   << " offset=" << file_block->offset();
953
0
    }
954
0
    *_evict_by_try_release << remove_size;
955
0
    LOG(INFO) << "Released " << trash.size() << " blocks in file cache " << _cache_base_path;
956
0
    return trash.size();
957
0
}
958
959
26.5M
LRUQueue& BlockFileCache::get_queue(FileCacheType type) {
960
26.5M
    switch (type) {
961
17.9M
    case FileCacheType::INDEX:
962
17.9M
        return _index_queue;
963
420k
    case FileCacheType::DISPOSABLE:
964
420k
        return _disposable_queue;
965
8.25M
    case FileCacheType::NORMAL:
966
8.25M
        return _normal_queue;
967
10.9k
    case FileCacheType::TTL:
968
10.9k
        return _ttl_queue;
969
0
    default:
970
0
        DCHECK(false);
971
26.5M
    }
972
0
    return _normal_queue;
973
26.5M
}
974
975
137
const LRUQueue& BlockFileCache::get_queue(FileCacheType type) const {
976
137
    switch (type) {
977
33
    case FileCacheType::INDEX:
978
33
        return _index_queue;
979
1
    case FileCacheType::DISPOSABLE:
980
1
        return _disposable_queue;
981
103
    case FileCacheType::NORMAL:
982
103
        return _normal_queue;
983
0
    case FileCacheType::TTL:
984
0
        return _ttl_queue;
985
0
    default:
986
0
        DCHECK(false);
987
137
    }
988
0
    return _normal_queue;
989
137
}
990
991
void BlockFileCache::remove_file_blocks(std::vector<FileBlockCell*>& to_evict,
992
                                        std::lock_guard<std::mutex>& cache_lock, bool sync,
993
544k
                                        std::string& reason) {
994
544k
    auto remove_file_block_if = [&](FileBlockCell* cell) {
995
115k
        FileBlockSPtr file_block = cell->file_block;
996
115k
        if (file_block) {
997
115k
            std::lock_guard block_lock(file_block->_mutex);
998
115k
            remove(file_block, cache_lock, block_lock, sync);
999
115k
            VLOG_DEBUG << "remove_file_blocks"
1000
0
                       << " hash=" << file_block->get_hash_value().to_string()
1001
0
                       << " offset=" << file_block->offset() << " reason=" << reason;
1002
115k
        }
1003
115k
    };
1004
544k
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1005
544k
}
1006
1007
void BlockFileCache::find_evict_candidates(LRUQueue& queue, size_t size, size_t cur_cache_size,
1008
                                           size_t& removed_size,
1009
                                           std::vector<FileBlockCell*>& to_evict,
1010
                                           std::lock_guard<std::mutex>& cache_lock,
1011
10.4k
                                           size_t& cur_removed_size, bool evict_in_advance) {
1012
313k
    for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1013
313k
        if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1014
4.29k
            break;
1015
4.29k
        }
1016
308k
        auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1017
1018
308k
        DCHECK(cell) << "Cache became inconsistent. key: " << entry_key.to_string()
1019
0
                     << ", offset: " << entry_offset;
1020
1021
308k
        size_t cell_size = cell->size();
1022
308k
        DCHECK(entry_size == cell_size);
1023
1024
308k
        if (cell->releasable()) {
1025
112k
            auto& file_block = cell->file_block;
1026
1027
112k
            std::lock_guard block_lock(file_block->_mutex);
1028
112k
            DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1029
112k
            to_evict.push_back(cell);
1030
112k
            removed_size += cell_size;
1031
112k
            cur_removed_size += cell_size;
1032
112k
        }
1033
308k
    }
1034
10.4k
}
1035
1036
// 1. if async load file cache not finish
1037
//     a. evict from lru queue
1038
// 2. if ttl cache
1039
//     a. evict from disposable/normal/index queue one by one
1040
// 3. if dont reach query limit or dont have query limit
1041
//     a. evict from other queue
1042
//     b. evict from current queue
1043
//         a.1 if the data belong write, then just evict cold data
1044
// 4. if reach query limit
1045
//     a. evict from query queue
1046
//     b. evict from other queue
1047
bool BlockFileCache::try_reserve(const UInt128Wrapper& hash, const CacheContext& context,
1048
                                 size_t offset, size_t size,
1049
361k
                                 std::lock_guard<std::mutex>& cache_lock) {
1050
361k
    if (!_async_open_done) {
1051
1.00k
        return try_reserve_during_async_load(size, cache_lock);
1052
1.00k
    }
1053
    // use this strategy in scenarios where there is insufficient disk capacity or insufficient number of inodes remaining
1054
    // directly eliminate 5 times the size of the space
1055
360k
    if (_disk_resource_limit_mode) {
1056
1
        size = 5 * size;
1057
1
    }
1058
1059
360k
    auto query_context = config::enable_file_cache_query_limit &&
1060
360k
                                         (context.query_id.hi != 0 || context.query_id.lo != 0)
1061
360k
                                 ? get_query_context(context.query_id, cache_lock)
1062
360k
                                 : nullptr;
1063
360k
    if (!query_context) {
1064
360k
        return try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock);
1065
360k
    } else if (query_context->get_cache_size(cache_lock) + size <=
1066
31
               query_context->get_max_cache_size()) {
1067
16
        return try_reserve_for_lru(hash, query_context, context, offset, size, cache_lock);
1068
16
    }
1069
15
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1070
15
                               std::chrono::steady_clock::now().time_since_epoch())
1071
15
                               .count();
1072
15
    auto& queue = get_queue(context.cache_type);
1073
15
    size_t removed_size = 0;
1074
15
    size_t ghost_remove_size = 0;
1075
15
    size_t queue_size = queue.get_capacity(cache_lock);
1076
15
    size_t cur_cache_size = _cur_cache_size;
1077
15
    size_t query_context_cache_size = query_context->get_cache_size(cache_lock);
1078
1079
15
    std::vector<LRUQueue::Iterator> ghost;
1080
15
    std::vector<FileBlockCell*> to_evict;
1081
1082
15
    size_t max_size = queue.get_max_size();
1083
48
    auto is_overflow = [&] {
1084
48
        return _disk_resource_limit_mode ? removed_size < size
1085
48
                                         : cur_cache_size + size - removed_size > _capacity ||
1086
48
                                                   (queue_size + size - removed_size > max_size) ||
1087
48
                                                   (query_context_cache_size + size -
1088
38
                                                            (removed_size + ghost_remove_size) >
1089
38
                                                    query_context->get_max_cache_size());
1090
48
    };
1091
1092
    /// Select the cache from the LRU queue held by query for expulsion.
1093
35
    for (auto iter = query_context->queue().begin(); iter != query_context->queue().end(); iter++) {
1094
33
        if (!is_overflow()) {
1095
13
            break;
1096
13
        }
1097
1098
20
        auto* cell = get_cell(iter->hash, iter->offset, cache_lock);
1099
1100
20
        if (!cell) {
1101
            /// The cache corresponding to this record may be swapped out by
1102
            /// other queries, so it has become invalid.
1103
4
            ghost.push_back(iter);
1104
4
            ghost_remove_size += iter->size;
1105
16
        } else {
1106
16
            size_t cell_size = cell->size();
1107
16
            DCHECK(iter->size == cell_size);
1108
1109
16
            if (cell->releasable()) {
1110
16
                auto& file_block = cell->file_block;
1111
1112
16
                std::lock_guard block_lock(file_block->_mutex);
1113
16
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1114
16
                to_evict.push_back(cell);
1115
16
                removed_size += cell_size;
1116
16
            }
1117
16
        }
1118
20
    }
1119
1120
16
    auto remove_file_block_if = [&](FileBlockCell* cell) {
1121
16
        FileBlockSPtr file_block = cell->file_block;
1122
16
        if (file_block) {
1123
16
            query_context->remove(file_block->get_hash_value(), file_block->offset(), cache_lock);
1124
16
            std::lock_guard block_lock(file_block->_mutex);
1125
16
            remove(file_block, cache_lock, block_lock);
1126
16
        }
1127
16
    };
1128
1129
15
    for (auto& iter : ghost) {
1130
4
        query_context->remove(iter->hash, iter->offset, cache_lock);
1131
4
    }
1132
1133
15
    std::for_each(to_evict.begin(), to_evict.end(), remove_file_block_if);
1134
1135
15
    if (is_overflow() &&
1136
15
        !try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock)) {
1137
1
        return false;
1138
1
    }
1139
14
    query_context->reserve(hash, offset, size, cache_lock);
1140
14
    return true;
1141
15
}
1142
1143
1.48k
void BlockFileCache::try_evict_in_advance(size_t size, std::lock_guard<std::mutex>& cache_lock) {
1144
1.48k
    UInt128Wrapper hash = UInt128Wrapper();
1145
1.48k
    size_t offset = 0;
1146
1.48k
    CacheContext context;
1147
    /* we pick NORMAL and TTL cache to evict in advance
1148
     * we reserve for them but won't acutually give space to them
1149
     * on the contrary, NORMAL and TTL may sacrifice by LRU evicting themselves
1150
     * other cache types cannot be exempted because we will evict what they have stolen before LRU evicting
1151
     * in summary: all cache types will shrink somewhat, and NORMAL and TTL shrink the most, to make sure the cache is not full
1152
     */
1153
1.48k
    context.cache_type = FileCacheType::NORMAL;
1154
1.48k
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1155
1.48k
    context.cache_type = FileCacheType::TTL;
1156
1.48k
    try_reserve_for_lru(hash, nullptr, context, offset, size, cache_lock, true);
1157
1.48k
}
1158
1159
// remove specific cache synchronously, for critical operations
1160
// if in use, cache meta will be deleted after use and the block file is then deleted asynchronously
1161
8
void BlockFileCache::remove_if_cached(const UInt128Wrapper& file_key) {
1162
8
    std::string reason = "remove_if_cached";
1163
8
    SCOPED_CACHE_LOCK(_mutex, this);
1164
8
    auto iter = _files.find(file_key);
1165
8
    std::vector<FileBlockCell*> to_remove;
1166
8
    if (iter != _files.end()) {
1167
14
        for (auto& [_, cell] : iter->second) {
1168
14
            if (cell.releasable()) {
1169
13
                to_remove.push_back(&cell);
1170
13
            } else {
1171
1
                cell.file_block->set_deleting();
1172
1
            }
1173
14
        }
1174
6
    }
1175
8
    remove_file_blocks(to_remove, cache_lock, true, reason);
1176
8
}
1177
1178
// the async version of remove_if_cached, for background operations
1179
// cache meta is deleted synchronously if not in use, and the block file is deleted asynchronously
1180
// if in use, cache meta will be deleted after use and the block file is then deleted asynchronously
1181
166k
void BlockFileCache::remove_if_cached_async(const UInt128Wrapper& file_key) {
1182
166k
    std::string reason = "remove_if_cached_async";
1183
166k
    SCOPED_CACHE_LOCK(_mutex, this);
1184
1185
166k
    auto iter = _files.find(file_key);
1186
166k
    std::vector<FileBlockCell*> to_remove;
1187
166k
    if (iter != _files.end()) {
1188
72.4k
        for (auto& [_, cell] : iter->second) {
1189
72.4k
            *_gc_evict_bytes_metrics << cell.size();
1190
72.4k
            *_gc_evict_count_metrics << 1;
1191
72.4k
            if (cell.releasable()) {
1192
2.90k
                to_remove.push_back(&cell);
1193
69.5k
            } else {
1194
69.5k
                cell.file_block->set_deleting();
1195
69.5k
            }
1196
72.4k
        }
1197
72.1k
    }
1198
166k
    remove_file_blocks(to_remove, cache_lock, false, reason);
1199
166k
}
1200
1201
std::vector<FileCacheType> BlockFileCache::get_other_cache_type_without_ttl(
1202
363k
        FileCacheType cur_cache_type) {
1203
363k
    switch (cur_cache_type) {
1204
5.39k
    case FileCacheType::TTL:
1205
5.39k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1206
52.5k
    case FileCacheType::INDEX:
1207
52.5k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL};
1208
302k
    case FileCacheType::NORMAL:
1209
302k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX};
1210
2.78k
    case FileCacheType::DISPOSABLE:
1211
2.78k
        return {FileCacheType::NORMAL, FileCacheType::INDEX};
1212
0
    default:
1213
0
        return {};
1214
363k
    }
1215
0
    return {};
1216
363k
}
1217
1218
10.0k
std::vector<FileCacheType> BlockFileCache::get_other_cache_type(FileCacheType cur_cache_type) {
1219
10.0k
    switch (cur_cache_type) {
1220
1.76k
    case FileCacheType::TTL:
1221
1.76k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::INDEX};
1222
1.50k
    case FileCacheType::INDEX:
1223
1.50k
        return {FileCacheType::DISPOSABLE, FileCacheType::NORMAL, FileCacheType::TTL};
1224
6.55k
    case FileCacheType::NORMAL:
1225
6.55k
        return {FileCacheType::DISPOSABLE, FileCacheType::INDEX, FileCacheType::TTL};
1226
202
    case FileCacheType::DISPOSABLE:
1227
202
        return {FileCacheType::NORMAL, FileCacheType::INDEX, FileCacheType::TTL};
1228
0
    default:
1229
0
        return {};
1230
10.0k
    }
1231
0
    return {};
1232
10.0k
}
1233
1234
void BlockFileCache::reset_range(const UInt128Wrapper& hash, size_t offset, size_t old_size,
1235
57.2k
                                 size_t new_size, std::lock_guard<std::mutex>& cache_lock) {
1236
57.2k
    DCHECK(_files.find(hash) != _files.end() &&
1237
57.2k
           _files.find(hash)->second.find(offset) != _files.find(hash)->second.end());
1238
57.2k
    FileBlockCell* cell = get_cell(hash, offset, cache_lock);
1239
57.2k
    DCHECK(cell != nullptr);
1240
57.2k
    if (cell == nullptr) {
1241
0
        LOG(WARNING) << "reset_range skipped because cache cell is missing. hash="
1242
0
                     << hash.to_string() << " offset=" << offset << " old_size=" << old_size
1243
0
                     << " new_size=" << new_size;
1244
0
        return;
1245
0
    }
1246
57.2k
    if (cell->queue_iterator) {
1247
57.2k
        auto& queue = get_queue(cell->file_block->cache_type());
1248
57.2k
        DCHECK(queue.contains(hash, offset, cache_lock));
1249
57.2k
        queue.resize(*cell->queue_iterator, new_size, cache_lock);
1250
57.2k
        _lru_recorder->record_queue_event(cell->file_block->cache_type(), CacheLRULogType::RESIZE,
1251
57.2k
                                          cell->file_block->get_hash_value(),
1252
57.2k
                                          cell->file_block->offset(), new_size);
1253
57.2k
    }
1254
57.2k
    _cur_cache_size -= old_size;
1255
57.2k
    _cur_cache_size += new_size;
1256
57.2k
}
1257
1258
bool BlockFileCache::try_reserve_from_other_queue_by_time_interval(
1259
        FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, size_t size,
1260
363k
        int64_t cur_time, std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1261
363k
    size_t removed_size = 0;
1262
363k
    size_t cur_cache_size = _cur_cache_size;
1263
363k
    std::vector<FileBlockCell*> to_evict;
1264
732k
    for (FileCacheType cache_type : other_cache_types) {
1265
732k
        auto& queue = get_queue(cache_type);
1266
732k
        size_t remove_size_per_type = 0;
1267
732k
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1268
676k
            if (!is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1269
660k
                break;
1270
660k
            }
1271
16.1k
            auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1272
16.1k
            DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << entry_key.to_string()
1273
0
                         << ", offset: " << entry_offset;
1274
1275
16.1k
            size_t cell_size = cell->size();
1276
16.1k
            DCHECK(entry_size == cell_size);
1277
1278
16.1k
            if (cell->atime == 0 ? true : cell->atime + queue.get_hot_data_interval() > cur_time) {
1279
16.1k
                break;
1280
16.1k
            }
1281
1282
2
            if (cell->releasable()) {
1283
2
                auto& file_block = cell->file_block;
1284
2
                std::lock_guard block_lock(file_block->_mutex);
1285
2
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
1286
2
                to_evict.push_back(cell);
1287
2
                removed_size += cell_size;
1288
2
                remove_size_per_type += cell_size;
1289
2
            }
1290
2
        }
1291
732k
        *(_evict_by_time_metrics_matrix[cache_type][cur_type]) << remove_size_per_type;
1292
732k
    }
1293
363k
    bool is_sync_removal = !evict_in_advance;
1294
363k
    std::string reason = std::string("try_reserve_by_time ") +
1295
363k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1296
363k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1297
1298
363k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1299
363k
}
1300
1301
bool BlockFileCache::is_overflow(size_t removed_size, size_t need_size, size_t cur_cache_size,
1302
1.36M
                                 bool evict_in_advance) const {
1303
1.36M
    bool ret = false;
1304
1.36M
    if (evict_in_advance) { // we don't need to check _need_evict_cache_in_advance
1305
70.3k
        ret = (removed_size < need_size);
1306
70.3k
        return ret;
1307
70.3k
    }
1308
1.29M
    if (_disk_resource_limit_mode) {
1309
4
        ret = (removed_size < need_size);
1310
1.29M
    } else {
1311
1.29M
        ret = (cur_cache_size + need_size - removed_size > _capacity);
1312
1.29M
    }
1313
1.29M
    return ret;
1314
1.36M
}
1315
1316
bool BlockFileCache::try_reserve_from_other_queue_by_size(
1317
        FileCacheType cur_type, std::vector<FileCacheType> other_cache_types, size_t size,
1318
4.19k
        std::lock_guard<std::mutex>& cache_lock, bool evict_in_advance) {
1319
4.19k
    size_t removed_size = 0;
1320
4.19k
    size_t cur_cache_size = _cur_cache_size;
1321
4.19k
    std::vector<FileBlockCell*> to_evict;
1322
    // we follow the privilege defined in get_other_cache_types to evict
1323
12.5k
    for (FileCacheType cache_type : other_cache_types) {
1324
12.5k
        auto& queue = get_queue(cache_type);
1325
1326
        // we will not drain each of them to the bottom -- i.e., we only
1327
        // evict what they have stolen.
1328
12.5k
        size_t cur_queue_size = queue.get_capacity(cache_lock);
1329
12.5k
        size_t cur_queue_max_size = queue.get_max_size();
1330
12.5k
        if (cur_queue_size <= cur_queue_max_size) {
1331
10.7k
            continue;
1332
10.7k
        }
1333
1.79k
        size_t cur_removed_size = 0;
1334
1.79k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1335
1.79k
                              cur_removed_size, evict_in_advance);
1336
1.79k
        *(_evict_by_size_metrics_matrix[cache_type][cur_type]) << cur_removed_size;
1337
1.79k
    }
1338
4.19k
    bool is_sync_removal = !evict_in_advance;
1339
4.19k
    std::string reason = std::string("try_reserve_by_size") +
1340
4.19k
                         " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1341
4.19k
    remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1342
4.19k
    return !is_overflow(removed_size, size, cur_cache_size, evict_in_advance);
1343
4.19k
}
1344
1345
bool BlockFileCache::try_reserve_from_other_queue(FileCacheType cur_cache_type, size_t size,
1346
                                                  int64_t cur_time,
1347
                                                  std::lock_guard<std::mutex>& cache_lock,
1348
363k
                                                  bool evict_in_advance) {
1349
    // currently, TTL cache is not considered as a candidate
1350
363k
    auto other_cache_types = get_other_cache_type_without_ttl(cur_cache_type);
1351
363k
    bool reserve_success = try_reserve_from_other_queue_by_time_interval(
1352
363k
            cur_cache_type, other_cache_types, size, cur_time, cache_lock, evict_in_advance);
1353
363k
    if (reserve_success || !config::file_cache_enable_evict_from_other_queue_by_size) {
1354
353k
        return reserve_success;
1355
353k
    }
1356
1357
10.0k
    other_cache_types = get_other_cache_type(cur_cache_type);
1358
10.0k
    auto& cur_queue = get_queue(cur_cache_type);
1359
10.0k
    size_t cur_queue_size = cur_queue.get_capacity(cache_lock);
1360
10.0k
    size_t cur_queue_max_size = cur_queue.get_max_size();
1361
    // Hit the soft limit by self, cannot remove from other queues
1362
10.0k
    if (_cur_cache_size + size > _capacity && cur_queue_size + size > cur_queue_max_size) {
1363
5.82k
        return false;
1364
5.82k
    }
1365
4.19k
    return try_reserve_from_other_queue_by_size(cur_cache_type, other_cache_types, size, cache_lock,
1366
4.19k
                                                evict_in_advance);
1367
10.0k
}
1368
1369
bool BlockFileCache::try_reserve_for_lru(const UInt128Wrapper& hash,
1370
                                         QueryFileCacheContextPtr query_context,
1371
                                         const CacheContext& context, size_t offset, size_t size,
1372
                                         std::lock_guard<std::mutex>& cache_lock,
1373
363k
                                         bool evict_in_advance) {
1374
363k
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
1375
363k
                               std::chrono::steady_clock::now().time_since_epoch())
1376
363k
                               .count();
1377
363k
    if (!try_reserve_from_other_queue(context.cache_type, size, cur_time, cache_lock,
1378
363k
                                      evict_in_advance)) {
1379
8.61k
        auto& queue = get_queue(context.cache_type);
1380
8.61k
        size_t removed_size = 0;
1381
8.61k
        size_t cur_cache_size = _cur_cache_size;
1382
1383
8.61k
        std::vector<FileBlockCell*> to_evict;
1384
8.61k
        size_t cur_removed_size = 0;
1385
8.61k
        find_evict_candidates(queue, size, cur_cache_size, removed_size, to_evict, cache_lock,
1386
8.61k
                              cur_removed_size, evict_in_advance);
1387
8.61k
        bool is_sync_removal = !evict_in_advance;
1388
8.61k
        std::string reason = std::string("try_reserve for cache type ") +
1389
8.61k
                             cache_type_to_string(context.cache_type) +
1390
8.61k
                             " evict_in_advance=" + (evict_in_advance ? "true" : "false");
1391
8.61k
        remove_file_blocks(to_evict, cache_lock, is_sync_removal, reason);
1392
8.61k
        *(_evict_by_self_lru_metrics_matrix[context.cache_type]) << cur_removed_size;
1393
1394
8.61k
        if (is_overflow(removed_size, size, cur_cache_size, evict_in_advance)) {
1395
5.97k
            return false;
1396
5.97k
        }
1397
8.61k
    }
1398
1399
357k
    if (query_context) {
1400
16
        query_context->reserve(hash, offset, size, cache_lock);
1401
16
    }
1402
357k
    return true;
1403
363k
}
1404
1405
template <class T, class U>
1406
    requires IsXLock<T> && IsXLock<U>
1407
350k
void BlockFileCache::remove(FileBlockSPtr file_block, T& cache_lock, U& block_lock, bool sync) {
1408
350k
    auto hash = file_block->get_hash_value();
1409
350k
    auto offset = file_block->offset();
1410
350k
    auto type = file_block->cache_type();
1411
350k
    auto expiration_time = file_block->expiration_time();
1412
350k
    auto tablet_id = file_block->tablet_id();
1413
350k
    auto* cell = get_cell(hash, offset, cache_lock);
1414
350k
    file_block->cell = nullptr;
1415
350k
    DCHECK(cell);
1416
350k
    DCHECK(cell->queue_iterator);
1417
350k
    if (cell->queue_iterator) {
1418
350k
        auto& queue = get_queue(file_block->cache_type());
1419
350k
        queue.remove(*cell->queue_iterator, cache_lock);
1420
350k
        _lru_recorder->record_queue_event(file_block->cache_type(), CacheLRULogType::REMOVE,
1421
350k
                                          cell->file_block->get_hash_value(),
1422
350k
                                          cell->file_block->offset(), cell->size());
1423
350k
    }
1424
350k
    *_queue_evict_size_metrics[static_cast<int>(file_block->cache_type())]
1425
350k
            << file_block->range().size();
1426
350k
    *_total_evict_size_metrics << file_block->range().size();
1427
1428
350k
    VLOG_DEBUG << "Removing file block from cache. hash: " << hash.to_string()
1429
0
               << ", offset: " << offset << ", size: " << file_block->range().size()
1430
0
               << ", type: " << cache_type_to_string(type);
1431
1432
350k
    if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADED) {
1433
117k
        FileCacheKey key;
1434
117k
        key.hash = hash;
1435
117k
        key.offset = offset;
1436
117k
        key.meta.type = type;
1437
117k
        key.meta.expiration_time = expiration_time;
1438
117k
        key.meta.tablet_id = tablet_id;
1439
117k
        if (sync) {
1440
54.7k
            int64_t duration_ns = 0;
1441
54.7k
            Status st;
1442
54.7k
            {
1443
54.7k
                SCOPED_RAW_TIMER(&duration_ns);
1444
54.7k
                st = _storage->remove(key);
1445
54.7k
            }
1446
54.7k
            *_storage_sync_remove_latency_us << (duration_ns / 1000);
1447
54.7k
            if (!st.ok()) {
1448
385
                LOG_WARNING("").error(st);
1449
385
            }
1450
63.0k
        } else {
1451
            // the file will be deleted in the bottom half
1452
            // so there will be a window that the file is not in the cache but still in the storage
1453
            // but it's ok, because the rowset is stale already
1454
63.0k
            bool ret = _recycle_keys.enqueue(key);
1455
63.0k
            if (ret) [[likely]] {
1456
63.0k
                *_recycle_keys_length_recorder << _recycle_keys.size_approx();
1457
63.0k
            } else {
1458
0
                LOG_WARNING("Failed to push recycle key to queue, do it synchronously");
1459
0
                int64_t duration_ns = 0;
1460
0
                Status st;
1461
0
                {
1462
0
                    SCOPED_RAW_TIMER(&duration_ns);
1463
0
                    st = _storage->remove(key);
1464
0
                }
1465
0
                *_storage_retry_sync_remove_latency_us << (duration_ns / 1000);
1466
0
                if (!st.ok()) {
1467
0
                    LOG_WARNING("").error(st);
1468
0
                }
1469
0
            }
1470
63.0k
        }
1471
233k
    } else if (file_block->state_unlock(block_lock) == FileBlock::State::DOWNLOADING) {
1472
0
        file_block->set_deleting();
1473
0
        return;
1474
0
    }
1475
350k
    _cur_cache_size -= file_block->range().size();
1476
350k
    if (FileCacheType::TTL == type) {
1477
1.29k
        _cur_ttl_size -= file_block->range().size();
1478
1.29k
    }
1479
350k
    auto it = _files.find(hash);
1480
350k
    if (it != _files.end()) {
1481
350k
        it->second.erase(file_block->offset());
1482
350k
        if (it->second.empty()) {
1483
114k
            _files.erase(hash);
1484
114k
        }
1485
350k
    }
1486
350k
    *_num_removed_blocks << 1;
1487
350k
}
1488
1489
46
size_t BlockFileCache::get_used_cache_size(FileCacheType cache_type) const {
1490
46
    SCOPED_CACHE_LOCK(_mutex, this);
1491
46
    return get_used_cache_size_unlocked(cache_type, cache_lock);
1492
46
}
1493
1494
size_t BlockFileCache::get_used_cache_size_unlocked(FileCacheType cache_type,
1495
46
                                                    std::lock_guard<std::mutex>& cache_lock) const {
1496
46
    return get_queue(cache_type).get_capacity(cache_lock);
1497
46
}
1498
1499
0
size_t BlockFileCache::get_available_cache_size(FileCacheType cache_type) const {
1500
0
    SCOPED_CACHE_LOCK(_mutex, this);
1501
0
    return get_available_cache_size_unlocked(cache_type, cache_lock);
1502
0
}
1503
1504
size_t BlockFileCache::get_available_cache_size_unlocked(
1505
0
        FileCacheType cache_type, std::lock_guard<std::mutex>& cache_lock) const {
1506
0
    return get_queue(cache_type).get_max_element_size() -
1507
0
           get_used_cache_size_unlocked(cache_type, cache_lock);
1508
0
}
1509
1510
88
size_t BlockFileCache::get_file_blocks_num(FileCacheType cache_type) const {
1511
88
    SCOPED_CACHE_LOCK(_mutex, this);
1512
88
    return get_file_blocks_num_unlocked(cache_type, cache_lock);
1513
88
}
1514
1515
size_t BlockFileCache::get_file_blocks_num_unlocked(FileCacheType cache_type,
1516
88
                                                    std::lock_guard<std::mutex>& cache_lock) const {
1517
88
    return get_queue(cache_type).get_elements_num(cache_lock);
1518
88
}
1519
1520
FileBlockCell::FileBlockCell(FileBlockSPtr file_block, std::lock_guard<std::mutex>& cache_lock)
1521
359k
        : file_block(file_block) {
1522
359k
    file_block->cell = this;
1523
    /**
1524
     * Cell can be created with either DOWNLOADED or EMPTY file block's state.
1525
     * File block acquires DOWNLOADING state and creates LRUQueue iterator on first
1526
     * successful getOrSetDownaloder call.
1527
     */
1528
1529
359k
    switch (file_block->_download_state) {
1530
897
    case FileBlock::State::DOWNLOADED:
1531
359k
    case FileBlock::State::EMPTY:
1532
359k
    case FileBlock::State::SKIP_CACHE: {
1533
359k
        break;
1534
359k
    }
1535
0
    default:
1536
0
        DCHECK(false) << "Can create cell with either EMPTY, DOWNLOADED, SKIP_CACHE state, got: "
1537
0
                      << FileBlock::state_to_string(file_block->_download_state);
1538
359k
    }
1539
359k
    if (file_block->cache_type() == FileCacheType::TTL) {
1540
3.92k
        update_atime();
1541
3.92k
    }
1542
359k
}
1543
1544
LRUQueue::Iterator LRUQueue::add(const UInt128Wrapper& hash, size_t offset, size_t size,
1545
715k
                                 std::lock_guard<std::mutex>& /* cache_lock */) {
1546
715k
    cache_size += size;
1547
715k
    auto iter = queue.insert(queue.end(), FileKeyAndOffset(hash, offset, size));
1548
715k
    map.insert(std::make_pair(std::make_pair(hash, offset), iter));
1549
715k
    return iter;
1550
715k
}
1551
1552
0
void LRUQueue::remove_all(std::lock_guard<std::mutex>& /* cache_lock */) {
1553
0
    queue.clear();
1554
0
    map.clear();
1555
0
    cache_size = 0;
1556
0
}
1557
1558
43.5M
void LRUQueue::move_to_end(Iterator queue_it, std::lock_guard<std::mutex>& /* cache_lock */) {
1559
43.5M
    queue.splice(queue.end(), queue, queue_it);
1560
43.5M
}
1561
1562
void LRUQueue::resize(Iterator queue_it, size_t new_size,
1563
114k
                      std::lock_guard<std::mutex>& /* cache_lock */) {
1564
114k
    cache_size -= queue_it->size;
1565
114k
    queue_it->size = new_size;
1566
114k
    cache_size += new_size;
1567
114k
}
1568
bool LRUQueue::contains(const UInt128Wrapper& hash, size_t offset,
1569
57.2k
                        std::lock_guard<std::mutex>& /* cache_lock */) const {
1570
57.2k
    return map.find(std::make_pair(hash, offset)) != map.end();
1571
57.2k
}
1572
1573
LRUQueue::Iterator LRUQueue::get(const UInt128Wrapper& hash, size_t offset,
1574
24.6M
                                 std::lock_guard<std::mutex>& /* cache_lock */) const {
1575
24.6M
    auto itr = map.find(std::make_pair(hash, offset));
1576
24.6M
    if (itr != map.end()) {
1577
19.7M
        return itr->second;
1578
19.7M
    }
1579
4.87M
    return std::list<FileKeyAndOffset>::iterator();
1580
24.6M
}
1581
1582
2
std::string LRUQueue::to_string(std::lock_guard<std::mutex>& /* cache_lock */) const {
1583
2
    std::string result;
1584
18
    for (const auto& [hash, offset, size] : queue) {
1585
18
        if (!result.empty()) {
1586
16
            result += ", ";
1587
16
        }
1588
18
        result += fmt::format("{}: [{}, {}]", hash.to_string(), offset, offset + size - 1);
1589
18
    }
1590
2
    return result;
1591
2
}
1592
1593
size_t LRUQueue::levenshtein_distance_from(LRUQueue& base,
1594
5
                                           std::lock_guard<std::mutex>& cache_lock) {
1595
5
    std::list<FileKeyAndOffset> target_queue = this->queue;
1596
5
    std::list<FileKeyAndOffset> base_queue = base.queue;
1597
5
    std::vector<FileKeyAndOffset> vec1(target_queue.begin(), target_queue.end());
1598
5
    std::vector<FileKeyAndOffset> vec2(base_queue.begin(), base_queue.end());
1599
1600
5
    size_t m = vec1.size();
1601
5
    size_t n = vec2.size();
1602
1603
    // Create a 2D vector (matrix) to store the Levenshtein distances
1604
    // dp[i][j] will hold the distance between the first i elements of vec1 and the first j elements of vec2
1605
5
    std::vector<std::vector<size_t>> dp(m + 1, std::vector<size_t>(n + 1, 0));
1606
1607
    // Initialize the first row and column of the matrix
1608
    // The distance between an empty list and a list of length k is k (all insertions or deletions)
1609
22
    for (size_t i = 0; i <= m; ++i) {
1610
17
        dp[i][0] = i;
1611
17
    }
1612
20
    for (size_t j = 0; j <= n; ++j) {
1613
15
        dp[0][j] = j;
1614
15
    }
1615
1616
    // Fill the matrix using dynamic programming
1617
17
    for (size_t i = 1; i <= m; ++i) {
1618
38
        for (size_t j = 1; j <= n; ++j) {
1619
            // Check if the current elements of both vectors are equal
1620
26
            size_t cost = (vec1[i - 1].hash == vec2[j - 1].hash &&
1621
26
                           vec1[i - 1].offset == vec2[j - 1].offset)
1622
26
                                  ? 0
1623
26
                                  : 1;
1624
            // Calculate the minimum cost of three possible operations:
1625
            // 1. Insertion: dp[i][j-1] + 1
1626
            // 2. Deletion: dp[i-1][j] + 1
1627
            // 3. Substitution: dp[i-1][j-1] + cost (0 if elements are equal, 1 if not)
1628
26
            dp[i][j] = std::min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost});
1629
26
        }
1630
12
    }
1631
    // The bottom-right cell of the matrix contains the Levenshtein distance
1632
5
    return dp[m][n];
1633
5
}
1634
1635
1
std::string BlockFileCache::dump_structure(const UInt128Wrapper& hash) {
1636
1
    SCOPED_CACHE_LOCK(_mutex, this);
1637
1
    return dump_structure_unlocked(hash, cache_lock);
1638
1
}
1639
1640
std::string BlockFileCache::dump_structure_unlocked(const UInt128Wrapper& hash,
1641
1
                                                    std::lock_guard<std::mutex>&) {
1642
1
    std::stringstream result;
1643
1
    auto it = _files.find(hash);
1644
1
    if (it == _files.end()) {
1645
0
        return std::string("");
1646
0
    }
1647
1
    const auto& cells_by_offset = it->second;
1648
1649
1
    for (const auto& [_, cell] : cells_by_offset) {
1650
1
        result << cell.file_block->get_info_for_log() << " "
1651
1
               << cache_type_to_string(cell.file_block->cache_type()) << "\n";
1652
1
    }
1653
1654
1
    return result.str();
1655
1
}
1656
1657
0
std::string BlockFileCache::dump_single_cache_type(const UInt128Wrapper& hash, size_t offset) {
1658
0
    SCOPED_CACHE_LOCK(_mutex, this);
1659
0
    return dump_single_cache_type_unlocked(hash, offset, cache_lock);
1660
0
}
1661
1662
std::string BlockFileCache::dump_single_cache_type_unlocked(const UInt128Wrapper& hash,
1663
                                                            size_t offset,
1664
0
                                                            std::lock_guard<std::mutex>&) {
1665
0
    std::stringstream result;
1666
0
    auto it = _files.find(hash);
1667
0
    if (it == _files.end()) {
1668
0
        return std::string("");
1669
0
    }
1670
0
    const auto& cells_by_offset = it->second;
1671
0
    const auto& cell = cells_by_offset.find(offset);
1672
1673
0
    return cache_type_to_string(cell->second.file_block->cache_type());
1674
0
}
1675
1676
void BlockFileCache::change_cache_type(const UInt128Wrapper& hash, size_t offset,
1677
                                       FileCacheType new_type,
1678
2.57k
                                       std::lock_guard<std::mutex>& cache_lock) {
1679
2.57k
    if (auto iter = _files.find(hash); iter != _files.end()) {
1680
2.57k
        auto& file_blocks = iter->second;
1681
2.57k
        if (auto cell_it = file_blocks.find(offset); cell_it != file_blocks.end()) {
1682
2.57k
            FileBlockCell& cell = cell_it->second;
1683
2.57k
            auto& cur_queue = get_queue(cell.file_block->cache_type());
1684
2.57k
            DCHECK(cell.queue_iterator.has_value());
1685
2.57k
            cur_queue.remove(*cell.queue_iterator, cache_lock);
1686
2.57k
            _lru_recorder->record_queue_event(
1687
2.57k
                    cell.file_block->cache_type(), CacheLRULogType::REMOVE,
1688
2.57k
                    cell.file_block->get_hash_value(), cell.file_block->offset(), cell.size());
1689
2.57k
            auto& new_queue = get_queue(new_type);
1690
2.57k
            cell.queue_iterator =
1691
2.57k
                    new_queue.add(hash, offset, cell.file_block->range().size(), cache_lock);
1692
2.57k
            _lru_recorder->record_queue_event(new_type, CacheLRULogType::ADD,
1693
2.57k
                                              cell.file_block->get_hash_value(),
1694
2.57k
                                              cell.file_block->offset(), cell.size());
1695
2.57k
        }
1696
2.57k
    }
1697
2.57k
}
1698
1699
// @brief: get a path's disk capacity used percent, inode used percent
1700
// @param: path
1701
// @param: percent.first disk used percent, percent.second inode used percent
1702
2.50k
int disk_used_percentage(const std::string& path, std::pair<int, int>* percent) {
1703
2.50k
    struct statfs stat;
1704
2.50k
    int ret = statfs(path.c_str(), &stat);
1705
2.50k
    if (ret != 0) {
1706
2
        return ret;
1707
2
    }
1708
    // https://github.com/coreutils/coreutils/blob/master/src/df.c#L1195
1709
    // v->used = stat.f_blocks - stat.f_bfree
1710
    // nonroot_total = stat.f_blocks - stat.f_bfree + stat.f_bavail
1711
2.49k
    uintmax_t u100 = (stat.f_blocks - stat.f_bfree) * 100;
1712
2.49k
    uintmax_t nonroot_total = stat.f_blocks - stat.f_bfree + stat.f_bavail;
1713
2.49k
    int capacity_percentage = int(u100 / nonroot_total + (u100 % nonroot_total != 0));
1714
1715
2.49k
    unsigned long long inode_free = stat.f_ffree;
1716
2.49k
    unsigned long long inode_total = stat.f_files;
1717
2.49k
    int inode_percentage = cast_set<int>(inode_free * 100 / inode_total);
1718
2.49k
    percent->first = capacity_percentage;
1719
2.49k
    percent->second = 100 - inode_percentage;
1720
1721
    // Add sync point for testing
1722
2.49k
    TEST_SYNC_POINT_CALLBACK("BlockFileCache::disk_used_percentage:1", percent);
1723
1724
2.49k
    return 0;
1725
2.50k
}
1726
1727
10
std::string BlockFileCache::reset_capacity(size_t new_capacity) {
1728
10
    using namespace std::chrono;
1729
10
    int64_t space_released = 0;
1730
10
    size_t old_capacity = 0;
1731
10
    std::stringstream ss;
1732
10
    ss << "finish reset_capacity, path=" << _cache_base_path;
1733
10
    auto adjust_start_time = steady_clock::time_point();
1734
10
    {
1735
10
        SCOPED_CACHE_LOCK(_mutex, this);
1736
10
        if (new_capacity < _capacity && new_capacity < _cur_cache_size) {
1737
1
            int64_t need_remove_size = _cur_cache_size - new_capacity;
1738
4
            auto remove_blocks = [&](LRUQueue& queue) -> int64_t {
1739
4
                int64_t queue_released = 0;
1740
4
                std::vector<FileBlockCell*> to_evict;
1741
13
                for (const auto& [entry_key, entry_offset, entry_size] : queue) {
1742
13
                    if (need_remove_size <= 0) {
1743
1
                        break;
1744
1
                    }
1745
12
                    need_remove_size -= entry_size;
1746
12
                    space_released += entry_size;
1747
12
                    queue_released += entry_size;
1748
12
                    auto* cell = get_cell(entry_key, entry_offset, cache_lock);
1749
12
                    if (!cell->releasable()) {
1750
0
                        cell->file_block->set_deleting();
1751
0
                        continue;
1752
0
                    }
1753
12
                    to_evict.push_back(cell);
1754
12
                }
1755
12
                for (auto& cell : to_evict) {
1756
12
                    FileBlockSPtr file_block = cell->file_block;
1757
12
                    std::lock_guard block_lock(file_block->_mutex);
1758
12
                    remove(file_block, cache_lock, block_lock);
1759
12
                }
1760
4
                return queue_released;
1761
4
            };
1762
1
            int64_t queue_released = remove_blocks(_disposable_queue);
1763
1
            ss << " disposable_queue released " << queue_released;
1764
1
            queue_released = remove_blocks(_normal_queue);
1765
1
            ss << " normal_queue released " << queue_released;
1766
1
            queue_released = remove_blocks(_index_queue);
1767
1
            ss << " index_queue released " << queue_released;
1768
1
            queue_released = remove_blocks(_ttl_queue);
1769
1
            ss << " ttl_queue released " << queue_released;
1770
1771
1
            _disk_resource_limit_mode = true;
1772
1
            _disk_limit_mode_metrics->set_value(1);
1773
1
            ss << " total_space_released=" << space_released;
1774
1
        }
1775
10
        old_capacity = _capacity;
1776
10
        _capacity = new_capacity;
1777
10
        _cache_capacity_metrics->set_value(_capacity);
1778
10
    }
1779
10
    auto use_time = duration_cast<milliseconds>(steady_clock::time_point() - adjust_start_time);
1780
10
    LOG(INFO) << "Finish tag deleted block. path=" << _cache_base_path
1781
10
              << " use_time=" << cast_set<int64_t>(use_time.count());
1782
10
    ss << " old_capacity=" << old_capacity << " new_capacity=" << new_capacity;
1783
10
    LOG(INFO) << ss.str();
1784
10
    return ss.str();
1785
10
}
1786
1787
2.25k
void BlockFileCache::check_disk_resource_limit() {
1788
2.25k
    if (_storage->get_type() != FileCacheStorageType::DISK) {
1789
940
        return;
1790
940
    }
1791
1792
1.31k
    bool previous_mode = _disk_resource_limit_mode;
1793
1.31k
    if (_capacity > _cur_cache_size) {
1794
1.31k
        _disk_resource_limit_mode = false;
1795
1.31k
        _disk_limit_mode_metrics->set_value(0);
1796
1.31k
    }
1797
1.31k
    std::pair<int, int> percent;
1798
1.31k
    int ret = disk_used_percentage(_cache_base_path, &percent);
1799
1.31k
    if (ret != 0) {
1800
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
1801
1
        return;
1802
1
    }
1803
1.31k
    auto [space_percentage, inode_percentage] = percent;
1804
2.62k
    auto is_insufficient = [](const int& percentage) {
1805
2.62k
        return percentage >= config::file_cache_enter_disk_resource_limit_mode_percent;
1806
2.62k
    };
1807
1.31k
    DCHECK_GE(space_percentage, 0);
1808
1.31k
    DCHECK_LE(space_percentage, 100);
1809
1.31k
    DCHECK_GE(inode_percentage, 0);
1810
1.31k
    DCHECK_LE(inode_percentage, 100);
1811
    // ATTN: due to that can be changed dynamically, set it to default value if it's invalid
1812
    // FIXME: reject with config validator
1813
1.31k
    if (config::file_cache_enter_disk_resource_limit_mode_percent <
1814
1.31k
        config::file_cache_exit_disk_resource_limit_mode_percent) {
1815
1
        LOG_WARNING("config error, set to default value")
1816
1
                .tag("enter", config::file_cache_enter_disk_resource_limit_mode_percent)
1817
1
                .tag("exit", config::file_cache_exit_disk_resource_limit_mode_percent);
1818
1
        config::file_cache_enter_disk_resource_limit_mode_percent = 88;
1819
1
        config::file_cache_exit_disk_resource_limit_mode_percent = 80;
1820
1
    }
1821
1.31k
    bool is_space_insufficient = is_insufficient(space_percentage);
1822
1.31k
    bool is_inode_insufficient = is_insufficient(inode_percentage);
1823
1.31k
    if (is_space_insufficient || is_inode_insufficient) {
1824
254
        _disk_resource_limit_mode = true;
1825
254
        _disk_limit_mode_metrics->set_value(1);
1826
1.05k
    } else if (_disk_resource_limit_mode &&
1827
1.05k
               (space_percentage < config::file_cache_exit_disk_resource_limit_mode_percent) &&
1828
1.05k
               (inode_percentage < config::file_cache_exit_disk_resource_limit_mode_percent)) {
1829
0
        _disk_resource_limit_mode = false;
1830
0
        _disk_limit_mode_metrics->set_value(0);
1831
0
    }
1832
1.31k
    if (previous_mode != _disk_resource_limit_mode) {
1833
        // add log for disk resource limit mode switching
1834
6
        if (_disk_resource_limit_mode) {
1835
5
            LOG(WARNING) << "Entering disk resource limit mode: file_cache=" << get_base_path()
1836
5
                         << " space_percent=" << space_percentage
1837
5
                         << " inode_percent=" << inode_percentage
1838
5
                         << " is_space_insufficient=" << is_space_insufficient
1839
5
                         << " is_inode_insufficient=" << is_inode_insufficient
1840
5
                         << " enter threshold="
1841
5
                         << config::file_cache_enter_disk_resource_limit_mode_percent;
1842
5
        } else {
1843
1
            LOG(INFO) << "Exiting disk resource limit mode: file_cache=" << get_base_path()
1844
1
                      << " space_percent=" << space_percentage
1845
1
                      << " inode_percent=" << inode_percentage << " exit threshold="
1846
1
                      << config::file_cache_exit_disk_resource_limit_mode_percent;
1847
1
        }
1848
1.30k
    } else if (_disk_resource_limit_mode) {
1849
        // print log for disk resource limit mode running, but less frequently
1850
249
        LOG_EVERY_N(WARNING, 10) << "file_cache=" << get_base_path()
1851
26
                                 << " space_percent=" << space_percentage
1852
26
                                 << " inode_percent=" << inode_percentage
1853
26
                                 << " is_space_insufficient=" << is_space_insufficient
1854
26
                                 << " is_inode_insufficient=" << is_inode_insufficient
1855
26
                                 << " mode run in resource limit";
1856
249
    }
1857
1.31k
}
1858
1859
1.18k
void BlockFileCache::check_need_evict_cache_in_advance() {
1860
1.18k
    if (_storage->get_type() != FileCacheStorageType::DISK) {
1861
1
        return;
1862
1
    }
1863
1864
1.18k
    std::pair<int, int> percent;
1865
1.18k
    int ret = disk_used_percentage(_cache_base_path, &percent);
1866
1.18k
    if (ret != 0) {
1867
1
        LOG_ERROR("").tag("file cache path", _cache_base_path).tag("error", strerror(errno));
1868
1
        return;
1869
1
    }
1870
1.18k
    auto [space_percentage, inode_percentage] = percent;
1871
1.18k
    int size_percentage = static_cast<int>(_cur_cache_size * 100 / _capacity);
1872
3.55k
    auto is_insufficient = [](const int& percentage) {
1873
3.55k
        return percentage >= config::file_cache_enter_need_evict_cache_in_advance_percent;
1874
3.55k
    };
1875
1.18k
    DCHECK_GE(space_percentage, 0);
1876
1.18k
    DCHECK_LE(space_percentage, 100);
1877
1.18k
    DCHECK_GE(inode_percentage, 0);
1878
1.18k
    DCHECK_LE(inode_percentage, 100);
1879
    // ATTN: due to that can be changed dynamically, set it to default value if it's invalid
1880
    // FIXME: reject with config validator
1881
1.18k
    if (config::file_cache_enter_need_evict_cache_in_advance_percent <=
1882
1.18k
        config::file_cache_exit_need_evict_cache_in_advance_percent) {
1883
1
        LOG_WARNING("config error, set to default value")
1884
1
                .tag("enter", config::file_cache_enter_need_evict_cache_in_advance_percent)
1885
1
                .tag("exit", config::file_cache_exit_need_evict_cache_in_advance_percent);
1886
1
        config::file_cache_enter_need_evict_cache_in_advance_percent = 78;
1887
1
        config::file_cache_exit_need_evict_cache_in_advance_percent = 75;
1888
1
    }
1889
1.18k
    bool previous_mode = _need_evict_cache_in_advance;
1890
1.18k
    bool is_space_insufficient = is_insufficient(space_percentage);
1891
1.18k
    bool is_inode_insufficient = is_insufficient(inode_percentage);
1892
1.18k
    bool is_size_insufficient = is_insufficient(size_percentage);
1893
1.18k
    if (is_space_insufficient || is_inode_insufficient || is_size_insufficient) {
1894
312
        _need_evict_cache_in_advance = true;
1895
312
        _need_evict_cache_in_advance_metrics->set_value(1);
1896
873
    } else if (_need_evict_cache_in_advance &&
1897
873
               (space_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
1898
873
               (inode_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent) &&
1899
873
               (size_percentage < config::file_cache_exit_need_evict_cache_in_advance_percent)) {
1900
50
        _need_evict_cache_in_advance = false;
1901
50
        _need_evict_cache_in_advance_metrics->set_value(0);
1902
50
    }
1903
1.18k
    if (previous_mode != _need_evict_cache_in_advance) {
1904
        // add log for evict cache in advance mode switching
1905
108
        if (_need_evict_cache_in_advance) {
1906
58
            LOG(WARNING) << "Entering evict cache in advance mode: "
1907
58
                         << "file_cache=" << get_base_path()
1908
58
                         << " space_percent=" << space_percentage
1909
58
                         << " inode_percent=" << inode_percentage
1910
58
                         << " size_percent=" << size_percentage
1911
58
                         << " is_space_insufficient=" << is_space_insufficient
1912
58
                         << " is_inode_insufficient=" << is_inode_insufficient
1913
58
                         << " is_size_insufficient=" << is_size_insufficient << " enter threshold="
1914
58
                         << config::file_cache_enter_need_evict_cache_in_advance_percent;
1915
58
        } else {
1916
50
            LOG(INFO) << "Exiting evict cache in advance mode: "
1917
50
                      << "file_cache=" << get_base_path() << " space_percent=" << space_percentage
1918
50
                      << " inode_percent=" << inode_percentage
1919
50
                      << " size_percent=" << size_percentage << " exit threshold="
1920
50
                      << config::file_cache_exit_need_evict_cache_in_advance_percent;
1921
50
        }
1922
1.07k
    } else if (_need_evict_cache_in_advance) {
1923
        // print log for evict cache in advance mode running, but less frequently
1924
254
        LOG_EVERY_N(WARNING, 10) << "file_cache=" << get_base_path()
1925
28
                                 << " space_percent=" << space_percentage
1926
28
                                 << " inode_percent=" << inode_percentage
1927
28
                                 << " size_percent=" << size_percentage
1928
28
                                 << " is_space_insufficient=" << is_space_insufficient
1929
28
                                 << " is_inode_insufficient=" << is_inode_insufficient
1930
28
                                 << " is_size_insufficient=" << is_size_insufficient
1931
28
                                 << " need evict cache in advance";
1932
254
    }
1933
1.18k
}
1934
1935
145
void BlockFileCache::run_background_monitor() {
1936
145
    Thread::set_self_name("run_background_monitor");
1937
2.25k
    while (!_close) {
1938
2.25k
        int64_t interval_ms = config::file_cache_background_monitor_interval_ms;
1939
2.25k
        TEST_SYNC_POINT_CALLBACK("BlockFileCache::set_sleep_time", &interval_ms);
1940
2.25k
        check_disk_resource_limit();
1941
2.25k
        if (config::enable_evict_file_cache_in_advance) {
1942
1.17k
            check_need_evict_cache_in_advance();
1943
1.17k
        } else {
1944
1.07k
            _need_evict_cache_in_advance = false;
1945
1.07k
            _need_evict_cache_in_advance_metrics->set_value(0);
1946
1.07k
        }
1947
1948
2.25k
        {
1949
2.25k
            std::unique_lock close_lock(_close_mtx);
1950
2.25k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
1951
2.25k
            if (_close) {
1952
142
                break;
1953
142
            }
1954
2.25k
        }
1955
        // report
1956
2.11k
        {
1957
2.11k
            SCOPED_CACHE_LOCK(_mutex, this);
1958
2.11k
            _cur_cache_size_metrics->set_value(_cur_cache_size);
1959
2.11k
            _cur_ttl_cache_size_metrics->set_value(_cur_cache_size -
1960
2.11k
                                                   _index_queue.get_capacity(cache_lock) -
1961
2.11k
                                                   _normal_queue.get_capacity(cache_lock) -
1962
2.11k
                                                   _disposable_queue.get_capacity(cache_lock));
1963
2.11k
            _cur_ttl_cache_lru_queue_cache_size_metrics->set_value(
1964
2.11k
                    _ttl_queue.get_capacity(cache_lock));
1965
2.11k
            _cur_ttl_cache_lru_queue_element_count_metrics->set_value(
1966
2.11k
                    _ttl_queue.get_elements_num(cache_lock));
1967
2.11k
            _cur_normal_queue_cache_size_metrics->set_value(_normal_queue.get_capacity(cache_lock));
1968
2.11k
            _cur_normal_queue_element_count_metrics->set_value(
1969
2.11k
                    _normal_queue.get_elements_num(cache_lock));
1970
2.11k
            _cur_index_queue_cache_size_metrics->set_value(_index_queue.get_capacity(cache_lock));
1971
2.11k
            _cur_index_queue_element_count_metrics->set_value(
1972
2.11k
                    _index_queue.get_elements_num(cache_lock));
1973
2.11k
            _cur_disposable_queue_cache_size_metrics->set_value(
1974
2.11k
                    _disposable_queue.get_capacity(cache_lock));
1975
2.11k
            _cur_disposable_queue_element_count_metrics->set_value(
1976
2.11k
                    _disposable_queue.get_elements_num(cache_lock));
1977
1978
            // Update meta store write queue size if storage is FSFileCacheStorage
1979
2.11k
            if (_storage->get_type() == FileCacheStorageType::DISK) {
1980
1.18k
                auto* fs_storage = dynamic_cast<FSFileCacheStorage*>(_storage.get());
1981
1.18k
                if (fs_storage != nullptr) {
1982
1.18k
                    auto* meta_store = fs_storage->get_meta_store();
1983
1.18k
                    if (meta_store != nullptr) {
1984
1.18k
                        _meta_store_write_queue_size_metrics->set_value(
1985
1.18k
                                meta_store->get_write_queue_size());
1986
1.18k
                    }
1987
1.18k
                }
1988
1.18k
            }
1989
1990
2.11k
            if (_num_read_blocks->get_value() > 0) {
1991
922
                _hit_ratio->set_value((double)_num_hit_blocks->get_value() /
1992
922
                                      (double)_num_read_blocks->get_value());
1993
922
            }
1994
2.11k
            if (_num_read_blocks_5m && _num_read_blocks_5m->get_value() > 0) {
1995
905
                _hit_ratio_5m->set_value((double)_num_hit_blocks_5m->get_value() /
1996
905
                                         (double)_num_read_blocks_5m->get_value());
1997
905
            }
1998
2.11k
            if (_num_read_blocks_1h && _num_read_blocks_1h->get_value() > 0) {
1999
908
                _hit_ratio_1h->set_value((double)_num_hit_blocks_1h->get_value() /
2000
908
                                         (double)_num_read_blocks_1h->get_value());
2001
908
            }
2002
2003
2.11k
            if (_no_warmup_num_hit_blocks->get_value() > 0) {
2004
882
                _no_warmup_hit_ratio->set_value((double)_no_warmup_num_hit_blocks->get_value() /
2005
882
                                                (double)_no_warmup_num_read_blocks->get_value());
2006
882
            }
2007
2.11k
            if (_no_warmup_num_hit_blocks_5m && _no_warmup_num_hit_blocks_5m->get_value() > 0) {
2008
877
                _no_warmup_hit_ratio_5m->set_value(
2009
877
                        (double)_no_warmup_num_hit_blocks_5m->get_value() /
2010
877
                        (double)_no_warmup_num_read_blocks_5m->get_value());
2011
877
            }
2012
2.11k
            if (_no_warmup_num_hit_blocks_1h && _no_warmup_num_hit_blocks_1h->get_value() > 0) {
2013
880
                _no_warmup_hit_ratio_1h->set_value(
2014
880
                        (double)_no_warmup_num_hit_blocks_1h->get_value() /
2015
880
                        (double)_no_warmup_num_read_blocks_1h->get_value());
2016
880
            }
2017
2.11k
        }
2018
2.11k
    }
2019
145
}
2020
2021
145
void BlockFileCache::run_background_gc() {
2022
145
    Thread::set_self_name("run_background_gc");
2023
145
    FileCacheKey key;
2024
145
    size_t batch_count = 0;
2025
58.0k
    while (!_close) {
2026
58.0k
        int64_t interval_ms = config::file_cache_background_gc_interval_ms;
2027
58.0k
        size_t batch_limit = config::file_cache_remove_block_qps_limit * interval_ms / 1000;
2028
58.0k
        {
2029
58.0k
            std::unique_lock close_lock(_close_mtx);
2030
58.0k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2031
58.0k
            if (_close) {
2032
142
                break;
2033
142
            }
2034
58.0k
        }
2035
2036
120k
        while (batch_count < batch_limit && _recycle_keys.try_dequeue(key)) {
2037
63.0k
            int64_t duration_ns = 0;
2038
63.0k
            Status st;
2039
63.0k
            {
2040
63.0k
                SCOPED_RAW_TIMER(&duration_ns);
2041
63.0k
                st = _storage->remove(key);
2042
63.0k
            }
2043
63.0k
            *_storage_async_remove_latency_us << (duration_ns / 1000);
2044
2045
63.0k
            if (!st.ok()) {
2046
1.66k
                LOG_WARNING("").error(st);
2047
1.66k
            }
2048
63.0k
            batch_count++;
2049
63.0k
        }
2050
57.8k
        *_recycle_keys_length_recorder << _recycle_keys.size_approx();
2051
57.8k
        batch_count = 0;
2052
57.8k
    }
2053
145
}
2054
2055
145
void BlockFileCache::run_background_evict_in_advance() {
2056
145
    Thread::set_self_name("run_background_evict_in_advance");
2057
145
    LOG(INFO) << "Starting background evict in advance thread";
2058
145
    int64_t batch = 0;
2059
10.7k
    while (!_close) {
2060
10.7k
        {
2061
10.7k
            std::unique_lock close_lock(_close_mtx);
2062
10.7k
            _close_cv.wait_for(
2063
10.7k
                    close_lock,
2064
10.7k
                    std::chrono::milliseconds(config::file_cache_evict_in_advance_interval_ms));
2065
10.7k
            if (_close) {
2066
142
                LOG(INFO) << "Background evict in advance thread exiting due to cache closing";
2067
142
                break;
2068
142
            }
2069
10.7k
        }
2070
10.5k
        batch = config::file_cache_evict_in_advance_batch_bytes;
2071
2072
        // Skip if eviction not needed or too many pending recycles
2073
10.5k
        if (!_need_evict_cache_in_advance ||
2074
10.5k
            _recycle_keys.size_approx() >=
2075
9.08k
                    config::file_cache_evict_in_advance_recycle_keys_num_threshold) {
2076
9.08k
            continue;
2077
9.08k
        }
2078
2079
1.48k
        int64_t duration_ns = 0;
2080
1.48k
        {
2081
1.48k
            SCOPED_CACHE_LOCK(_mutex, this);
2082
1.48k
            SCOPED_RAW_TIMER(&duration_ns);
2083
1.48k
            try_evict_in_advance(batch, cache_lock);
2084
1.48k
        }
2085
1.48k
        *_evict_in_advance_latency_us << (duration_ns / 1000);
2086
1.48k
    }
2087
145
}
2088
2089
145
void BlockFileCache::run_background_block_lru_update() {
2090
145
    Thread::set_self_name("run_background_block_lru_update");
2091
145
    std::vector<FileBlockSPtr> batch;
2092
5.89k
    while (!_close) {
2093
5.89k
        int64_t interval_ms = config::file_cache_background_block_lru_update_interval_ms;
2094
5.89k
        size_t batch_limit =
2095
5.89k
                config::file_cache_background_block_lru_update_qps_limit * interval_ms / 1000;
2096
5.89k
        {
2097
5.89k
            std::unique_lock close_lock(_close_mtx);
2098
5.89k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2099
5.89k
            if (_close) {
2100
142
                break;
2101
142
            }
2102
5.89k
        }
2103
2104
5.75k
        batch.clear();
2105
5.75k
        batch.reserve(batch_limit);
2106
5.75k
        size_t drained = _need_update_lru_blocks.drain(batch_limit, &batch);
2107
5.79k
        if (drained == 0) {
2108
5.79k
            *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2109
5.79k
            continue;
2110
5.79k
        }
2111
2112
18.4E
        int64_t duration_ns = 0;
2113
18.4E
        {
2114
18.4E
            SCOPED_CACHE_LOCK(_mutex, this);
2115
18.4E
            SCOPED_RAW_TIMER(&duration_ns);
2116
18.4E
            for (auto& block : batch) {
2117
482
                update_block_lru(block, cache_lock);
2118
482
            }
2119
18.4E
        }
2120
18.4E
        *_update_lru_blocks_latency_us << (duration_ns / 1000);
2121
18.4E
        *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2122
18.4E
    }
2123
145
}
2124
2125
std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>>
2126
2
BlockFileCache::get_hot_blocks_meta(const UInt128Wrapper& hash) const {
2127
2
    int64_t cur_time = std::chrono::duration_cast<std::chrono::seconds>(
2128
2
                               std::chrono::steady_clock::now().time_since_epoch())
2129
2
                               .count();
2130
2
    SCOPED_CACHE_LOCK(_mutex, this);
2131
2
    std::vector<std::tuple<size_t, size_t, FileCacheType, uint64_t>> blocks_meta;
2132
2
    if (auto iter = _files.find(hash); iter != _files.end()) {
2133
5
        for (auto& pair : _files.find(hash)->second) {
2134
5
            const FileBlockCell* cell = &pair.second;
2135
5
            if (cell->file_block->cache_type() != FileCacheType::DISPOSABLE) {
2136
4
                if (cell->file_block->cache_type() == FileCacheType::TTL ||
2137
4
                    (cell->atime != 0 &&
2138
3
                     cur_time - cell->atime <
2139
3
                             get_queue(cell->file_block->cache_type()).get_hot_data_interval())) {
2140
3
                    blocks_meta.emplace_back(pair.first, cell->size(),
2141
3
                                             cell->file_block->cache_type(),
2142
3
                                             cell->file_block->expiration_time());
2143
3
                }
2144
4
            }
2145
5
        }
2146
2
    }
2147
2
    return blocks_meta;
2148
2
}
2149
2150
bool BlockFileCache::try_reserve_during_async_load(size_t size,
2151
1.00k
                                                   std::lock_guard<std::mutex>& cache_lock) {
2152
1.00k
    size_t removed_size = 0;
2153
1.00k
    size_t normal_queue_size = _normal_queue.get_capacity(cache_lock);
2154
1.00k
    size_t disposable_queue_size = _disposable_queue.get_capacity(cache_lock);
2155
1.00k
    size_t index_queue_size = _index_queue.get_capacity(cache_lock);
2156
2157
1.00k
    std::vector<FileBlockCell*> to_evict;
2158
1.00k
    auto collect_eliminate_fragments = [&](LRUQueue& queue) {
2159
1.00k
        for (const auto& [entry_key, entry_offset, entry_size] : queue) {
2160
1.00k
            if (!_disk_resource_limit_mode || removed_size >= size) {
2161
1.00k
                break;
2162
1.00k
            }
2163
1
            auto* cell = get_cell(entry_key, entry_offset, cache_lock);
2164
2165
1
            DCHECK(cell) << "Cache became inconsistent. UInt128Wrapper: " << entry_key.to_string()
2166
0
                         << ", offset: " << entry_offset;
2167
2168
1
            size_t cell_size = cell->size();
2169
1
            DCHECK(entry_size == cell_size);
2170
2171
1
            if (cell->releasable()) {
2172
1
                auto& file_block = cell->file_block;
2173
2174
1
                std::lock_guard block_lock(file_block->_mutex);
2175
1
                DCHECK(file_block->_download_state == FileBlock::State::DOWNLOADED);
2176
1
                to_evict.push_back(cell);
2177
1
                removed_size += cell_size;
2178
1
            }
2179
1
        }
2180
1.00k
    };
2181
1.00k
    if (disposable_queue_size != 0) {
2182
0
        collect_eliminate_fragments(get_queue(FileCacheType::DISPOSABLE));
2183
0
    }
2184
1.00k
    if (normal_queue_size != 0) {
2185
1.00k
        collect_eliminate_fragments(get_queue(FileCacheType::NORMAL));
2186
1.00k
    }
2187
1.00k
    if (index_queue_size != 0) {
2188
0
        collect_eliminate_fragments(get_queue(FileCacheType::INDEX));
2189
0
    }
2190
1.00k
    std::string reason = "async load";
2191
1.00k
    remove_file_blocks(to_evict, cache_lock, true, reason);
2192
2193
1.00k
    return !_disk_resource_limit_mode || removed_size >= size;
2194
1.00k
}
2195
2196
30
void BlockFileCache::clear_need_update_lru_blocks() {
2197
30
    _need_update_lru_blocks.clear();
2198
30
    *_need_update_lru_blocks_length_recorder << _need_update_lru_blocks.size();
2199
30
}
2200
2201
27
std::string BlockFileCache::clear_file_cache_directly() {
2202
27
    _lru_dumper->remove_lru_dump_files();
2203
27
    using namespace std::chrono;
2204
27
    std::stringstream ss;
2205
27
    auto start = steady_clock::now();
2206
27
    SCOPED_CACHE_LOCK(_mutex, this);
2207
27
    LOG_INFO("start clear_file_cache_directly").tag("path", _cache_base_path);
2208
2209
27
    std::string clear_msg;
2210
27
    auto s = _storage->clear(clear_msg);
2211
27
    if (!s.ok()) {
2212
1
        return clear_msg;
2213
1
    }
2214
2215
26
    int64_t num_files = _files.size();
2216
26
    int64_t cache_size = _cur_cache_size;
2217
26
    int64_t index_queue_size = _index_queue.get_elements_num(cache_lock);
2218
26
    int64_t normal_queue_size = _normal_queue.get_elements_num(cache_lock);
2219
26
    int64_t disposible_queue_size = _disposable_queue.get_elements_num(cache_lock);
2220
26
    int64_t ttl_queue_size = _ttl_queue.get_elements_num(cache_lock);
2221
2222
26
    int64_t clear_fd_duration = 0;
2223
26
    {
2224
        // clear FDCache to release fd
2225
26
        SCOPED_RAW_TIMER(&clear_fd_duration);
2226
26
        for (const auto& [file_key, file_blocks] : _files) {
2227
13
            for (const auto& [offset, file_block_cell] : file_blocks) {
2228
13
                AccessKeyAndOffset access_key_and_offset(file_key, offset);
2229
13
                FDCache::instance()->remove_file_reader(access_key_and_offset);
2230
13
            }
2231
2
        }
2232
26
    }
2233
2234
26
    _files.clear();
2235
26
    _cur_cache_size = 0;
2236
26
    _cur_ttl_size = 0;
2237
26
    _time_to_key.clear();
2238
26
    _key_to_time.clear();
2239
26
    _index_queue.clear(cache_lock);
2240
26
    _normal_queue.clear(cache_lock);
2241
26
    _disposable_queue.clear(cache_lock);
2242
26
    _ttl_queue.clear(cache_lock);
2243
2244
    // Synchronously update cache metrics so that information_schema.file_cache_statistics
2245
    // reflects the cleared state immediately, without waiting for the next
2246
    // run_background_monitor cycle.
2247
26
    _cur_cache_size_metrics->set_value(0);
2248
26
    _cur_ttl_cache_size_metrics->set_value(0);
2249
26
    _cur_ttl_cache_lru_queue_cache_size_metrics->set_value(0);
2250
26
    _cur_ttl_cache_lru_queue_element_count_metrics->set_value(0);
2251
26
    _cur_normal_queue_cache_size_metrics->set_value(0);
2252
26
    _cur_normal_queue_element_count_metrics->set_value(0);
2253
26
    _cur_index_queue_cache_size_metrics->set_value(0);
2254
26
    _cur_index_queue_element_count_metrics->set_value(0);
2255
26
    _cur_disposable_queue_cache_size_metrics->set_value(0);
2256
26
    _cur_disposable_queue_element_count_metrics->set_value(0);
2257
2258
26
    clear_need_update_lru_blocks();
2259
2260
26
    ss << "finish clear_file_cache_directly"
2261
26
       << " path=" << _cache_base_path
2262
26
       << " time_elapsed_ms=" << duration_cast<milliseconds>(steady_clock::now() - start).count()
2263
26
       << " fd_clear_time_ms=" << (clear_fd_duration / 1000000) << " num_files=" << num_files
2264
26
       << " cache_size=" << cache_size << " index_queue_size=" << index_queue_size
2265
26
       << " normal_queue_size=" << normal_queue_size
2266
26
       << " disposible_queue_size=" << disposible_queue_size << "ttl_queue_size=" << ttl_queue_size;
2267
26
    auto msg = ss.str();
2268
26
    LOG(INFO) << msg;
2269
26
    _lru_dumper->remove_lru_dump_files();
2270
26
    return msg;
2271
27
}
2272
2273
44.9k
std::map<size_t, FileBlockSPtr> BlockFileCache::get_blocks_by_key(const UInt128Wrapper& hash) {
2274
44.9k
    std::map<size_t, FileBlockSPtr> offset_to_block;
2275
44.9k
    SCOPED_CACHE_LOCK(_mutex, this);
2276
44.9k
    if (_files.contains(hash)) {
2277
41.4k
        for (auto& [offset, cell] : _files[hash]) {
2278
41.4k
            if (cell.file_block->state() == FileBlock::State::DOWNLOADED) {
2279
41.4k
                cell.file_block->_owned_by_cached_reader = true;
2280
41.4k
                offset_to_block.emplace(offset, cell.file_block);
2281
41.4k
            }
2282
41.4k
        }
2283
39.8k
    }
2284
44.9k
    return offset_to_block;
2285
44.9k
}
2286
2287
0
void BlockFileCache::update_ttl_atime(const UInt128Wrapper& hash) {
2288
0
    SCOPED_CACHE_LOCK(_mutex, this);
2289
0
    if (auto iter = _files.find(hash); iter != _files.end()) {
2290
0
        for (auto& [_, cell] : iter->second) {
2291
0
            cell.update_atime();
2292
0
        }
2293
0
    };
2294
0
}
2295
2296
145
void BlockFileCache::run_background_lru_log_replay() {
2297
145
    Thread::set_self_name("run_background_lru_log_replay");
2298
8.55k
    while (!_close) {
2299
8.55k
        int64_t interval_ms = config::file_cache_background_lru_log_replay_interval_ms;
2300
8.55k
        {
2301
8.55k
            std::unique_lock close_lock(_close_mtx);
2302
8.55k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2303
8.55k
            if (_close) {
2304
142
                break;
2305
142
            }
2306
8.55k
        }
2307
2308
8.41k
        _lru_recorder->replay_queue_event(FileCacheType::TTL);
2309
8.41k
        _lru_recorder->replay_queue_event(FileCacheType::INDEX);
2310
8.41k
        _lru_recorder->replay_queue_event(FileCacheType::NORMAL);
2311
8.41k
        _lru_recorder->replay_queue_event(FileCacheType::DISPOSABLE);
2312
2313
8.41k
        if (config::enable_evaluate_shadow_queue_diff) {
2314
0
            SCOPED_CACHE_LOCK(_mutex, this);
2315
0
            _lru_recorder->evaluate_queue_diff(_ttl_queue, "ttl", cache_lock);
2316
0
            _lru_recorder->evaluate_queue_diff(_index_queue, "index", cache_lock);
2317
0
            _lru_recorder->evaluate_queue_diff(_normal_queue, "normal", cache_lock);
2318
0
            _lru_recorder->evaluate_queue_diff(_disposable_queue, "disposable", cache_lock);
2319
0
        }
2320
8.41k
    }
2321
145
}
2322
2323
1.61k
void BlockFileCache::dump_lru_queues(bool force) {
2324
1.61k
    std::unique_lock dump_lock(_dump_lru_queues_mtx);
2325
1.61k
    if (config::file_cache_background_lru_dump_tail_record_num > 0 &&
2326
1.61k
        !ExecEnv::GetInstance()->get_is_upgrading()) {
2327
1.61k
        _lru_dumper->dump_queue("disposable", force);
2328
1.61k
        _lru_dumper->dump_queue("normal", force);
2329
1.61k
        _lru_dumper->dump_queue("index", force);
2330
1.61k
        _lru_dumper->dump_queue("ttl", force);
2331
1.61k
        _lru_dumper->set_first_dump_done();
2332
1.61k
    }
2333
1.61k
}
2334
2335
145
void BlockFileCache::run_background_lru_dump() {
2336
145
    Thread::set_self_name("run_background_lru_dump");
2337
1.76k
    while (!_close) {
2338
1.76k
        int64_t interval_ms = config::file_cache_background_lru_dump_interval_ms;
2339
1.76k
        {
2340
1.76k
            std::unique_lock close_lock(_close_mtx);
2341
1.76k
            _close_cv.wait_for(close_lock, std::chrono::milliseconds(interval_ms));
2342
1.76k
            if (_close) {
2343
142
                break;
2344
142
            }
2345
1.76k
        }
2346
1.62k
        dump_lru_queues(false);
2347
1.62k
    }
2348
145
}
2349
2350
145
void BlockFileCache::restore_lru_queues_from_disk(std::lock_guard<std::mutex>& cache_lock) {
2351
    // keep this order coz may be duplicated in different queue, we use the first appearence
2352
145
    _lru_dumper->restore_queue(_ttl_queue, "ttl", cache_lock);
2353
145
    _lru_dumper->restore_queue(_index_queue, "index", cache_lock);
2354
145
    _lru_dumper->restore_queue(_normal_queue, "normal", cache_lock);
2355
145
    _lru_dumper->restore_queue(_disposable_queue, "disposable", cache_lock);
2356
145
}
2357
2358
1
std::map<std::string, double> BlockFileCache::get_stats() {
2359
1
    std::map<std::string, double> stats;
2360
1
    stats["hits_ratio"] = (double)_hit_ratio->get_value();
2361
1
    stats["hits_ratio_5m"] = (double)_hit_ratio_5m->get_value();
2362
1
    stats["hits_ratio_1h"] = (double)_hit_ratio_1h->get_value();
2363
2364
1
    stats["index_queue_max_size"] = (double)_index_queue.get_max_size();
2365
1
    stats["index_queue_curr_size"] = (double)_cur_index_queue_cache_size_metrics->get_value();
2366
1
    stats["index_queue_max_elements"] = (double)_index_queue.get_max_element_size();
2367
1
    stats["index_queue_curr_elements"] =
2368
1
            (double)_cur_index_queue_element_count_metrics->get_value();
2369
2370
1
    stats["ttl_queue_max_size"] = (double)_ttl_queue.get_max_size();
2371
1
    stats["ttl_queue_curr_size"] = (double)_cur_ttl_cache_lru_queue_cache_size_metrics->get_value();
2372
1
    stats["ttl_queue_max_elements"] = (double)_ttl_queue.get_max_element_size();
2373
1
    stats["ttl_queue_curr_elements"] =
2374
1
            (double)_cur_ttl_cache_lru_queue_element_count_metrics->get_value();
2375
2376
1
    stats["normal_queue_max_size"] = (double)_normal_queue.get_max_size();
2377
1
    stats["normal_queue_curr_size"] = (double)_cur_normal_queue_cache_size_metrics->get_value();
2378
1
    stats["normal_queue_max_elements"] = (double)_normal_queue.get_max_element_size();
2379
1
    stats["normal_queue_curr_elements"] =
2380
1
            (double)_cur_normal_queue_element_count_metrics->get_value();
2381
2382
1
    stats["disposable_queue_max_size"] = (double)_disposable_queue.get_max_size();
2383
1
    stats["disposable_queue_curr_size"] =
2384
1
            (double)_cur_disposable_queue_cache_size_metrics->get_value();
2385
1
    stats["disposable_queue_max_elements"] = (double)_disposable_queue.get_max_element_size();
2386
1
    stats["disposable_queue_curr_elements"] =
2387
1
            (double)_cur_disposable_queue_element_count_metrics->get_value();
2388
2389
1
    stats["need_evict_cache_in_advance"] = (double)_need_evict_cache_in_advance;
2390
1
    stats["disk_resource_limit_mode"] = (double)_disk_resource_limit_mode;
2391
2392
1
    stats["total_removed_counts"] = (double)_num_removed_blocks->get_value();
2393
1
    stats["total_hit_counts"] = (double)_num_hit_blocks->get_value();
2394
1
    stats["total_read_counts"] = (double)_num_read_blocks->get_value();
2395
2396
1
    stats["total_read_size"] = (double)_total_read_size_metrics->get_value();
2397
1
    stats["total_hit_size"] = (double)_total_hit_size_metrics->get_value();
2398
1
    stats["total_removed_size"] = (double)_total_evict_size_metrics->get_value();
2399
2400
1
    return stats;
2401
1
}
2402
2403
// for be UTs
2404
172
std::map<std::string, double> BlockFileCache::get_stats_unsafe() {
2405
172
    std::map<std::string, double> stats;
2406
172
    stats["hits_ratio"] = (double)_hit_ratio->get_value();
2407
172
    stats["hits_ratio_5m"] = (double)_hit_ratio_5m->get_value();
2408
172
    stats["hits_ratio_1h"] = (double)_hit_ratio_1h->get_value();
2409
2410
172
    stats["index_queue_max_size"] = (double)_index_queue.get_max_size();
2411
172
    stats["index_queue_curr_size"] = (double)_index_queue.get_capacity_unsafe();
2412
172
    stats["index_queue_max_elements"] = (double)_index_queue.get_max_element_size();
2413
172
    stats["index_queue_curr_elements"] = (double)_index_queue.get_elements_num_unsafe();
2414
2415
172
    stats["ttl_queue_max_size"] = (double)_ttl_queue.get_max_size();
2416
172
    stats["ttl_queue_curr_size"] = (double)_ttl_queue.get_capacity_unsafe();
2417
172
    stats["ttl_queue_max_elements"] = (double)_ttl_queue.get_max_element_size();
2418
172
    stats["ttl_queue_curr_elements"] = (double)_ttl_queue.get_elements_num_unsafe();
2419
2420
172
    stats["normal_queue_max_size"] = (double)_normal_queue.get_max_size();
2421
172
    stats["normal_queue_curr_size"] = (double)_normal_queue.get_capacity_unsafe();
2422
172
    stats["normal_queue_max_elements"] = (double)_normal_queue.get_max_element_size();
2423
172
    stats["normal_queue_curr_elements"] = (double)_normal_queue.get_elements_num_unsafe();
2424
2425
172
    stats["disposable_queue_max_size"] = (double)_disposable_queue.get_max_size();
2426
172
    stats["disposable_queue_curr_size"] = (double)_disposable_queue.get_capacity_unsafe();
2427
172
    stats["disposable_queue_max_elements"] = (double)_disposable_queue.get_max_element_size();
2428
172
    stats["disposable_queue_curr_elements"] = (double)_disposable_queue.get_elements_num_unsafe();
2429
2430
172
    stats["need_evict_cache_in_advance"] = (double)_need_evict_cache_in_advance;
2431
172
    stats["disk_resource_limit_mode"] = (double)_disk_resource_limit_mode;
2432
2433
172
    stats["total_removed_counts"] = (double)_num_removed_blocks->get_value();
2434
172
    stats["total_hit_counts"] = (double)_num_hit_blocks->get_value();
2435
172
    stats["total_read_counts"] = (double)_num_read_blocks->get_value();
2436
2437
172
    stats["total_read_size"] = (double)_total_read_size_metrics->get_value();
2438
172
    stats["total_hit_size"] = (double)_total_hit_size_metrics->get_value();
2439
172
    stats["total_removed_size"] = (double)_total_evict_size_metrics->get_value();
2440
2441
172
    return stats;
2442
172
}
2443
2444
template void BlockFileCache::remove(FileBlockSPtr file_block,
2445
                                     std::lock_guard<std::mutex>& cache_lock,
2446
                                     std::lock_guard<std::mutex>& block_lock, bool sync);
2447
2448
#include "common/compile_check_end.h"
2449
2450
1
Status BlockFileCache::report_file_cache_inconsistency(std::vector<std::string>& results) {
2451
1
    InconsistencyContext inconsistency_context;
2452
1
    RETURN_IF_ERROR(check_file_cache_consistency(inconsistency_context));
2453
1
    auto n = inconsistency_context.types.size();
2454
1
    results.reserve(n);
2455
1
    for (size_t i = 0; i < n; i++) {
2456
0
        std::string result;
2457
0
        result += "File cache info in manager:\n";
2458
0
        result += inconsistency_context.infos_in_manager[i].to_string();
2459
0
        result += "File cache info in storage:\n";
2460
0
        result += inconsistency_context.infos_in_storage[i].to_string();
2461
0
        result += inconsistency_context.types[i].to_string();
2462
0
        result += "\n";
2463
0
        results.push_back(std::move(result));
2464
0
    }
2465
1
    return Status::OK();
2466
1
}
2467
2468
1
Status BlockFileCache::check_file_cache_consistency(InconsistencyContext& inconsistency_context) {
2469
1
    std::lock_guard<std::mutex> cache_lock(_mutex);
2470
1
    std::vector<FileCacheInfo> infos_in_storage;
2471
1
    RETURN_IF_ERROR(_storage->get_file_cache_infos(infos_in_storage, cache_lock));
2472
1
    std::unordered_set<AccessKeyAndOffset, KeyAndOffsetHash> confirmed_blocks;
2473
1
    for (const auto& info_in_storage : infos_in_storage) {
2474
0
        confirmed_blocks.insert({info_in_storage.hash, info_in_storage.offset});
2475
0
        auto* cell = get_cell(info_in_storage.hash, info_in_storage.offset, cache_lock);
2476
0
        if (cell == nullptr || cell->file_block == nullptr) {
2477
0
            inconsistency_context.infos_in_manager.emplace_back();
2478
0
            inconsistency_context.infos_in_storage.push_back(info_in_storage);
2479
0
            inconsistency_context.types.emplace_back(InconsistencyType::NOT_LOADED);
2480
0
            continue;
2481
0
        }
2482
0
        FileCacheInfo info_in_manager {
2483
0
                .hash = info_in_storage.hash,
2484
0
                .expiration_time = cell->file_block->expiration_time(),
2485
0
                .size = cell->size(),
2486
0
                .offset = info_in_storage.offset,
2487
0
                .is_tmp = cell->file_block->state() == FileBlock::State::DOWNLOADING,
2488
0
                .cache_type = cell->file_block->cache_type()};
2489
0
        InconsistencyType inconsistent_type;
2490
0
        if (info_in_storage.is_tmp != info_in_manager.is_tmp) {
2491
0
            inconsistent_type |= InconsistencyType::TMP_FILE_EXPECT_DOWNLOADING_STATE;
2492
0
        }
2493
0
        size_t expected_size =
2494
0
                info_in_manager.is_tmp ? cell->dowloading_size() : info_in_manager.size;
2495
0
        if (info_in_storage.size != expected_size) {
2496
0
            inconsistent_type |= InconsistencyType::SIZE_INCONSISTENT;
2497
0
        }
2498
        // Only if it is not a tmp file need we check the cache type.
2499
0
        if ((inconsistent_type & InconsistencyType::TMP_FILE_EXPECT_DOWNLOADING_STATE) == 0 &&
2500
0
            info_in_storage.cache_type != info_in_manager.cache_type) {
2501
0
            inconsistent_type |= InconsistencyType::CACHE_TYPE_INCONSISTENT;
2502
0
        }
2503
0
        if (info_in_storage.expiration_time != info_in_manager.expiration_time) {
2504
0
            inconsistent_type |= InconsistencyType::EXPIRATION_TIME_INCONSISTENT;
2505
0
        }
2506
0
        if (inconsistent_type != InconsistencyType::NONE) {
2507
0
            inconsistency_context.infos_in_manager.push_back(info_in_manager);
2508
0
            inconsistency_context.infos_in_storage.push_back(info_in_storage);
2509
0
            inconsistency_context.types.push_back(inconsistent_type);
2510
0
        }
2511
0
    }
2512
2513
1
    for (const auto& [hash, offset_to_cell] : _files) {
2514
0
        for (const auto& [offset, cell] : offset_to_cell) {
2515
0
            if (confirmed_blocks.contains({hash, offset})) {
2516
0
                continue;
2517
0
            }
2518
0
            const auto& block = cell.file_block;
2519
0
            inconsistency_context.infos_in_manager.emplace_back(
2520
0
                    hash, block->expiration_time(), cell.size(), offset,
2521
0
                    cell.file_block->state() == FileBlock::State::DOWNLOADING, block->cache_type());
2522
0
            inconsistency_context.infos_in_storage.emplace_back();
2523
0
            inconsistency_context.types.emplace_back(InconsistencyType::MISSING_IN_STORAGE);
2524
0
        }
2525
0
    }
2526
1
    return Status::OK();
2527
1
}
2528
2529
} // namespace doris::io