Coverage Report

Created: 2026-04-16 14:28

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
154
SpillFileManager::~SpillFileManager() {
41
154
    DorisMetrics::instance()->metric_registry()->deregister_entity(_entity);
42
154
}
43
44
SpillFileManager::SpillFileManager(
45
        std::unordered_map<std::string, std::unique_ptr<SpillDataDir>>&& spill_store_map)
46
179
        : _spill_store_map(std::move(spill_store_map)), _stop_background_threads_latch(1) {}
47
48
179
Status SpillFileManager::init() {
49
179
    LOG(INFO) << "init spill stream manager";
50
179
    RETURN_IF_ERROR(_init_spill_store_map());
51
52
179
    for (const auto& [path, store] : _spill_store_map) {
53
179
        auto gc_dir_root_dir = store->get_spill_data_gc_path();
54
179
        bool exists = true;
55
179
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(gc_dir_root_dir, &exists));
56
179
        if (!exists) {
57
77
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(gc_dir_root_dir));
58
77
        }
59
60
179
        auto spill_dir = store->get_spill_data_path();
61
179
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(spill_dir, &exists));
62
179
        if (!exists) {
63
77
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
64
102
        } else {
65
102
            auto suffix = ToStringFromUnixMillis(UnixMillis());
66
102
            auto gc_dir = store->get_spill_data_gc_path(suffix);
67
102
            if (std::filesystem::exists(gc_dir)) {
68
0
                LOG(WARNING) << "gc dir already exists: " << gc_dir;
69
0
            }
70
102
            (void)io::global_local_filesystem()->rename(spill_dir, gc_dir);
71
102
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(spill_dir));
72
102
        }
73
179
    }
74
75
179
    RETURN_IF_ERROR(Thread::create(
76
179
            "Spill", "spill_gc_thread", [this]() { this->_spill_gc_thread_callback(); },
77
179
            &_spill_gc_thread));
78
179
    LOG(INFO) << "spill gc thread started";
79
80
179
    _init_metrics();
81
82
179
    return Status::OK();
83
179
}
84
85
179
void SpillFileManager::_init_metrics() {
86
179
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("spill",
87
179
                                                                           {{"name", "spill"}});
88
89
179
    _spill_write_bytes_metric = std::make_unique<doris::MetricPrototype>(
90
179
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_write_bytes");
91
179
    _spill_write_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
92
179
            _spill_write_bytes_metric.get()));
93
94
179
    _spill_read_bytes_metric = std::make_unique<doris::MetricPrototype>(
95
179
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_read_bytes");
96
179
    _spill_read_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
97
179
            _spill_read_bytes_metric.get()));
