Coverage Report

Created: 2026-11-03 14:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/packed_file_manager.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
#pragma once
19
20
#include <butil/macros.h>
21
#include <glog/logging.h>
22
23
#include <atomic>
24
#include <chrono>
25
#include <condition_variable>
26
#include <map>
27
#include <memory>
28
#include <mutex>
29
#include <optional>
30
#include <string>
31
#include <thread>
32
#include <unordered_map>
33
#include <vector>
34
35
#include "common/status.h"
36
#include "io/fs/file_system.h"
37
#include "io/fs/file_writer.h"
38
#include "io/fs/packed_slice_location.h"
39
#include "io/fs/path.h"
40
#include "util/slice.h"
41
42
namespace doris::cloud {
43
class PackedFileInfoPB;
44
}
45
46
namespace doris::io {
47
48
// Upload state of the packed file a slice belongs to
49
enum class PackedSliceUploadState : uint8_t {
50
    PENDING = 0,
51
    UPLOADED,
52
    FAILED,
53
};
54
55
// A slice of a packed file, shared by PackedFileManager and the PackedFileWriter that
56
// produced it. The writer holds its handle for as long as it lives, so it can wait for the
57
// upload and read the location back at the end of the load, whatever the manager recycled
58
// from its by-path index in the meantime.
59
class PackedSliceHandle {
60
public:
61
1.05k
    explicit PackedSliceHandle(PackedSliceLocation location) : _location(std::move(location)) {}
62
63
1.00k
    const std::string& packed_file_path() const { return _location.packed_file_path; }
64
65
1
    int64_t create_time() const { return _location.create_time; }
66
67
5.13k
    PackedSliceUploadState upload_state() const {
68
5.13k
        return _upload_state.load(std::memory_order_acquire);
69
5.13k
    }
70
71
    // Called once the packed file this slice belongs to reaches a terminal state
72
1.01k
    void set_upload_result(PackedSliceUploadState state, int64_t packed_file_size) {
73
1.01k
        if (state == PackedSliceUploadState::UPLOADED) {
74
1.00k
            _packed_file_size.store(packed_file_size, std::memory_order_relaxed);
75
1.00k
        }
76
1.01k
        _upload_state.store(state, std::memory_order_release);
77
1.01k
    }
78
79
4.12k
    PackedSliceLocation location() const {
80
4.12k
        PackedSliceLocation location = _location;
81
4.12k
        if (upload_state() == PackedSliceUploadState::UPLOADED) {
82
1.00k
            location.packed_file_size = _packed_file_size.load(std::memory_order_relaxed);
83
1.00k
        }
84
4.12k
        return location;
85
4.12k
    }
86
87
private:
88
    const PackedSliceLocation _location; // Immutable once the slice has been appended
89
    std::atomic<int64_t> _packed_file_size {-1};
90
    std::atomic<PackedSliceUploadState> _upload_state {PackedSliceUploadState::PENDING};
91
};
92
93
using PackedSliceHandlePtr = std::shared_ptr<PackedSliceHandle>;
94
95
struct PackedAppendContext {
96
    std::string resource_id;
97
    int64_t tablet_id = 0;
98
    std::string rowset_id;
99
    int64_t first_segment_id = 0;
100
    int64_t txn_id = 0;
101
    uint64_t expiration_time = 0; // TTL expiration time in seconds since epoch, 0 means no TTL
102
    bool write_file_cache = true; // Whether to write data to file cache
103
};
104
105
// Global object that manages packing small files into larger files for S3 optimization
106
class PackedFileManager {
107
    struct PackedFileContext;
108
109
public:
110
    static PackedFileManager* instance();
111
112
    // Initialize manager state; file system will be resolved lazily
113
    Status init();
114
115
    // Write a small file to the current packed file. On success `handle` receives a handle
116
    // to the new slice, or nullptr if `data` was too large to be packed.
117
    Status append_small_file(const std::string& path, const Slice& data,
118
                             const PackedAppendContext& info, PackedSliceHandlePtr* handle);
119
120
    // Block until the packed file holding `handle` is uploaded to S3
121
    Status wait_upload_done(const PackedSliceHandlePtr& handle);
122
123
    // Look a slice location up by small file path, for readers that have no handle to the
124
    // slice. The entry lives as long as anything else holds the slice, so this only fails
125
    // for a file whose writer and packed file context are both long gone.
126
    Status get_packed_slice_location(const std::string& path, PackedSliceLocation* location);
127
128
    // Start the background management thread
129
    void start_background_manager();
130
131
    // Stop the background management thread
132
    void stop_background_manager();
133
134
    // Mark current packed file for upload and create new one
135
    Status mark_current_packed_file_for_upload(const std::string& resource_id);
136
137
    // Internal helper; expects caller holds _current_packed_file_mutex
138
    Status mark_current_packed_file_for_upload_locked(const std::string& resource_id);
139
140
    void record_packed_file_metrics(const PackedFileContext& packed_file);
141
142
private:
143
47
    PackedFileManager() = default;
144
    ~PackedFileManager();
145
146
    DISALLOW_COPY_AND_ASSIGN(PackedFileManager);
147
148
    // Background thread function for managing packed file lifecycle
149
    void background_manager();
150
151
    // Upload packed file to S3 and update meta service
152
    Status finalize_packed_file_upload(const std::string& packed_file_path, FileWriter* writer);
153
154
    // Update meta service with packed file information
155
    // table_id is used for rate limiting; -1 means no specific table (cross-table operation)
156
    Status update_meta_service(const std::string& packed_file_path,
157
                               const cloud::PackedFileInfoPB& packed_file_info,
158
                               int64_t table_id = -1);
159
160
    // Process uploading files
161
    void process_uploading_packed_files();
162
163
    // Clean up expired data
164
    void cleanup_expired_data();
165
166
    // Record the terminal upload state of `packed_file` on the slices it contains
167
    void mark_slices_upload_result(const PackedFileContext& packed_file,
168
                                   PackedSliceUploadState state);
169
170
    // Internal structure to track packed file state
171
    enum class PackedFileState {
172
        INIT,            // Initial state, no files written yet
173
        ACTIVE,          // Has files but doesn't meet upload conditions
174
        READY_TO_UPLOAD, // Ready for upload, metadata still being prepared
175
        UPLOADING,       // Upload triggered, waiting for writer close to finish
176
        UPLOADED,        // Upload completed
177
        FAILED           // Upload failed
178
    };
179
180
    struct PackedFileContext {
181
        std::string packed_file_path;
182
        std::unique_ptr<FileWriter> writer;
183
        std::unordered_map<std::string, PackedSliceHandlePtr> slice_locations;
184
        // Every slice appended to this packed file. `slice_locations` is keyed by path, so
185
        // writing one path twice into the same packed file only leaves the last handle
186
        // there, while the upload result still has to reach both.
187
        std::vector<PackedSliceHandlePtr> appended_slices;
188
        int64_t current_offset = 0;
189
        int64_t total_size = 0;
190
        int64_t create_time;
191
        int64_t upload_time = 0;
192
        std::chrono::steady_clock::time_point create_timestamp;
193
        std::optional<std::chrono::steady_clock::time_point> first_append_timestamp;
194
        std::optional<std::chrono::steady_clock::time_point> ready_to_upload_timestamp;
195
        std::optional<std::chrono::steady_clock::time_point> uploading_timestamp;
196
        std::atomic<PackedFileState> state {PackedFileState::INIT};
197
        std::condition_variable upload_cv;
198
        std::mutex upload_mutex;
199
        std::string last_error;
200
        std::string resource_id;
201
        FileSystemSPtr file_system;
202
    };
203
204
    // Create a new packed file state with file writer
205
    Status create_new_packed_file_context(const std::string& resource_id,
206
                                          std::unique_ptr<PackedFileContext>& packed_file_ctx);
207
208
    Status ensure_file_system(const std::string& resource_id, FileSystemSPtr* file_system);
209
210
    // Helper function to wait for packed file upload completion
211
    Status wait_for_packed_file_upload(PackedFileContext* packed_file_ptr);
212
213
    // Thread management
214
    std::atomic<bool> _stop_background_thread {false};
215
    std::unique_ptr<std::thread> _background_thread;
216
217
    // File system
218
    FileSystemSPtr _default_file_system;
219
    std::unordered_map<std::string, FileSystemSPtr> _file_systems;
220
    std::mutex _file_system_mutex;
221
222
    // Current active packed file
223
    std::unordered_map<std::string, std::unique_ptr<PackedFileContext>> _current_packed_files;
224
    std::timed_mutex _current_packed_file_mutex;
225
226
    // Merge files ready for upload or being processed
227
    std::unordered_map<std::string, std::shared_ptr<PackedFileContext>> _uploading_packed_files;
228
229
    // Uploaded packed files (kept for some time for wait_write_done)
230
    std::unordered_map<std::string, std::shared_ptr<PackedFileContext>> _uploaded_packed_files;
231
    std::mutex _packed_files_mutex;
232
233
    // Global index mapping small file path to packed file index, for readers that have no
234
    // handle to the slice, such as PackedFileSystem::open_file_impl() reading a segment back
235
    // before its rowset meta exists. An entry is only recycled once nothing else holds the
236
    // slice, so it outlives every writer and packed file context that could still read it.
237
    std::unordered_map<std::string, PackedSliceHandlePtr> _global_slice_locations;
238
    std::mutex _global_index_mutex;
239
240
#ifdef BE_TEST
241
public:
242
    void reset_packed_file_bvars_for_test() const;
243
    int64_t packed_file_total_count_for_test() const;
244
    int64_t packed_file_total_small_file_num_for_test() const;
245
    int64_t packed_file_total_size_bytes_for_test() const;
246
    double packed_file_avg_small_file_num_for_test() const;
247
    double packed_file_avg_file_size_for_test() const;
248
    void record_packed_file_metrics_for_test(const PackedFileContext* packed_file);
249
250
    // Test-only helpers to introspect/clear internal state
251
    void clear_state_for_test();
252
    auto& current_packed_files_for_test() { return _current_packed_files; }
253
    auto& uploading_packed_files_for_test() { return _uploading_packed_files; }
254
    auto& uploaded_packed_files_for_test() { return _uploaded_packed_files; }
255
    auto& global_slice_locations_for_test() { return _global_slice_locations; }
256
    auto& file_systems_for_test() { return _file_systems; }
257
    FileSystemSPtr& default_file_system_for_test() { return _default_file_system; }
258
    Status create_new_packed_file_state_for_test(const std::string& resource_id,
259
                                                 std::unique_ptr<PackedFileContext>& ctx) {
260
        return create_new_packed_file_context(resource_id, ctx);
261
    }
262
#endif
263
};
264
265
} // namespace doris::io