Coverage Report

Created: 2026-06-11 11:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/spill/spill_file_manager.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/spill/spill_file_manager.h"
19
20
#include <fmt/format.h>
21
#include <glog/logging.h>
22
23
#include <algorithm>
24
#include <filesystem>
25
#include <memory>
26
#include <string>
27
28
#include "common/logging.h"
29
#include "common/metrics/doris_metrics.h"
30
#include "exec/spill/spill_file.h"
31
#include "io/fs/file_system.h"
32
#include "io/fs/local_file_system.h"
33
#include "storage/olap_define.h"
34
#include "util/parse_util.h"
35
#include "util/pretty_printer.h"
36
#include "util/time.h"
37
38
namespace doris {
39
40
168
SpillFileManager::~SpillFileManager() {
41
168
    DorisMetrics::instance()->metric_registry()->deregister_entity(_entity);
42
168
}
43
44
SpillFileManager::SpillFileManager(
45
        std::unordered_map<std::string, std::unique_ptr<SpillDataDir>>&& spill_store_map)
46
198
        : _spill_store_map(std::move(spill_store_map)), _stop_background_threads_latch(1) {}
47
48
198
Status SpillFileManager::init() {
49
198
    LOG(INFO) << "init spill stream manager";
50
198
    RETURN_IF_ERROR(_init_spill_store_map());
51
52
202
    for (const auto& [path, store] : _spill_store_map) {
53
202
        auto gc_dir_root_dir = store->get_spill_data_gc_path();
54
202
        bool exists = true;
55
202
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(gc_dir_root_dir, &exists));
56
202
        if (!exists) {
57
79
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(gc_dir_root_dir));
58
79
        }
59
60
202
        auto spill_dir = store->get_spill_data_path();
61
202
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(spill_dir, &exists));
62
202
        if (!exists) {
63
79
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
64
123
        } else {
65
123
            auto suffix = ToStringFromUnixMillis(UnixMillis());
66
123
            auto gc_dir = store->get_spill_data_gc_path(suffix);
67
123
            if (std::filesystem::exists(gc_dir)) {
68
0
                LOG(WARNING) << "gc dir already exists: " << gc_dir;
69
0
            }
70
123
            (void)io::global_local_filesystem()->rename(spill_dir, gc_dir);
71
123
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
72
123
        }
73
202
    }
74
75
198
    RETURN_IF_ERROR(Thread::create(
76
198
            "Spill", "spill_gc_thread", [this]() { this->_spill_gc_thread_callback(); },
77
198
            &_spill_gc_thread));
78
198
    LOG(INFO) << "spill gc thread started";
79
80
198
    _init_metrics();
81
82
198
    return Status::OK();
83
198
}
84
85
198
void SpillFileManager::_init_metrics() {
86
198
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("spill",
87
198
                                                                           {{"name", "spill"}});
88
89
198
    _spill_write_bytes_metric = std::make_unique<doris::MetricPrototype>(
90
198
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_write_bytes");
91
198
    _spill_write_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
92
198
            _spill_write_bytes_metric.get()));
93
94
198
    _spill_read_bytes_metric = std::make_unique<doris::MetricPrototype>(
95
198
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_read_bytes");
96
198
    _spill_read_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
97
198
            _spill_read_bytes_metric.get()));
