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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
149 changes: 135 additions & 14 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <cstdio>
#include <exception>
#include <fstream>
#include <iostream>
#include <memory>
#include <numeric>
#include <string>
Expand All @@ -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<unsigned char>(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<unsigned char>(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<unsigned char>(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<unsigned char>(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<uint8_t, 4096> buffer{};
const auto storage = flight_log::DataContainer::StorageConfig::FullLog;
Expand All @@ -34,12 +148,16 @@ int inspectLog(const char* path)
do {
file.read(reinterpret_cast<char*>(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<int>(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());
}
Expand All @@ -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(
Expand Down Expand Up @@ -130,19 +245,25 @@ int inspectLog(const char* path)

int main(int argc, char** argv)
{
constexpr auto usage = "Usage: flight-log-inspector <file.ulg>\n";
constexpr auto usage = "Usage: flight-log-inspector [--json] <file.ulg>\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;
}
}
15 changes: 15 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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=$<TARGET_FILE:flight-log-inspector> -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=$<TARGET_FILE:flight-log-inspector> -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)
Expand Down
10 changes: 9 additions & 1 deletion tests/check_cli.cmake
Original file line number Diff line number Diff line change
@@ -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
)

Expand All @@ -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)
Expand Down
Loading