Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion examples/ulog_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 5 additions & 2 deletions include/flight_log/simple_writer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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]
*/
Expand Down Expand Up @@ -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();

Expand All @@ -152,8 +154,9 @@ class SimpleWriter {

void writeDataImpl(uint16_t id, const uint8_t* data, unsigned length);

std::string _filename;
std::unique_ptr<std::FILE, decltype(&std::fclose)> _file{nullptr, &std::fclose};
std::unique_ptr<Writer> _writer;
std::FILE* _file{nullptr};

bool _header_complete{false};
std::unordered_map<std::string, Format> _formats;
Expand Down
66 changes: 47 additions & 19 deletions src/simple_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,35 @@

#include <flight_log/simple_writer.hpp>

#include <cerrno>
#include <system_error>

#ifdef _WIN32
// clang-format off
#include <windows.h>
#include <fileapi.h>
// clang-format on
#include <io.h>
#else
#include <unistd.h>
#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_]+";
Expand All @@ -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<Writer>(
[this](const uint8_t* data, int length) { std::fwrite(data, 1, length, _file); });
_writer = std::make_unique<Writer>([this](const uint8_t* data, int length) {
const auto size = static_cast<size_t>(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<Field>& fields)
{
Expand Down Expand Up @@ -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<HANDLE>(static_cast<uintptr_t>(_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,
Expand Down
3 changes: 2 additions & 1 deletion tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
70 changes: 70 additions & 0 deletions tests/writer_file_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/****************************************************************************
* SPDX-License-Identifier: BSD-3-Clause
****************************************************************************/
#include <doctest/doctest.h>

#include <filesystem>
#include <string>

#include <flight_log/simple_writer.hpp>

namespace {

template <typename Operation>
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
Loading