Coverage Report

Created: 2026-04-11 00:05

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