98
179
}
99
100
// clean up stale spilled files
101
179
void SpillFileManager::_spill_gc_thread_callback() {
102
18.7k
    while (!_stop_background_threads_latch.wait_for(
103
18.7k
            std::chrono::milliseconds(config::spill_gc_interval_ms))) {
104
18.5k
        gc(config::spill_gc_work_time_ms);
105
18.5k
        for (auto& [path, dir] : _spill_store_map) {
106
18.2k
            static_cast<void>(dir->update_capacity());
107
18.2k
        }
108
18.5k
    }
109
179
}
110
111
179
Status SpillFileManager::_init_spill_store_map() {
112
179
    for (const auto& store : _spill_store_map) {
113
179
        RETURN_IF_ERROR(store.second->init());
114
179
    }
115
116
179
    return Status::OK();
117
179
}
118
119
std::vector<SpillDataDir*> SpillFileManager::_get_stores_for_spill(
120
652
        TStorageMedium::type storage_medium) {
121
652
    std::vector<std::pair<SpillDataDir*, double>> stores_with_usage;
122
652
    for (auto& [_, store] : _spill_store_map) {
123
652
        if (store->storage_medium() == storage_medium && !store->reach_capacity_limit(0)) {
124
326
            stores_with_usage.emplace_back(store.get(), store->_get_disk_usage(0));
125
326
        }
126
652
    }
127
652
    if (stores_with_usage.empty()) {
128
326
        return {};
129
326
    }
130
131
326
    std::ranges::sort(stores_with_usage, [](auto&& a, auto&& b) { return a.second < b.second; });
132
133
326
    std::vector<SpillDataDir*> stores;
134
326
    for (const auto& [store, _] : stores_with_usage) {
135
326
        stores.emplace_back(store);
136
326
    }
137
326
    return stores;
138
652
}
139
140
Status SpillFileManager::create_spill_file(const std::string& relative_path,
141
326
                                           SpillFileSPtr& spill_file) {
142
326
    auto data_dirs = _get_stores_for_spill(TStorageMedium::type::SSD);
143
326
    if (data_dirs.empty()) {
144
326
        data_dirs = _get_stores_for_spill(TStorageMedium::type::HDD);
145
326
    }
146
326
    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
326
    SpillDataDir* data_dir = data_dirs.front();
153
326
    spill_file = std::make_shared<SpillFile>(data_dir, relative_path);
154
326
    return Status::OK();
155
326
}
156
157
112
void SpillFileManager::delete_spill_file(SpillFileSPtr spill_file) {
158
112
    if (!spill_file) {
159
0
        LOG(WARNING) << "[spill][delete] null spill_file";
160
0
        return;
161
0
    }
162
112
    spill_file->gc();
163
112
}
164
165
18.8k
void SpillFileManager::gc(int32_t max_work_time_ms) {
166
18.8k
    bool exists = true;
167
18.8k
    bool has_work = false;
168
18.8k
    int64_t max_work_time_ns = max_work_time_ms * 1000L * 1000L;
169
18.8k
    MonotonicStopWatch watch;
170
18.8k
    watch.start();
171
18.8k
    Defer defer {[&]() {
172
17.8k
        if (has_work) {
173
4
            std::string msg(
174
4
                    fmt::format("spill gc time: {}",
175
4
                                PrettyPrinter::print(watch.elapsed_time(), TUnit::TIME_NS)));
176
4
            msg += ", spill storage:\n";
177
4
            for (const auto& [path, store_dir] : _spill_store_map) {
178
4
                msg += "    " + store_dir->debug_string();
179
4
                msg += "\n";
180
4
            }
181
4
            LOG(INFO) << msg;
182
4
        }
183
17.8k
    }};
184
18.8k
    for (const auto& [path, store_dir] : _spill_store_map) {
185
17.9k
        std::string gc_root_dir = store_dir->get_spill_data_gc_path();
186
187
17.9k
        std::error_code ec;
188
17.9k
        exists = std::filesystem::exists(gc_root_dir, ec);
189
17.9k
        if (ec || !exists) {
190
17.4k
            continue;
191
17.4k
        }
192
        // dirs of queries
193
508
        std::vector<io::FileInfo> dirs;
194
508
        auto st = io::global_local_filesystem()->list(gc_root_dir, false, &dirs, &exists);
195
508
        if (!st.ok()) {
196
0
            continue;
197
0
        }
198
199
508
        for (const auto& dir : dirs) {
200
152
            has_work = true;
201
152
            if (dir.is_file) {
202
0
                continue;
203
0
            }
204
152
            std::string abs_dir = fmt::format("{}/{}", gc_root_dir, dir.file_name);
205
            // operator spill sub dirs of a query
206
152
            std::vector<io::FileInfo> files;
207
152
            st = io::global_local_filesystem()->list(abs_dir, false, &files, &exists);
208
152
            if (!st.ok()) {
209
0
                continue;
210
0
            }
211
152
            if (files.empty()) {
212
102
                static_cast<void>(io::global_local_filesystem()->delete_directory(abs_dir));
213
102
                continue;
214
102
            }
215
216
50
            for (const auto& file : files) {
217
50
                auto abs_file_path = fmt::format("{}/{}", abs_dir, file.file_name);
218
50
                if (file.is_file) {
219
0
                    static_cast<void>(io::global_local_filesystem()->delete_file(abs_file_path));
220
50
                } else {
221
50
                    static_cast<void>(
222
50
                            io::global_local_filesystem()->delete_directory(abs_file_path));
223
50
                }
224
50
                if (watch.elapsed_time() > max_work_time_ns) {
225
0
                    break;
226
0
                }
227
50
            }
228
50
        }
229
508
    }
230
18.8k
}
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
179
        : _path(std::move(path)),
242
179
          _disk_capacity_bytes(capacity_bytes),
243
179
          _storage_medium(storage_medium) {
244
179
    spill_data_dir_metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
245
179
            std::string("spill_data_dir.") + _path, {{"path", _path + "/" + SPILL_DIR_PREFIX}});