98
198
}
99
100
// clean up stale spilled files
101
198
void SpillFileManager::_spill_gc_thread_callback() {
102
21.5k
    while (!_stop_background_threads_latch.wait_for(
103
21.5k
            std::chrono::milliseconds(config::spill_gc_interval_ms))) {
104
21.3k
        gc(config::spill_gc_work_time_ms);
105
21.3k
        for (auto& [path, dir] : _spill_store_map) {
106
20.7k
            static_cast<void>(dir->update_capacity());
107
20.7k
        }
108
21.3k
    }
109
198
}
110
111
198
Status SpillFileManager::_init_spill_store_map() {
112
202
    for (const auto& store : _spill_store_map) {
113
202
        RETURN_IF_ERROR(store.second->init());
114
202
    }
115
116
198
    return Status::OK();
117
198
}
118
119
std::vector<SpillDataDir*> SpillFileManager::_get_stores_for_spill(
120
656
        TStorageMedium::type storage_medium) {
121
656
    std::vector<std::pair<SpillDataDir*, double>> stores_with_usage;
122
656
    for (auto& [_, store] : _spill_store_map) {
123
656
        if (store->storage_medium() == storage_medium && !store->reach_capacity_limit(0)) {
124
328
            stores_with_usage.emplace_back(store.get(), store->_get_disk_usage(0));
125
328
        }
126
656
    }
127
656
    if (stores_with_usage.empty()) {
128
328
        return {};
129
328
    }
130
131
328
    std::ranges::sort(stores_with_usage, [](auto&& a, auto&& b) { return a.second < b.second; });
132
133
328
    std::vector<SpillDataDir*> stores;
134
328
    for (const auto& [store, _] : stores_with_usage) {
135
328
        stores.emplace_back(store);
136
328
    }
137
328
    return stores;
138
656
}
139
140
Status SpillFileManager::create_spill_file(const std::string& relative_path,
141
328
                                           SpillFileSPtr& spill_file) {
142
328
    auto data_dirs = _get_stores_for_spill(TStorageMedium::type::SSD);
143
328
    if (data_dirs.empty()) {
144
328
        data_dirs = _get_stores_for_spill(TStorageMedium::type::HDD);
145
328
    }
146
328
    if (data_dirs.empty()) {
147
0
        return Status::Error<ErrorCode::NO_AVAILABLE_ROOT_PATH>(
148
0
                "no available disk can be used for spill.");
149
0
    }
150
151
    // Select the first available data dir (sorted by usage ascending)
152
328
    SpillDataDir* data_dir = data_dirs.front();
153
328
    spill_file = std::make_shared<SpillFile>(data_dir, relative_path);
154
328
    return Status::OK();
155
328
}
156
157
140
void SpillFileManager::delete_spill_file(SpillFileSPtr spill_file) {
158
140
    if (!spill_file) {
159
0
        LOG(WARNING) << "[spill][delete] null spill_file";
160
0
        return;
161
0
    }
162
140
    spill_file->gc();
163
140
}
164
165
21.6k
void SpillFileManager::gc(int32_t max_work_time_ms) {
166
21.6k
    bool exists = true;
167
21.6k
    bool has_work = false;
168
21.6k
    int64_t max_work_time_ns = max_work_time_ms * 1000L * 1000L;
169
21.6k
    MonotonicStopWatch watch;
170
21.6k
    watch.start();
171
21.6k
    Defer defer {[&]() {
172
19.5k
        if (has_work) {
173
14
            std::string msg(
174
14
                    fmt::format("spill gc time: {}",
175
14
                                PrettyPrinter::print(watch.elapsed_time(), TUnit::TIME_NS)));
176
14
            msg += ", spill storage:\n";
177
22
            for (const auto& [path, store_dir] : _spill_store_map) {
178
22
                msg += "    " + store_dir->debug_string();
179
22
                msg += "\n";
180
22
            }
181
14
            LOG(INFO) << msg;
182
14
        }
183
19.5k
    }};
184
21.6k
    for (const auto& [path, store_dir] : _spill_store_map) {
185
21.2k
        std::string gc_root_dir = store_dir->get_spill_data_gc_path();
186
187
21.2k
        std::error_code ec;
188
21.2k
        exists = std::filesystem::exists(gc_root_dir, ec);
189
21.2k
        if (ec || !exists) {
190
16.7k
            continue;
191
16.7k
        }
192
        // dirs of queries
193
4.52k
        std::vector<io::FileInfo> dirs;
194
4.52k
        auto st = io::global_local_filesystem()->list(gc_root_dir, false, &dirs, &exists);
195
4.52k
        if (!st.ok()) {
196
0
            continue;
197
0
        }
198
199
4.52k
        for (const auto& dir : dirs) {
200
177
            has_work = true;
201
177
            if (dir.is_file) {
202
0
                continue;
203
0
            }
204
177
            std::string abs_dir = fmt::format("{}/{}", gc_root_dir, dir.file_name);
205
            // operator spill sub dirs of a query
206
177
            std::vector<io::FileInfo> files;
207
177
            st = io::global_local_filesystem()->list(abs_dir, false, &files, &exists);
208
177
            if (!st.ok()) {
209
0
                continue;
210
0
            }
211
177
            if (files.empty()) {
212
123
                static_cast<void>(io::global_local_filesystem()->delete_directory(abs_dir));
213
123
                continue;
214
123
            }
215
216
218
            for (const auto& file : files) {
217
218
                auto abs_file_path = fmt::format("{}/{}", abs_dir, file.file_name);
218
218
                if (file.is_file) {
219
0
                    static_cast<void>(io::global_local_filesystem()->delete_file(abs_file_path));
220
218
                } else {
221
218
                    static_cast<void>(
222
218
                            io::global_local_filesystem()->delete_directory(abs_file_path));
223
218
                }
224
218
                if (watch.elapsed_time() > max_work_time_ns) {
225
0
                    break;
226
0
                }
227
218
            }
228
54
        }
229
4.52k
    }
230
21.6k
}
231
232
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_capacity, MetricUnit::BYTES);
233
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_limit, MetricUnit::BYTES);
234
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_avail_capacity, MetricUnit::BYTES);
235
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_data_size, MetricUnit::BYTES);
236
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_has_spill_data, MetricUnit::BYTES);
237
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(spill_disk_has_spill_gc_data, MetricUnit::BYTES);
238
239
SpillDataDir::SpillDataDir(std::string path, int64_t capacity_bytes,
240
                           TStorageMedium::type storage_medium)
