Coverage Report

Created: 2026-08-21 02:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/file_handle_cache.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
//
18
// This file is copied from
19
// https://github.com/apache/impala/blob/master/be/src/runtime/io/handle-cache.h
20
// and modified by Doris
21
22
#pragma once
23
24
#include <array>
25
#include <cstdint>
26
#include <list>
27
#include <map>
28
#include <memory>
29
#include <mutex>
30
#include <string>
31
#include <utility>
32
33
#include "common/status.h"
34
#include "io/fs/file_system.h"
35
#include "io/fs/hdfs.h"
36
#include "util/aligned_new.h"
37
#include "util/lru_multi_cache.inline.h"
38
#include "util/thread.h"
39
40
namespace doris::io {
41
42
/// This abstract class is a small wrapper around the hdfsFile handle and the file system
43
/// instance which is needed to close the file handle. The handle incorporates
44
/// the last modified time of the file when it was opened. This is used to distinguish
45
/// between file handles for files that can be updated or overwritten.
46
/// This is used only through its subclasses, CachedHdfsFileHandle and
47
/// ExclusiveHdfsFileHandle.
48
class HdfsFileHandle {
49
public:
50
    /// Destructor will close the file handle
51
    ~HdfsFileHandle();
52
53
    /// Init only sets file_size (from param or hdfsGetPathInfo), does NOT open the file.
54
    Status init(int64_t file_size);
55
56
    /// Lazily opens the file handle on first read. Thread-safe via std::call_once.
57
    Status ensure_open();
58
59
0
    hdfsFS fs() const { return _fs; }
60
15
    hdfsFile file() const { return _hdfs_file; }
61
0
    int64_t mtime() const { return _mtime; }
62
2
    int64_t file_size() const { return _file_size; }
63
64
protected:
65
    HdfsFileHandle(const hdfsFS& fs, const std::string& fname, int64_t mtime)
66
13
            : _fs(fs), _fname(fname), _mtime(mtime) {}
67
68
private:
69
    hdfsFS _fs;
70
    const std::string _fname;
71
    hdfsFile _hdfs_file = nullptr;
72
    int64_t _mtime;
73
    int64_t _file_size = -1;
74
    std::once_flag _open_once;
75
};
76
77
/// CachedHdfsFileHandles are owned by the file handle cache and are used for no
78
/// other purpose.
79
class CachedHdfsFileHandle : public HdfsFileHandle {
80
public:
81
    CachedHdfsFileHandle(const hdfsFS& fs, const std::string& fname, int64_t mtime);
82
    ~CachedHdfsFileHandle();
83
};
84
85
/// ExclusiveHdfsFileHandles are used for all purposes where a CachedHdfsFileHandle
86
/// is not appropriate.
87
class ExclusiveHdfsFileHandle : public HdfsFileHandle {
88
public:
89
    ExclusiveHdfsFileHandle(const hdfsFS& fs, const std::string& fname, int64_t mtime)
90
8
            : HdfsFileHandle(fs, fname, mtime) {}
91
};
92
93
/// The FileHandleCache is a data structure that owns HdfsFileHandles to share between
94
/// threads. The HdfsFileHandles are hash partitioned across NUM_PARTITIONS partitions.
95
/// Each partition operates independently with its own locks, reducing contention
96
/// between concurrent threads. The `capacity` is split between the partitions and is
97
/// enforced independently.
98
///
99
/// Threads check out a file handle for exclusive access, released automatically by RAII
100
/// accessor. If the file handle is not already present in the cache or all file handles
101
/// for this file are checked out, the file handle is emplaced in the cache. The cache can
102
/// contain multiple file handles for the same file. If a file handle is checked out, it
103
/// cannot be evicted from the cache. In this case, a cache can exceed the specified
104
/// capacity.
105
///
106
/// Remote file systems could keep a connection as part of the file handle without support
107
/// for unbuffering. The file handle cache is not suitable for those systems, as the cache
108
/// size can exceed the limit on the number of concurrent connections. HDFS does not
109
/// maintain a connection in the file handle, S3A client supports unbuffering since
110
/// IMPALA-8428, so those do not have this restriction.
111
///
112
/// If there is a file handle in the cache and the underlying file is deleted,
113
/// the file handle might keep the file from being deleted at the OS level. This can
114
/// take up disk space and impact correctness. To avoid this, the cache will evict any
115
/// file handle that has been unused for longer than threshold specified by
116
/// `unused_handle_timeout_secs`. Eviction is disabled when the threshold is 0.
117
///
118
/// TODO: The cache should also evict file handles more aggressively if the file handle's
119
/// mtime is older than the file's current mtime.
120
class FileHandleCache {
121
private:
122
    using CacheKey = std::pair<hdfsFS, std::pair<std::string, int64_t>>;
123
124
    /// Each partition operates independently, and thus has its own thread-safe cache.
125
    /// To avoid contention on the lock_ due to false sharing the partitions are
126
    /// aligned to cache line boundaries.
127
    struct FileHandleCachePartition : public CacheLineAligned {
128
        // The same HDFS path can be opened through different hdfsFS instances with
129
        // different authentication contexts, so the filesystem handle is part of the key.
130
        typedef LruMultiCache<CacheKey, CachedHdfsFileHandle> CacheType;
131
        CacheType cache;
132
    };
133
134
public:
135
    /// RAII accessor built over LruMultiCache::Accessor to handle metrics and unbuffering.
136
    /// Composition is used instead of inheritance to support the usage as in/out parameter
137
    class Accessor {
138
    public:
139
        Accessor();
140
        Accessor(FileHandleCachePartition::CacheType::Accessor&& cache_accessor);
141
2
        Accessor(Accessor&&) = default;
142
        Accessor& operator=(Accessor&&) = default;
143
144
        DISALLOW_COPY_AND_ASSIGN(Accessor);
145
146
        /// Handles metrics and unbuffering
147
        ~Accessor();
148
149
        /// Set function can be used if the Accessor is used as in/out parameter.
150
        void set(FileHandleCachePartition::CacheType::Accessor&& cache_accessor);
151
152
        /// Interface mimics LruMultiCache::Accessor's interface, handles metrics
153
        CachedHdfsFileHandle* get();
154
        void release();
155
        void destroy();
156
157
    private:
158
        FileHandleCachePartition::CacheType::Accessor _cache_accessor;
159
    };
160
161
    /// Instantiates the cache with `capacity` split evenly across NUM_PARTITIONS
162
    /// partitions. If the capacity does not split evenly, then the capacity is rounded
163
    /// up. The cache will age out any file handle that is unused for
164
    /// `unused_handle_timeout_secs` seconds. Age out is disabled if this is set to zero.
165
    FileHandleCache(size_t capacity, size_t num_partitions, uint64_t unused_handle_timeout_secs);
166
167
    /// Destructor is only called for backend tests
168
    ~FileHandleCache();
169
170
    /// Starts up a thread that monitors the age of file handles and evicts any that
171
    /// exceed the limit.
172
    Status init() WARN_UNUSED_RESULT;
173
174
    /// Get a file handle accessor from the cache for the specified filename (fname) and
175
    /// last modification time (mtime). This will hash the filename to determine
176
    /// which partition to use for this file handle.
177
    ///
178
    /// If 'require_new_handle' is false and the partition contains an available handle,
179
    /// an accessor is returned and cache_hit is set to true. Otherwise, the partition will
180
    /// emplace file handle, an accessor to it will be returned with cache_hit set to false.
181
    /// On failure, empty accessor will be returned. In either case, the partition may evict
182
    /// a file handle to make room for the new file handle.
183
    ///
184
    /// This obtains exclusive control over the returned file handle.
185
    Status get_file_handle(const hdfsFS& fs, const std::string& fname, int64_t mtime,
186
                           int64_t file_size, bool require_new_handle, Accessor* accessor,
187
                           bool* cache_hit) WARN_UNUSED_RESULT;
188
189
#ifdef BE_TEST
190
    static bool same_cache_key_for_test(const hdfsFS& lhs_fs, const std::string& lhs_fname,
191
                                        int64_t lhs_mtime, const hdfsFS& rhs_fs,
192
                                        const std::string& rhs_fname, int64_t rhs_mtime);
193
#endif
194
195
private:
196
14
    static CacheKey make_cache_key(const hdfsFS& fs, const std::string& fname, int64_t mtime) {
197
14
        return {fs, {fname, mtime}};
198
14
    }
199
200
    /// Periodic check to evict unused file handles. Only executed by _eviction_thread.
201
    void _evict_handles_loop();
202
203
    std::vector<FileHandleCachePartition> _cache_partitions;
204
205
    /// Maximum time before an unused file handle is aged out of the cache.
206
    /// Aging out is disabled if this is set to 0.
207
    uint64_t _unused_handle_timeout_secs;
208
209
    /// Thread to check for unused file handles to evict. This thread will exit when
210
    /// the _shut_down_promise is set.
211
    std::shared_ptr<Thread> _eviction_thread;
212
    std::atomic<bool> _is_shut_down = {false};
213
};
214
215
} // namespace doris::io