246
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_capacity);
247
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_limit);
248
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_avail_capacity);
249
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_data_size);
250
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_data);
251
179
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_gc_data);
252
179
}
253
254
366
bool is_directory_empty(const std::filesystem::path& dir) {
255
366
    try {
256
366
        return std::filesystem::is_directory(dir) &&
257
366
               std::filesystem::directory_iterator(dir) ==
258
212
                       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
366
    } catch (const std::filesystem::filesystem_error&) {
262
0
        return true;
263
0
    }
264
366
}
265
266
179
Status SpillDataDir::init() {
267
179
    bool exists = false;
268
179
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(_path, &exists));
269
179
    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
179
    RETURN_IF_ERROR(update_capacity());
274
179
    LOG(INFO) << fmt::format(
275
179
            "spill storage path: {}, capacity: {}, limit: {}, available: "
276
179
            "{}",
277
179
            _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
278
179
            PrettyPrinter::print_bytes(_spill_data_limit_bytes),
279
179
            PrettyPrinter::print_bytes(_available_bytes));
280
179
    return Status::OK();
281
179
}
282
283
689
std::string SpillDataDir::get_spill_data_path(const std::string& query_id) const {
284
689
    auto dir = fmt::format("{}/{}", _path, SPILL_DIR_PREFIX);
285
689
    if (!query_id.empty()) {
286
0
        dir = fmt::format("{}/{}", dir, query_id);
287
0
    }
288
689
    return dir;
289
689
}
290
291
18.2k
std::string SpillDataDir::get_spill_data_gc_path(const std::string& sub_dir_name) const {
292
18.2k
    auto dir = fmt::format("{}/{}", _path, SPILL_GC_DIR_PREFIX);
293
18.2k
    if (!sub_dir_name.empty()) {
294
102
        dir = fmt::format("{}/{}", dir, sub_dir_name);
295
102
    }
296
18.2k
    return dir;
297
18.2k
}
298
299
18.2k
Status SpillDataDir::update_capacity() {
300
18.2k
    std::lock_guard<std::mutex> l(_mutex);
301
18.2k
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
302
18.2k
                                                                  &_available_bytes));
303
406
    spill_disk_capacity->set_value(_disk_capacity_bytes);
304
406
    spill_disk_avail_capacity->set_value(_available_bytes);
305
406
    auto disk_use_max_bytes =
306
406
            (int64_t)(_disk_capacity_bytes * config::storage_flood_stage_usage_percent / 100);
307
406
    bool is_percent = true;
308
406
    _spill_data_limit_bytes = ParseUtil::parse_mem_spec(config::spill_storage_limit, -1,
309
406
                                                        _disk_capacity_bytes, &is_percent);
310
406
    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
406
    if (is_percent) {
318
183
        _spill_data_limit_bytes = (int64_t)(_spill_data_limit_bytes *
319
183
                                            config::storage_flood_stage_usage_percent / 100);
320
183
    }
321
406
    _spill_data_limit_bytes = std::min(_spill_data_limit_bytes, disk_use_max_bytes);
322
406
    spill_disk_limit->set_value(_spill_data_limit_bytes);
323
324
406
    std::string spill_root_dir = get_spill_data_path();
325
406
    std::string spill_gc_root_dir = get_spill_data_gc_path();
326
406
    spill_disk_has_spill_data->set_value(is_directory_empty(spill_root_dir) ? 0 : 1);
327
406
    spill_disk_has_spill_gc_data->set_value(is_directory_empty(spill_gc_root_dir) ? 0 : 1);
328
329
406
    return Status::OK();
330
406
}
331
332
766
bool SpillDataDir::_reach_disk_capacity_limit(int64_t incoming_data_size) {
333
766
    double used_pct = _get_disk_usage(incoming_data_size);
334
766
    int64_t left_bytes = _available_bytes - incoming_data_size;
335
766
    if (used_pct >= config::storage_flood_stage_usage_percent / 100.0 &&
336
766
        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
766
    return false;
342
766
}
343
766
bool SpillDataDir::reach_capacity_limit(int64_t incoming_data_size) {
344
766
    std::lock_guard<std::mutex> l(_mutex);
345
766
    if (_reach_disk_capacity_limit(incoming_data_size)) {
346
0
        return true;
347
0
    }
348
766
    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
766
    return false;
363
766
}
364
4
std::string SpillDataDir::debug_string() {
365
4
    return fmt::format(
366
4
            "path: {}, capacity: {}, limit: {}, used: {}, available: "
367
4
            "{}",
368
4
            _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
369
4
            PrettyPrinter::print_bytes(_spill_data_limit_bytes),
370
4
            PrettyPrinter::print_bytes(_spill_data_bytes),
371
4
            PrettyPrinter::print_bytes(_available_bytes));
372
4
}
373
} // namespace doris