diff --git a/README.md b/README.md index 6802e1a..ef1e29c 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,14 @@ nonzero exit status. The CLI keeps samples in memory while it builds the report. reader can process chunks incrementally for large logs. Logs with appended data segments may yield partial results. +Add `--json` before the path to produce one machine-readable diagnostics report. +Schema version 1 reports `status`, parsing `diagnostics`, `dropouts` with a +count and total duration in milliseconds, and `topics` with each name, instance +and sample count. Status is `ok` for a log accepted without diagnostics, +`warning` for recoverable parsing problems, and `error` for an unreadable log +or fatal parsing failure. Both successful statuses exit with code 0. Errors +still produce a JSON report and exit with code 1. + ## C++ library Point `CMAKE_PREFIX_PATH` to the installation directory, then link the library in your project. diff --git a/src/main.cpp b/src/main.cpp index d573e4e..cb73496 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -20,12 +21,125 @@ namespace { -int inspectLog(const char* path) +uint64_t totalDropoutDuration(const flight_log::DataContainer& data) +{ + const auto& dropouts = data.dropouts(); + return std::accumulate( + dropouts.begin(), dropouts.end(), uint64_t{0}, + [](uint64_t sum, const flight_log::Dropout& dropout) { return sum + dropout.durationMs(); }); +} + +size_t utf8SequenceLength(std::string_view text) +{ + const auto lead = static_cast(text.front()); + if (lead < 0xc2 || lead > 0xf4) { + return 0; + } + size_t length = 2; + if (lead >= 0xf0) { + length = 4; + } else if (lead >= 0xe0) { + length = 3; + } + if (text.size() < length) { + return 0; + } + const auto second = static_cast(text[1]); + if ((lead == 0xe0 && second < 0xa0) || (lead == 0xed && second > 0x9f) || + (lead == 0xf0 && second < 0x90) || (lead == 0xf4 && second > 0x8f)) { + return 0; + } + for (size_t i = 1; i < length; ++i) { + const auto continuation = static_cast(text[i]); + if (continuation < 0x80 || continuation > 0xbf) { + return 0; + } + } + return length; +} + +void writeJsonString(std::ostream& output, std::string_view text) +{ + constexpr char hex[] = "0123456789abcdef"; + output.put('"'); + while (!text.empty()) { + const auto first = static_cast(text.front()); + size_t length = 1; + if (first < 0x20) { + output << "\\u00" << hex[first >> 4] << hex[first & 0xf]; + } else if (first == '"' || first == '\\') { + output.put('\\').put(text.front()); + } else if (first < 0x80) { + output.put(text.front()); + } else { + const auto sequence = utf8SequenceLength(text); + if (sequence == 0) { + output << "\\ufffd"; + } else { + length = sequence; + output << text.substr(0, length); + } + } + text.remove_prefix(length); + } + output.put('"'); +} + +void writeJsonReport(std::ostream& output, flight_log::DataContainer* data, + std::string_view input_error = {}) +{ + const bool failed = data == nullptr || data->hadFatalError(); + const char* status = "error"; + if (!failed) { + status = data->parsingErrors().empty() ? "ok" : "warning"; + } + output << "{\"schema_version\":1,\"status\":\"" << status << "\",\"diagnostics\":["; + if (data == nullptr) { + writeJsonString(output, input_error); + } else { + const auto& errors = data->parsingErrors(); + for (size_t i = 0; i < errors.size(); ++i) { + if (i != 0) { + output.put(','); + } + writeJsonString(output, errors[i]); + } + } + if (failed) { + output << "],\"dropouts\":null,\"topics\":[]}\n"; + return; + } + + output << "],\"dropouts\":{\"count\":" << data->dropouts().size() + << ",\"total_duration_ms\":" << totalDropoutDuration(*data) << "},\"topics\":["; + bool first_topic = true; + for (const auto& [key, subscription] : data->subscriptionsByNameAndMultiId()) { + if (!first_topic) { + output.put(','); + } + first_topic = false; + output << "{\"name\":"; + writeJsonString(output, key.name); + output << ",\"instance\":" << key.multi_id << ",\"samples\":" << subscription->size() << '}'; + } + output << "]}\n"; +} + +int reportInputError(const char* description, const char* path, bool json) +{ + if (json) { + writeJsonReport(std::cout, nullptr, description); + } else { + std::fprintf(stderr, "%s '%s'\n", description, path); + } + return 1; +} + +int inspectLog(const char* path, bool json) { std::ifstream file(path, std::ios::binary); if (!file) { - std::fprintf(stderr, "Cannot open log '%s'\n", path); - return 1; + return reportInputError("Cannot open log", path, json); } std::array buffer{}; const auto storage = flight_log::DataContainer::StorageConfig::FullLog; @@ -34,12 +148,16 @@ int inspectLog(const char* path) do { file.read(reinterpret_cast(buffer.data()), buffer.size()); if (file.bad() || (file.fail() && !file.eof())) { - std::fprintf(stderr, "Cannot read log '%s'\n", path); - return 1; + return reportInputError("Cannot read log", path, json); } reader.readChunk(buffer.data(), static_cast(file.gcount())); } while (file && !data_container->hadFatalError()); + if (json) { + writeJsonReport(std::cout, data_container.get()); + return data_container->hadFatalError() ? 1 : 0; + } + for (const auto& parsing_error : data_container->parsingErrors()) { std::fprintf(stderr, "%s: %s\n", path, parsing_error.c_str()); } @@ -48,11 +166,8 @@ int inspectLog(const char* path) } // Dropouts - const auto& dropouts = data_container->dropouts(); - const auto total_dropouts_ms = std::accumulate( - dropouts.begin(), dropouts.end(), uint64_t{0}, - [](uint64_t sum, const flight_log::Dropout& curr) { return sum + curr.durationMs(); }); - printf("Dropouts: %zu, total duration: %" PRIu64 " ms\n", dropouts.size(), total_dropouts_ms); + printf("Dropouts: %zu, total duration: %" PRIu64 " ms\n", data_container->dropouts().size(), + totalDropoutDuration(*data_container)); auto print_value = [](const std::string& name, const flight_log::Value& value) { std::visit( @@ -130,19 +245,25 @@ int inspectLog(const char* path) int main(int argc, char** argv) { - constexpr auto usage = "Usage: flight-log-inspector \n"; + constexpr auto usage = "Usage: flight-log-inspector [--json] \n"; if (argc == 2 && std::string_view(argv[1]) == "--help") { std::fputs(usage, stdout); return 0; } - if (argc != 2) { + const bool json = argc > 1 && std::string_view(argv[1]) == "--json"; + if (argc != (json ? 3 : 2)) { std::fputs(usage, stderr); return 2; } + const char* path = argv[json ? 2 : 1]; try { - return inspectLog(argv[1]); + return inspectLog(path, json); } catch (const std::exception& error) { - std::fprintf(stderr, "%s: %s\n", argv[1], error.what()); + if (json) { + writeJsonReport(std::cout, nullptr, error.what()); + } else { + std::fprintf(stderr, "%s: %s\n", path, error.what()); + } return 1; } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1d021d0..516e0ed 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -19,6 +19,21 @@ add_test(NAME cli-empty-input COMMAND ${CMAKE_COMMAND} -P ${cli_tests} ) +add_test(NAME cli-json-summary COMMAND ${CMAKE_COMMAND} + -DCLI=$ -DCLI_OPTION=--json + -DARGUMENT=${CMAKE_CURRENT_SOURCE_DIR}/log_files/sample_log_small.ulg + -DEXPECTED_STATUS=0 -DEXPECT_QUIET_STDERR=ON + "-DEXPECTED_OUTPUT=\"name\":\"sensor_combined\",\"instance\":0,\"samples\":1298" + -P ${cli_tests} +) +add_test(NAME cli-json-empty-input COMMAND ${CMAKE_COMMAND} + -DCLI=$ -DCLI_OPTION=--json + -DARGUMENT=${empty_log} + -DEXPECTED_STATUS=1 -DEXPECT_QUIET_STDERR=ON + "-DEXPECTED_OUTPUT=\"status\":\"error\",\"diagnostics\":[\"Not enough data to read file magic\"]" + -P ${cli_tests} +) + 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) diff --git a/tests/check_cli.cmake b/tests/check_cli.cmake index d862a6b..3259eb1 100644 --- a/tests/check_cli.cmake +++ b/tests/check_cli.cmake @@ -1,4 +1,8 @@ -execute_process(COMMAND "${CLI}" "${ARGUMENT}" +set(options) +if(DEFINED CLI_OPTION) + list(APPEND options "${CLI_OPTION}") +endif() +execute_process(COMMAND "${CLI}" ${options} "${ARGUMENT}" RESULT_VARIABLE status OUTPUT_VARIABLE output ERROR_VARIABLE error ) @@ -13,6 +17,10 @@ if(DEFINED EXPECTED_OUTPUT) endif() endif() +if(EXPECT_QUIET_STDERR AND NOT error STREQUAL "") + message(FATAL_ERROR "Unexpected error output\n${error}") +endif() + if(DEFINED EXPECTED_ERROR) string(FIND "${error}" "${EXPECTED_ERROR}" error_index) if(error_index EQUAL -1)