From 85bf9f9b4356dc727145bd4eebfbdeb1e06cd228 Mon Sep 17 00:00:00 2001 From: Xia Chao Date: Tue, 24 Nov 2026 21:13:16 +0800 Subject: [PATCH] Propagate ULog file writer I/O failures --- examples/ulog_writer.cpp | 4 +- include/flight_log/simple_writer.hpp | 7 ++- src/simple_writer.cpp | 66 ++++++++++++++++++-------- tests/CMakeLists.txt | 3 +- tests/writer_file_test.cpp | 70 ++++++++++++++++++++++++++++ 5 files changed, 127 insertions(+), 23 deletions(-) create mode 100644 tests/writer_file_test.cpp diff --git a/examples/ulog_writer.cpp b/examples/ulog_writer.cpp index 2d9c9d2..d3445bb 100644 --- a/examples/ulog_writer.cpp +++ b/examples/ulog_writer.cpp @@ -75,8 +75,10 @@ int main(int argc, char** argv) std::this_thread::sleep_for(10ms); } + writer.fsync(); } catch (const flight_log::ExceptionBase& e) { - printf("ULog exception: %s\n", e.what()); + std::fprintf(stderr, "ULog exception: %s\n", e.what()); + return 1; } return 0; diff --git a/include/flight_log/simple_writer.hpp b/include/flight_log/simple_writer.hpp index 39fa38b..1c16577 100644 --- a/include/flight_log/simple_writer.hpp +++ b/include/flight_log/simple_writer.hpp @@ -36,6 +36,7 @@ class SimpleWriter { explicit SimpleWriter(DataWriteCB data_write_cb, uint64_t timestamp_us); /** * Constructor to write to a file. + * Throws ParsingException if the file cannot be opened or written. * @param filename ULog file to write to (will be overwritten if it exists) * @param timestamp_us start timestamp [us] */ @@ -133,7 +134,8 @@ class SimpleWriter { } /** - * Flush the buffer and call fsync() on the file (only if the file-based constructor is used). + * Flush and synchronize a file-based writer, throwing ParsingException on error. + * Call before destruction to check for buffered output errors. Does nothing for a callback. */ void fsync(); @@ -152,8 +154,9 @@ class SimpleWriter { void writeDataImpl(uint16_t id, const uint8_t* data, unsigned length); + std::string _filename; + std::unique_ptr _file{nullptr, &std::fclose}; std::unique_ptr _writer; - std::FILE* _file{nullptr}; bool _header_complete{false}; std::unordered_map _formats; diff --git a/src/simple_writer.cpp b/src/simple_writer.cpp index 590b29d..264dc7a 100644 --- a/src/simple_writer.cpp +++ b/src/simple_writer.cpp @@ -5,17 +5,35 @@ #include +#include +#include + #ifdef _WIN32 -// clang-format off -#include -#include -// clang-format on +#include #else #include #endif namespace flight_log { +namespace { + +[[noreturn]] void throwFileError(const char* operation, const std::string& filename, int error) +{ + const std::error_code code(error == 0 ? EIO : error, std::generic_category()); + throw ParsingException(std::string("Failed to ") + operation + " '" + filename + + "': " + code.message()); +} + +void checkFileStream(std::FILE* file, const std::string& filename) +{ + if (std::ferror(file)) { + throw ParsingException("Previous stream error writing '" + filename + "'"); + } +} + +} // namespace + const std::string SimpleWriter::kFormatNameRegexStr = "[a-zA-Z0-9_\\-/]+"; const std::regex SimpleWriter::kFormatNameRegex = std::regex(std::string(kFormatNameRegexStr)); const std::string SimpleWriter::kFieldNameRegexStr = "[a-z0-9_]+"; @@ -28,24 +46,23 @@ SimpleWriter::SimpleWriter(DataWriteCB data_write_cb, uint64_t timestamp_us) } SimpleWriter::SimpleWriter(const std::string& filename, uint64_t timestamp_us) + : _filename(filename), _file(std::fopen(filename.c_str(), "wb"), &std::fclose) { - _file = std::fopen(filename.c_str(), "wb"); if (!_file) { - throw ParsingException("Failed to open file"); + throwFileError("open", _filename, errno); } - _writer = std::make_unique( - [this](const uint8_t* data, int length) { std::fwrite(data, 1, length, _file); }); + _writer = std::make_unique([this](const uint8_t* data, int length) { + const auto size = static_cast(length); + checkFileStream(_file.get(), _filename); + if (std::fwrite(data, 1, size, _file.get()) != size || std::ferror(_file.get())) { + throwFileError("write", _filename, errno); + } + }); _writer->fileHeader(FileHeader(timestamp_us)); } -SimpleWriter::~SimpleWriter() -{ - _writer.reset(); - if (_file) { - std::fclose(_file); - } -} +SimpleWriter::~SimpleWriter() = default; void SimpleWriter::writeMessageFormat(const std::string& name, const std::vector& fields) { @@ -113,13 +130,24 @@ void SimpleWriter::writeTextMessage(Logging::Level level, const std::string& mes void SimpleWriter::fsync() { - if (_file) { - fflush(_file); + if (!_file) { + return; + } + checkFileStream(_file.get(), _filename); + if (std::fflush(_file.get()) != 0) { + throwFileError("flush", _filename, errno); + } + #ifdef _WIN32 - FlushFileBuffers(reinterpret_cast(static_cast(_fileno(_file)))); + const int result = _commit(_fileno(_file.get())); #else - ::fsync(fileno(_file)); + int result; + do { + result = ::fsync(fileno(_file.get())); + } while (result != 0 && errno == EINTR); #endif + if (result != 0) { + throwFileError("sync", _filename, errno); } } uint16_t SimpleWriter::writeAddLoggedMessage(const std::string& message_format_name, diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1d021d0..9745101 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -21,7 +21,8 @@ add_test(NAME cli-empty-input COMMAND ${CMAKE_COMMAND} if(FLIGHT_LOG_ENABLE_UNIT_TESTS) find_package(doctest CONFIG REQUIRED) - add_executable(flight_log_unit_tests main.cpp read_api_test.cpp ulog_parsing_test.cpp) + add_executable(flight_log_unit_tests main.cpp read_api_test.cpp ulog_parsing_test.cpp + writer_file_test.cpp) target_link_libraries(flight_log_unit_tests PRIVATE doctest::doctest flight_log::flight_log) add_test(NAME unit-tests COMMAND flight_log_unit_tests) endif() diff --git a/tests/writer_file_test.cpp b/tests/writer_file_test.cpp new file mode 100644 index 0000000..7e8fdfd --- /dev/null +++ b/tests/writer_file_test.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** + * SPDX-License-Identifier: BSD-3-Clause + ****************************************************************************/ +#include + +#include +#include + +#include + +namespace { + +template +std::string writeError(Operation operation) +{ + try { + operation(); + } catch (const flight_log::ParsingException& error) { + return error.what(); + } + return {}; +} + +} // namespace + +TEST_CASE("file writer reports the destination on an open error") +{ + const std::string directory = std::filesystem::temp_directory_path().string(); + const auto error = writeError([&] { flight_log::SimpleWriter writer(directory, 0); }); + MESSAGE("open directory as output: ", error); + CHECK(error.find(directory) != std::string::npos); +} + +#ifdef __linux__ +TEST_CASE("file writer reports errors while writing a normal recording") +{ + flight_log::SimpleWriter writer("/dev/full", 0); + writer.headerComplete(); + const std::string message(1000, 'x'); + unsigned accepted = 0; + const auto error = writeError([&] { + for (; accepted < 32; ++accepted) { + writer.writeTextMessage(flight_log::Logging::Level::Info, message, accepted); + } + }); + MESSAGE("write to /dev/full: records accepted=", accepted, " error=", error); + CHECK(accepted < 32); + CHECK(error.find("/dev/full") != std::string::npos); + CHECK_FALSE(writeError([&] { writer.fsync(); }).empty()); +} + +TEST_CASE("file writer reports a buffered flush error") +{ + flight_log::SimpleWriter writer("/dev/full", 0); + const auto error = writeError([&] { writer.fsync(); }); + MESSAGE("flush /dev/full: ", error); + CHECK(error.find("flush") != std::string::npos); + CHECK(error.find("/dev/full") != std::string::npos); + CHECK_FALSE(writeError([&] { writer.fsync(); }).empty()); +} + +TEST_CASE("file writer reports a filesystem sync error after a successful flush") +{ + flight_log::SimpleWriter writer("/dev/null", 0); + const auto error = writeError([&] { writer.fsync(); }); + MESSAGE("sync /dev/null: ", error); + CHECK(error.find("sync") != std::string::npos); + CHECK(error.find("/dev/null") != std::string::npos); +} +#endif