241
202
        : _path(std::move(path)),
242
202
          _disk_capacity_bytes(capacity_bytes),
243
202
          _storage_medium(storage_medium) {
244
202
    spill_data_dir_metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
245
202
            std::string("spill_data_dir.") + _path, {{"path", _path + "/" + SPILL_DIR_PREFIX}});
246
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_capacity);
247
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_limit);
248
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_avail_capacity);
249
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_data_size);
250
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_data);
251
202
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_gc_data);
252
202
}
253
254
7.28k
bool is_directory_empty(const std::filesystem::path& dir) {
255
7.28k
    try {
256
7.28k
        return std::filesystem::is_directory(dir) &&
257
7.28k
               std::filesystem::directory_iterator(dir) ==
258
7.13k
                       std::filesystem::end(std::filesystem::directory_iterator {});
259
        // this method is not thread safe, the file referenced by directory_iterator
260
        // maybe moved to spill_gc dir during this function call, so need to catch expection
261
7.28k
    } catch (const std::filesystem::filesystem_error&) {
262
0
        return true;
263
0
    }
264
7.28k
}
265
266
202
Status SpillDataDir::init() {
267
202
    bool exists = false;
268
202
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(_path, &exists));
269
202
    if (!exists) {
270
0
        RETURN_NOT_OK_STATUS_WITH_WARN(Status::IOError("opendir failed, path={}", _path),
271
0
                                       "check file exist failed");
272
0
    }
273
202
    RETURN_IF_ERROR(update_capacity());
274
202
    LOG(INFO) << fmt::format(
275
202
            "spill storage path: {}, capacity: {}, limit: {}, available: "
276
202
            "{}",
277
202
            _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
278
202
            PrettyPrinter::print_bytes(_spill_data_limit_bytes),
279
202
            PrettyPrinter::print_bytes(_available_bytes));
280
202
    return Status::OK();
281
202
}
282
283
4.17k
std::string SpillDataDir::get_spill_data_path(const std::string& query_id) const {
284
4.17k
    auto dir = fmt::format("{}/{}", _path, SPILL_DIR_PREFIX);
285
4.17k
    if (!query_id.empty()) {
286
0
        dir = fmt::format("{}/{}", dir, query_id);
287
0
    }
288
4.17k
    return dir;
289
4.17k
}
290
291
24.7k
std::string SpillDataDir::get_spill_data_gc_path(const std::string& sub_dir_name) const {
292
24.7k
    auto dir = fmt::format("{}/{}", _path, SPILL_GC_DIR_PREFIX);
293
24.7k
    if (!sub_dir_name.empty()) {
294
123
        dir = fmt::format("{}/{}", dir, sub_dir_name);
295
123
    }
296
24.7k
    return dir;
297
24.7k
}
298
299
21.2k
Status SpillDataDir::update_capacity() {
300
21.2k
    std::lock_guard<std::mutex> l(_mutex);
301
21.2k
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
302
21.2k
                                                                  &_available_bytes));
