Coverage Report

Created: 2026-04-20 10:23

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
187
        : _spill_store_map(std::move(spill_store_map)), _stop_background_threads_latch(1) {}
47
48
187
Status SpillFileManager::init() {
49
187
    LOG(INFO) << "init spill stream manager";
50
187
    RETURN_IF_ERROR(_init_spill_store_map());
51
52
191
    for (const auto& [path, store] : _spill_store_map) {
53
191
        auto gc_dir_root_dir = store->get_spill_data_gc_path();
54
191
        bool exists = true;
55
191
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(gc_dir_root_dir, &exists));
56
191
        if (!exists) {
57
81
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(gc_dir_root_dir));
58
81
        }
59
60
191
        auto spill_dir = store->get_spill_data_path();
61
191
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(spill_dir, &exists));
62
191
        if (!exists) {
63
81
            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
191
    }
74
75
187
    RETURN_IF_ERROR(Thread::create(
76
187
            "Spill", "spill_gc_thread", [this]() { this->_spill_gc_thread_callback(); },
77
187
            &_spill_gc_thread));
78
187
    LOG(INFO) << "spill gc thread started";
79
80
187
    _init_metrics();
81
82
187
    return Status::OK();
83
187
}
84
85
187
void SpillFileManager::_init_metrics() {
86
187
    _entity = DorisMetrics::instance()->metric_registry()->register_entity("spill",
87
187
                                                                           {{"name", "spill"}});
88
89
187
    _spill_write_bytes_metric = std::make_unique<doris::MetricPrototype>(
90
187
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_write_bytes");
91
187
    _spill_write_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
92
187
            _spill_write_bytes_metric.get()));
93
94
187
    _spill_read_bytes_metric = std::make_unique<doris::MetricPrototype>(
95
187
            doris::MetricType::COUNTER, doris::MetricUnit::BYTES, "spill_read_bytes");
96
187
    _spill_read_bytes_counter = (IntAtomicCounter*)(_entity->register_metric<IntAtomicCounter>(
97
187
            _spill_read_bytes_metric.get()));
98
187
}
99
100
// clean up stale spilled files
101
187
void SpillFileManager::_spill_gc_thread_callback() {
102
24.4k
    while (!_stop_background_threads_latch.wait_for(
103
24.4k
            std::chrono::milliseconds(config::spill_gc_interval_ms))) {
104
24.2k
        gc(config::spill_gc_work_time_ms);
105
24.2k
        for (auto& [path, dir] : _spill_store_map) {
106
24.2k
            static_cast<void>(dir->update_capacity());
107
24.2k
        }
108
24.2k
    }
109
187
}
110
111
187
Status SpillFileManager::_init_spill_store_map() {
112
191
    for (const auto& store : _spill_store_map) {
113
191
        RETURN_IF_ERROR(store.second->init());
114
191
    }
115
116
187
    return Status::OK();
117
187
}
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.1k
void SpillFileManager::gc(int32_t max_work_time_ms) {
166
25.1k
    bool exists = true;
167
25.1k
    bool has_work = false;
168
25.1k
    int64_t max_work_time_ns = max_work_time_ms * 1000L * 1000L;
169
25.1k
    MonotonicStopWatch watch;
170
25.1k
    watch.start();
171
25.1k
    Defer defer {[&]() {
172
23.5k
        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.5k
    }};
184
25.1k
    for (const auto& [path, store_dir] : _spill_store_map) {
185
23.7k
        std::string gc_root_dir = store_dir->get_spill_data_gc_path();
186
187
23.7k
        std::error_code ec;
188
23.7k
        exists = std::filesystem::exists(gc_root_dir, ec);
189
23.7k
        if (ec || !exists) {
190
15.9k
            continue;
191
15.9k
        }
192
        // dirs of queries
193
7.74k
        std::vector<io::FileInfo> dirs;
194
7.74k
        auto st = io::global_local_filesystem()->list(gc_root_dir, false, &dirs, &exists);
195
7.74k
        if (!st.ok()) {
196
0
            continue;
197
0
        }
198
199
7.74k
        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
320
            for (const auto& file : files) {
217
320
                auto abs_file_path = fmt::format("{}/{}", abs_dir, file.file_name);
218
320
                if (file.is_file) {
219
0
                    static_cast<void>(io::global_local_filesystem()->delete_file(abs_file_path));
220
320
                } else {
221
320
                    static_cast<void>(
222
320
                            io::global_local_filesystem()->delete_directory(abs_file_path));
223
320
                }
224
320
                if (watch.elapsed_time() > max_work_time_ns) {
225
0
                    break;
226
0
                }
227
320
            }
228
54
        }
229
7.74k
    }
