Coverage Report

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