Repository navigation
Fix time_slave missing config validation - #332
mattday-etas wants to merge 7 commits into
Conversation
Enforce the schema's min/max ranges for all integer options, reject JSON booleans for integer fields (and numbers for boolean fields), and abort on any fatal config error instead of only logging it. Add tests and document the validation in the configuration guide. This does not use the schema, but uses manual validation logic to enforce the same constraints. Fixes eclipse-score#314
Add a build-time tool that derives keys, ranges and defaults from time_slave_config_schema.json, so the parser can no longer drift from the schema. Reject keys the schema doesn't define and fail when the schema gains a property the parser doesn't handle. Tests now take defaults and range boundaries from the generated header.
Follow-up to the schema validation for eclipse-score#314. Drop the build-time generator (tools/gen_config_limits) and its genrule. The parser now uses a hand-written table in config_limits.h, and a unit test keeps it in sync with time_slave_config_schema.json. - config_schema_consistency_test loads the schema and compares it with the table in both directions: keys, types, ranges, defaults. It also fails on schema keywords the parser does not implement (enum, pattern, exclusiveMinimum, ...), on additionalProperties != false, and on a non-empty "required". - Integer properties are passed to the parser as template arguments, so a static_assert fails the build if a schema range does not fit the C++ field type (e.g. domain_number above 255 into uint8_t). - ParseConfig returns ConfigParseResult instead of calling std::abort(). It collects all errors, and TimeSlave::Initialize logs them and returns kInitFailure. Invalid values are never applied. - Replace the EXPECT_DEATH tests with plain assertions on the reported errors (about 18 s -> 0.1 s). Add a test that every key is applied. - Validate the deployed QNX configs against the schema. - Docs: describe the refuse-to-start behaviour and the table/schema consistency test. Fix the stale pdelay_interval_ms name in the detailed design and diagrams.
License Check Results🚀 The license check job ran with the Bazel command: bazel run //:license-checkStatus: Click to expand output |
|
Quality pack traceability report for this pull request: Status: PASS (workflow run) |
|
Documentation preview for this pull request is available at: |
Drop default_value from the config schema table. The consistency test
now compares the schema's defaults with a default-constructed
TimeSlaveConfig, which replaces StructDefaultsMatchTable. The parser
test only checks that parsing {} leaves the struct defaults unchanged.
Rename config_limits.h to config_schema_table.h, since it holds keys,
types and ranges, not only limits.
808a932 to
c76af67
Compare
jorgecasal
left a comment
There was a problem hiding this comment.
Approved with some minor suggestions.
In summary, the validation works as described and I found nothing blocking. However, I'd update the PR description, since main has no std::abort() or EXPECT_DEATH. I'd also like the comment on Finish() and the missing test for the refuse to start path either fixed here or possibly tracked in a follow up issue. The rest is up to you.
| * - ``pdelay_req_interval_ms`` | ||
| - int | ||
| - Interval between PDelayReq transmissions (ms); default: ``1000`` | ||
| - Interval between PDelayReq transmissions (ms); range 10..60000; default: ``1000`` |
There was a problem hiding this comment.
This is the only row in the table that gives a range. The guide says the schema defines the ranges, so I'd leave it out here, otherwise we have one more place to keep in sync.
| if (!std::filesystem::is_regular_file(path, ec)) | ||
| { | ||
| score::mw::log::LogError(kTimeSlaveAppContext) | ||
| score::mw::log::LogWarn(kTimeSlaveAppContext) |
There was a problem hiding this comment.
I noticed this went from LogError to LogWarn. It isn't mentioned in the description. Was that on purpose?
| template <const cs::IntProperty& Prop, typename T> | ||
| void Int(T& out) | ||
| { | ||
| static_assert(Prop.min >= std::numeric_limits<T>::min() && Prop.max <= std::numeric_limits<T>::max(), | ||
| "schema range of this property does not fit into the C++ field type"); |
There was a problem hiding this comment.
It took me a while to see why Int is called as Int<cs::kDomainNumber>(out) when String and Bool take the property as a normal argument. Would it work to pass it the same way and keep the static_assert next to the table instead?
| return; | ||
| } | ||
| const auto result = value->As<bool>(); | ||
| if (value->As<score::json::Number>().has_value() || !result.has_value()) |
There was a problem hiding this comment.
I had to read this twice and, think it's right, but a small helper like IsJsonBool(value) would make it obvious why the Number check comes first.
| void ParsePhcConfig(JsonObjectReader& root, std::vector<std::string>& errors, details::PhcConfig& cfg) | ||
| { | ||
| const JsonObject* phc_obj = root.NestedObject(cs::kPhcKey); | ||
| if (phc_obj == nullptr) | ||
| { | ||
| return; | ||
| } | ||
| JsonObjectReader reader{*phc_obj, cs::kPhcKey, cs::kPhcKeys, errors}; | ||
| reader.Bool(cs::kPhcEnabled, cfg.enabled); | ||
| reader.String(cs::kPhcDevice, cfg.device); | ||
| reader.Int<cs::kPhcStepThresholdNs>(cfg.step_threshold_ns); | ||
| reader.Finish(); | ||
| } | ||
|
|
||
| /// Parse the optional "qnx" nested object. If absent, @p qnx keeps defaults. | ||
| void ParseQnxConfig(const Object& obj, TimeSlaveConfig::QnxSettings& qnx) | ||
| void ParseQnxConfig(JsonObjectReader& root, std::vector<std::string>& errors, TimeSlaveConfig::QnxSettings& qnx) |
There was a problem hiding this comment.
The root reader already holds the errors vector, so passing errors as well looks redundant. Maybe the reader could hand out a child reader for the nested object?
| Default Configuration (`GptpEngineOptions`) | ||
| ------------------------------------------- | ||
|
|
||
| The following table lists all available options and their default values as defined in the source code. Currently, only ``iface_name`` can be changed without recompiling the application. |
There was a problem hiding this comment.
Not new in this PR, but this sentence says only iface_name can be changed without recompiling, and that no longer fits the table below or the new Validation section. Could you fix it while you're editing this page?
| auto parsed = ParseConfig(config_path.string()); | ||
| if (!parsed.ok()) | ||
| { | ||
| for (const auto& error : parsed.errors) | ||
| { | ||
| score::mw::log::LogError(kTimeSlaveAppContext) << error; | ||
| } | ||
| score::mw::log::LogError(kTimeSlaveAppContext) | ||
| << "Invalid configuration file " << config_path.string() << ", refusing to start"; | ||
| return kInitFailure; | ||
| } |
There was a problem hiding this comment.
This is the main behaviour change of the PR, but I don't see a test that reaches it. My understanding is that time_slave.cpp is only built into the binary, so it's not trivial. Could we add one, or maybe open a follow up issue for it?
| TEST(ConfigParserTest, ReportsAllErrorsNotJustTheFirst) | ||
| { | ||
| const auto result = ParseConfig(WriteTempFile( | ||
| "multi_error.json", R"({"domain_number": 128, "sync_timeout_ms": 1, "phc": {"enabled": 1}, "typo": 0})")); | ||
| EXPECT_EQ(result.errors.size(), 4U); | ||
| } |
There was a problem hiding this comment.
This only checks the number of errors. Could it also check that the four key names show up in the messages? Otherwise it would still pass with four wrong errors.
| /// Invalid JSON is an error (not defaults): the caller refuses to start on it. | ||
| TEST(ConfigParserTest, InvalidJsonIsReportedNotDefaulted) | ||
| { | ||
| const auto cfg = ParseConfig(WriteTempFile("invalid_config.json", "{not json")); | ||
| const auto result = ParseConfig(WriteTempFile("invalid_config.json", "{not json")); | ||
|
|
||
| EXPECT_EQ(cfg.engine_opts.iface_name, "emac0"); | ||
| EXPECT_EQ(cfg.shm_path, "/gptp_shmem"); | ||
| ASSERT_FALSE(result.ok()); | ||
| EXPECT_NE(result.errors.front().find("Failed to parse"), std::string::npos); | ||
| } |
There was a problem hiding this comment.
Correct me if I'm wrong but, this looks like the same case as not_json in the list above (line 278). I think one of the two is enough.
| target_compatible_with = ["@platforms//os:linux"], | ||
| ) | ||
|
|
||
| # Deployed configurations must satisfy the schema too. |
There was a problem hiding this comment.
Good to see the deployed configs checked against the schema. A small parser test that loads the same two files would also show that ParseConfig itself accepts them.
Description
Closes #314.
The TimeSlave config parser did not check values against
time_slave_config_schema.json. Out-of-range values were applied silently. For example,"domain_number": 128makes the slave ignore every Sync. A JSON boolean was also accepted for an integer field.The parser now enforces the schema's types,
minimum/maximumandadditionalProperties: false. It collects every error, andTimeSlave::Initializelogs them and returnskInitFailure. Invalid values are never applied.Behaviour change: a config file with an unknown or misspelled key, or any invalid value, now stops the TimeSlave from starting. Before, the bad value was ignored or applied. The deployed QNX configs are now validated against the schema in CI, and they pass.
How the parser stays in sync with the schema:
config_schema_table.hlists the keys, types and ranges the parser enforces.config_schema_consistency_testcompares that table with the schema in both directions. It also checks the schema defaults against the C++ struct defaults. It fails if the schema uses a keyword the parser does not implement (enum,pattern, ...).static_assertfails the build if a schema range does not fit the C++ field type.Also:
ParseConfigreturnsConfigParseResultinstead of callingstd::abort(). TheEXPECT_DEATHtests became plain assertions (about 18 s down to 0.1 s).pdelay_interval_msname is fixed in the guide and the design docs.