230
25.1k
}
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
191
        : _path(std::move(path)),
242
191
          _disk_capacity_bytes(capacity_bytes),
243
191
          _storage_medium(storage_medium) {
244
191
    spill_data_dir_metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
245
191
            std::string("spill_data_dir.") + _path, {{"path", _path + "/" + SPILL_DIR_PREFIX}});
246
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_capacity);
247
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_limit);
248
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_avail_capacity);
249
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_data_size);
250
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_data);
251
191
    INT_GAUGE_METRIC_REGISTER(spill_data_dir_metric_entity, spill_disk_has_spill_gc_data);
252
191
}
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
191
Status SpillDataDir::init() {
267
191
    bool exists = false;
268
191
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(_path, &exists));
269
191
    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
191
    RETURN_IF_ERROR(update_capacity());
274
191
    LOG(INFO) << fmt::format(
275
191
            "spill storage path: {}, capacity: {}, limit: {}, available: "
276
191
            "{}",
277
191
            _path, PrettyPrinter::print_bytes(_disk_capacity_bytes),
278
191
            PrettyPrinter::print_bytes(_spill_data_limit_bytes),
279
191
            PrettyPrinter::print_bytes(_available_bytes));
280
191
    return Status::OK();
281
191
}
282
283
7.87k
std::string SpillDataDir::get_spill_data_path(const std::string& query_id) const {
284
7.87k
    auto dir = fmt::format("{}/{}", _path, SPILL_DIR_PREFIX);
285
7.87k
    if (!query_id.empty()) {
286
0
        dir = fmt::format("{}/{}", dir, query_id);
287
0
    }
288
7.87k
    return dir;
289
7.87k
}
290
291
31.0k
std::string SpillDataDir::get_spill_data_gc_path(const std::string& sub_dir_name) const {
292
31.0k
    auto dir = fmt::format("{}/{}", _path, SPILL_GC_DIR_PREFIX);
293
31.0k
    if (!sub_dir_name.empty()) {
294
110
        dir = fmt::format("{}/{}", dir, sub_dir_name);
295
110
    }
296
31.0k
    return dir;
297
31.0k
}
298
299
24.5k
Status SpillDataDir::update_capacity() {
300
24.5k
    std::lock_guard<std::mutex> l(_mutex);
301
24.5k
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
302
24.5k
                                                                  &_available_bytes));
303
7.84k
    spill_disk_capacity->set_value(_disk_capacity_bytes);
304
7.84k
    spill_disk_avail_capacity->set_value(_available_bytes);
305
7.84k
    auto disk_use_max_bytes =
306
7.84k
            (int64_t)(_disk_capacity_bytes * config::storage_flood_stage_usage_percent / 100);
307
7.84k
    bool is_percent = true;
308
7.84k
    _spill_data_limit_bytes = ParseUtil::parse_mem_spec(config::spill_storage_limit, -1,
309
7.84k
                                                        _disk_capacity_bytes, &is_percent);
310
7.84k
    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.84k
    if (is_percent) {
318
7.35k
        _spill_data_limit_bytes = (int64_t)(_spill_data_limit_bytes *
319
7.35k
                                            config::storage_flood_stage_usage_percent / 100);
320
7.35k
    }
321
7.84k
    _spill_data_limit_bytes = std::min(_spill_data_limit_bytes, disk_use_max_bytes);
322
7.84k
    spill_disk_limit->set_value(_spill_data_limit_bytes);
323
324
7.84k
    std::string spill_root_dir = get_spill_data_path();
325
7.84k
    std::string spill_gc_root_dir = get_spill_data_gc_path();
326
7.84k
    spill_disk_has_spill_data->set_value(is_directory_empty(spill_root_dir) ? 0 : 1);
327
7.84k
    spill_disk_has_spill_gc_data->set_value(is_directory_empty(spill_gc_root_dir) ? 0 : 1);
328
329
7.84k
    return Status::OK();
330
7.84k
}
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