303
3.92k
    spill_disk_capacity->set_value(_disk_capacity_bytes);
304
3.92k
    spill_disk_avail_capacity->set_value(_available_bytes);
305
3.92k
    auto disk_use_max_bytes =
306
3.92k
            (int64_t)(_disk_capacity_bytes * config::storage_flood_stage_usage_percent / 100);
307
3.92k
    bool is_percent = true;
308
3.92k
    _spill_data_limit_bytes = ParseUtil::parse_mem_spec(config::spill_storage_limit, -1,
309
3.92k
                                                        _disk_capacity_bytes, &is_percent);
310
3.92k
    if (_spill_data_limit_bytes <= 0) {
311
0
        spill_disk_limit->set_value(_spill_data_limit_bytes);
312
0
        auto err_msg = fmt::format("Failed to parse spill storage limit from '{}'",
313
0
                                   config::spill_storage_limit);
314
0
        LOG(WARNING) << err_msg;
315
0
        return Status::InvalidArgument(err_msg);
316
0
    }
317
3.92k
    if (is_percent) {
318
3.64k
        _spill_data_limit_bytes = (int64_t)(_spill_data_limit_bytes *
319
3.64k
                                            config::storage_flood_stage_usage_percent / 100);
320
3.64k
    }
321
3.92k
    _spill_data_limit_bytes = std::min(_spill_data_limit_bytes, disk_use_max_bytes);
322
3.92k
    spill_disk_limit->set_value(_spill_data_limit_bytes);
323
324
3.92k
    std::string spill_root_dir = get_spill_data_path();
325
3.92k
    std::string spill_gc_root_dir = get_spill_data_gc_path();
326
3.92k
    spill_disk_has_spill_data->set_value(is_directory_empty(spill_root_dir) ? 0 : 1);
327
3.92k
    spill_disk_has_spill_gc_data->set_value(is_directory_empty(spill_gc_root_dir) ? 0 : 1);
328
329
3.92k
    return Status::OK();
330
3.92k
}
331
332
770
bool SpillDataDir::_reach_disk_capacity_limit(int64_t incoming_data_size) {
333
770
    double used_pct = _get_disk_usage(incoming_data_size);
334
770
    int64_t left_bytes = _available_bytes - incoming_data_size;
335
770
    if (used_pct >= config::storage_flood_stage_usage_percent / 100.0 &&
336
770
        left_bytes <= config::storage_flood_stage_left_capacity_bytes) {
337
0
        LOG(WARNING) << "reach capacity limit. used pct: " << used_pct
338
0
                     << ", left bytes: " << left_bytes << ", path: " << _path;
339
0
        return true;
340
0
    }
341
770
    return false;
342
770
}
343
770
bool SpillDataDir::reach_capacity_limit(int64_t incoming_data_size) {
344
770
    std::lock_guard<std::mutex> l(_mutex);
345
770
    if (_reach_disk_capacity_limit(incoming_data_size)) {
346
0
        return true;
347
0
    }
348
770
    if (_spill_data_bytes + incoming_data_size > _spill_data_limit_bytes) {
349
0
        LOG_EVERY_T(WARNING, 1) << fmt::format(
350
0
                "spill data reach limit, path: {}, capacity: {}, limit: {}, used: {}, "
351
0
                "available: "
352
0
                "{}, "
353
0
                "incoming "
354
0
                "bytes: {}",
355
0
                _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
356
0
                PrettyPrinter::print_bytes(_spill_data_limit_bytes),
357
0
                PrettyPrinter::print_bytes(_spill_data_bytes),
358
0
                PrettyPrinter::print_bytes(_available_bytes),
359
0
                PrettyPrinter::print_bytes(incoming_data_size));
360
0
        return true;
361
0
    }
362
770
    return false;
363
770
}
364
22
std::string SpillDataDir::debug_string() {
365
22
    return fmt::format(
366
22
            "path: {}, capacity: {}, limit: {}, used: {}, available: "
367
22
            "{}",
368
22
            _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
369
22
            PrettyPrinter::print_bytes(_spill_data_limit_bytes),
370
22
            PrettyPrinter::print_bytes(_spill_data_bytes),
371
22
            PrettyPrinter::print_bytes(_available_bytes));
372
22
}
373
} // namespace doris