blob: 43470174848d0721b6f9f30b0848de4492695e2c [file] [log] [blame]
James Kuszmaul827bd212023-05-15 23:57:39 -07001#include "aos/util/config_validator_lib.h"
2
Stephan Pleinesb1177672024-05-27 17:48:32 -07003#include <algorithm>
James Kuszmaul827bd212023-05-15 23:57:39 -07004#include <chrono>
Stephan Pleinesb1177672024-05-27 17:48:32 -07005#include <cstdlib>
6#include <initializer_list>
7#include <map>
8#include <memory>
9#include <ostream>
10#include <set>
11#include <string>
12#include <string_view>
13#include <utility>
14#include <vector>
James Kuszmaul827bd212023-05-15 23:57:39 -070015
Stephan Pleinesb1177672024-05-27 17:48:32 -070016#include "flatbuffers/buffer.h"
17#include "flatbuffers/detached_buffer.h"
18#include "flatbuffers/string.h"
19#include "flatbuffers/vector.h"
20#include "gflags/gflags_declare.h"
21#include "glog/logging.h"
22#include "gtest/gtest.h"
23
24#include "aos/events/event_loop.h"
James Kuszmaul827bd212023-05-15 23:57:39 -070025#include "aos/events/logging/log_reader.h"
Stephan Pleinesb1177672024-05-27 17:48:32 -070026#include "aos/events/logging/logfile_sorting.h"
27#include "aos/events/logging/logfile_utils.h"
James Kuszmaul827bd212023-05-15 23:57:39 -070028#include "aos/events/simulated_event_loop.h"
Stephan Pleinesb1177672024-05-27 17:48:32 -070029#include "aos/flatbuffers/builder.h"
30#include "aos/flatbuffers/static_vector.h"
31#include "aos/json_to_flatbuffer.h"
James Kuszmaul827bd212023-05-15 23:57:39 -070032#include "aos/network/remote_message_generated.h"
33#include "aos/network/timestamp_channel.h"
34#include "aos/testing/tmpdir.h"
James Kuszmaul464012b2024-03-20 14:12:08 -070035#include "aos/util/config_validator_config_static.h"
Stephan Pleinesb1177672024-05-27 17:48:32 -070036#include "aos/util/file.h"
James Kuszmaul827bd212023-05-15 23:57:39 -070037#include "aos/util/simulation_logger.h"
38
39DECLARE_bool(validate_timestamp_logger_nodes);
40
41namespace aos::util {
42
43namespace {
44void RunSimulationAndExit(const aos::Configuration *config) {
45 aos::SimulatedEventLoopFactory factory(config);
46
47 factory.RunFor(std::chrono::seconds(1));
48
49 std::exit(EXIT_SUCCESS);
50}
51
52// Checks if either the node is in the specified list of node names or if the
53// list is empty (in which case it is treated as matching all nodes).
54bool NodeInList(
55 const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *list,
56 const aos::Node *node) {
57 if (list == nullptr || list->size() == 0) {
58 return true;
59 }
60 for (const flatbuffers::String *name : *list) {
61 if (name->string_view() == node->name()->string_view()) {
62 return true;
63 }
64 }
65 return false;
66}
67
68} // namespace
69
70void ConfigIsValid(const aos::Configuration *config,
James Kuszmaul464012b2024-03-20 14:12:08 -070071 const ConfigValidatorConfig *validation_config_raw) {
James Kuszmaul827bd212023-05-15 23:57:39 -070072 ASSERT_TRUE(config->has_channels())
73 << "An AOS config must have channels. If you have a valid use-case for "
74 "channels with no channels, please write a design proposal.";
75
James Kuszmaul464012b2024-03-20 14:12:08 -070076 aos::fbs::Builder<ConfigValidatorConfigStatic> validation_config;
77 CHECK(validation_config->FromFlatbuffer(validation_config_raw));
78
79 if (validation_config_raw->has_logging() &&
80 validation_config_raw->logging()->validate_individual_node_loggers() &&
81 configuration::MultiNode(config)) {
82 if (!validation_config->logging()->has_logger_sets()) {
83 validation_config->mutable_logging()->add_logger_sets();
84 }
85 auto logger_sets =
86 validation_config->mutable_logging()->mutable_logger_sets();
87 for (const aos::Node *node : configuration::GetNodes(config)) {
88 CHECK(logger_sets->reserve(logger_sets->size() + 1));
89 auto logger_set = logger_sets->emplace_back();
90 CHECK(logger_set->add_loggers()->FromFlatbuffer({node->name()->str()}));
91 CHECK(logger_set->add_replay_nodes()->FromFlatbuffer(
92 {node->name()->str()}));
93 }
94 }
95
James Kuszmaul827bd212023-05-15 23:57:39 -070096 // First, we do some sanity checks--these are likely to indicate a malformed
97 // config, and so catching them early with a clear error message is likely to
98 // help.
99
100 // The set of all channels that are required by the channels that are
101 // configured--these are the remote timestamp channels that *must* be present,
102 // and ideally there are no other channels present.
103 std::set<const Channel *> required_timestamp_channels;
104 // The set of all channels that *look* like remote timestamp channels. This
105 // may include channels that are improperly configured and thus have typos &
106 // aren't actually going to do anything at runtime.
107 std::set<const Channel *> configured_timestamp_channels;
108 bool validation_failed = false;
109 for (size_t channel_index = 0; channel_index < config->channels()->size();
110 ++channel_index) {
111 const aos::Channel *channel = config->channels()->Get(channel_index);
112 ASSERT_TRUE(channel->has_name()) << "All AOS channels must have a name.";
113 ASSERT_TRUE(channel->has_type()) << "All AOS channels must have a type.";
114
115 const bool channel_looks_like_remote_message_channel =
116 channel->type()->string_view() ==
117 message_bridge::RemoteMessage::GetFullyQualifiedName();
118
119 const bool check_for_not_logged_channels =
120 !validation_config->has_logging() ||
James Kuszmaul464012b2024-03-20 14:12:08 -0700121 validation_config->AsFlatbuffer().logging()->all_channels_logged();
James Kuszmaul827bd212023-05-15 23:57:39 -0700122 const bool channel_is_not_logged =
123 channel->logger() == aos::LoggerConfig::NOT_LOGGED;
124 if (check_for_not_logged_channels) {
125 if (channel_looks_like_remote_message_channel != channel_is_not_logged) {
126 LOG(WARNING)
127 << "Channel " << configuration::StrippedChannelToString(channel)
128 << " is " << EnumNameLoggerConfig(channel->logger()) << " but "
129 << (channel_looks_like_remote_message_channel ? "is" : "is not")
130 << " a remote timestamp channel. This is almost certainly wrong.";
131 validation_failed = true;
132 }
133 }
134
135 if (channel_looks_like_remote_message_channel) {
136 configured_timestamp_channels.insert(channel);
137 } else {
138 if (channel->has_destination_nodes()) {
139 // TODO(james): Technically the timestamp finder should receive a
140 // non-empty application name. However, there are no known users that
141 // care at this moment.
142 message_bridge::ChannelTimestampFinder timestamp_finder(
143 config, "",
144 configuration::GetNode(config,
145 channel->source_node()->string_view()));
146 for (const Connection *connection : *channel->destination_nodes()) {
147 switch (connection->timestamp_logger()) {
148 case LoggerConfig::NOT_LOGGED:
149 case LoggerConfig::LOCAL_LOGGER:
150 if (connection->has_timestamp_logger_nodes()) {
151 LOG(WARNING)
152 << "Connections that are "
153 << EnumNameLoggerConfig(connection->timestamp_logger())
154 << " should not have remote timestamp logger nodes "
155 "populated. This is for the connection to "
156 << connection->name()->string_view() << " on "
157 << configuration::StrippedChannelToString(channel);
158 validation_failed = true;
159 }
160 break;
161 case LoggerConfig::REMOTE_LOGGER:
162 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
163 if (!connection->has_timestamp_logger_nodes() ||
164 connection->timestamp_logger_nodes()->size() != 1 ||
165 connection->timestamp_logger_nodes()->Get(0)->string_view() !=
166 channel->source_node()->string_view()) {
167 LOG(WARNING)
168 << "Connections that are "
169 << EnumNameLoggerConfig(connection->timestamp_logger())
170 << " should have exactly 1 remote timestamp logger node "
171 "populated, and that node should be the source_node ("
172 << channel->source_node()->string_view()
173 << "). This is for the connection to "
174 << connection->name()->string_view() << " on "
175 << configuration::StrippedChannelToString(channel);
176 validation_failed = true;
177 }
178 // TODO(james): This will be overly noisy, as it ends up
179 // CHECK-failing.
Austin Schuh6bdcc372024-06-27 14:49:11 -0700180 const Channel *found_channel =
181 timestamp_finder.ForChannel(channel, connection);
182 CHECK(found_channel != nullptr);
183 required_timestamp_channels.insert(found_channel);
James Kuszmaul827bd212023-05-15 23:57:39 -0700184 break;
185 }
186 }
187 }
188 }
189 }
190
191 // Check that all of the things that look like timestamp channels are indeed
192 // required.
193 // Note: Because ForChannel() will die if a required channel is not present,
194 // we do not do a separate check that all the required channels exist.
195 for (const auto &channel : configured_timestamp_channels) {
196 if (required_timestamp_channels.count(channel) == 0) {
197 LOG(WARNING) << "Timestamp channel "
198 << configuration::StrippedChannelToString(channel)
199 << " was specified in the config but is not used.";
200 validation_failed = true;
201 }
202 }
203
204 if (validation_failed) {
205 FAIL() << "Remote timestamp linting failed.";
206 return;
207 }
208
209 // Because the most common way for simulation to fail involves it dying, force
210 // it to fail in a slightly more controlled manner.
211 ASSERT_EXIT(RunSimulationAndExit(config),
212 ::testing::ExitedWithCode(EXIT_SUCCESS), "");
213
214 if (!validation_config->has_logging() || !configuration::MultiNode(config)) {
215 return;
216 }
217
218 // We will run all the logger configs in two modes:
219 // 1) We don't send any data on any non-infrastructure channels; this confirms
220 // that the logs are readable in the absence of any user applications being
221 // present.
222 // 2) We confirm that we can generate a good logfile that actually has data
223 // on every channel (some checks in the LogReader may not get hit if there
224 // is no data on a given channel).
225 const std::string log_path = aos::testing::TestTmpDir() + "/logs/";
226 for (const bool send_data_on_channels : {false, true}) {
227 SCOPED_TRACE(send_data_on_channels);
Pallavi Madhukaraaba67e2023-09-08 14:20:00 -0700228 // Single nodes (multi-nodes with node count = 1) will not produce readable
229 // logs in the absense of data.
230 if (!send_data_on_channels && (configuration::NodesCount(config) == 1u)) {
231 continue;
232 }
Pallavi Madhukar3076d5c2023-09-09 10:23:26 -0700233 // Send timing report when we are sending data.
234 const bool do_skip_timing_report = !send_data_on_channels;
James Kuszmaul464012b2024-03-20 14:12:08 -0700235 for (const LoggerNodeSetValidationStatic &logger_set :
James Kuszmaul827bd212023-05-15 23:57:39 -0700236 *validation_config->logging()->logger_sets()) {
James Kuszmaul464012b2024-03-20 14:12:08 -0700237 SCOPED_TRACE(aos::FlatbufferToJson(&logger_set.AsFlatbuffer()));
James Kuszmaul827bd212023-05-15 23:57:39 -0700238 aos::SimulatedEventLoopFactory factory(config);
239 std::vector<std::unique_ptr<LoggerState>> loggers;
James Kuszmaul464012b2024-03-20 14:12:08 -0700240 if (logger_set.has_loggers() && logger_set.loggers()->size() > 0) {
James Kuszmaul827bd212023-05-15 23:57:39 -0700241 std::vector<std::string> logger_nodes;
James Kuszmaul464012b2024-03-20 14:12:08 -0700242 for (const auto &node : *logger_set.loggers()) {
243 logger_nodes.push_back(node.str());
James Kuszmaul827bd212023-05-15 23:57:39 -0700244 }
Pallavi Madhukar3076d5c2023-09-09 10:23:26 -0700245 loggers = MakeLoggersForNodes(&factory, logger_nodes, log_path,
246 do_skip_timing_report);
James Kuszmaul827bd212023-05-15 23:57:39 -0700247 } else {
Pallavi Madhukar3076d5c2023-09-09 10:23:26 -0700248 loggers =
249 MakeLoggersForAllNodes(&factory, log_path, do_skip_timing_report);
James Kuszmaul827bd212023-05-15 23:57:39 -0700250 }
251
252 std::vector<std::unique_ptr<EventLoop>> test_loops;
253 std::map<std::string, std::vector<std::unique_ptr<RawSender>>>
254 test_senders;
255
256 if (send_data_on_channels) {
257 // Make a sender on every non-infrastructure channel on every node
258 // (including channels that may not be observable by the current logger
259 // set).
260 for (const aos::Node *node : configuration::GetNodes(config)) {
261 test_loops.emplace_back(factory.MakeEventLoop("", node));
262 for (const aos::Channel *channel : *config->channels()) {
263 // TODO(james): Make a more sophisticated check for "infrastructure"
264 // channels than just looking for a "/aos" in the channel--we don't
265 // accidentally want to spam nonsense data onto any timestamp
266 // channels, though.
267 if (configuration::ChannelIsSendableOnNode(channel, node) &&
268 channel->name()->str().find("/aos") == std::string::npos &&
269 channel->logger() != LoggerConfig::NOT_LOGGED) {
270 test_senders[node->name()->str()].emplace_back(
271 test_loops.back()->MakeRawSender(channel));
272 RawSender *sender =
273 test_senders[node->name()->str()].back().get();
274 test_loops.back()->OnRun([sender, channel]() {
275 flatbuffers::DetachedBuffer buffer =
276 JsonToFlatbuffer("{}", channel->schema());
277 sender->CheckOk(sender->Send(buffer.data(), buffer.size()));
278 });
279 }
280 }
281 }
282 }
283
284 factory.RunFor(std::chrono::seconds(2));
285
286 // Get all of the loggers to close before trying to read the logfiles.
287 loggers.clear();
288
289 // Confirm that we can read the log, and that if we put data in it that we
290 // can find data on all the nodes that the user cares about.
291 logger::LogReader reader(logger::SortParts(logger::FindLogs(log_path)));
292 SimulatedEventLoopFactory replay_factory(reader.configuration());
293 reader.RegisterWithoutStarting(&replay_factory);
294
295 // Find every channel we deliberately sent data on, and if it is for a
296 // node that we care about, confirm that we get it during replay.
297 std::vector<std::unique_ptr<EventLoop>> replay_loops;
James Kuszmaul827bd212023-05-15 23:57:39 -0700298 for (const aos::Node *node :
299 configuration::GetNodes(replay_factory.configuration())) {
300 // If the user doesn't care about this node, don't check it.
James Kuszmaul464012b2024-03-20 14:12:08 -0700301 if (!NodeInList(logger_set.has_replay_nodes()
302 ? logger_set.replay_nodes()->AsFlatbufferVector()
303 : nullptr,
304 node)) {
James Kuszmaul827bd212023-05-15 23:57:39 -0700305 continue;
306 }
307 replay_loops.emplace_back(replay_factory.MakeEventLoop("", node));
James Kuszmaul827bd212023-05-15 23:57:39 -0700308 }
309
310 std::vector<std::pair<const aos::Node *, std::unique_ptr<RawFetcher>>>
James Kuszmaul464012b2024-03-20 14:12:08 -0700311 fetchers;
312 for (const auto &node_senders : test_senders) {
313 for (const auto &sender : node_senders.second) {
314 for (auto &loop : replay_loops) {
315 if (configuration::ChannelIsReadableOnNode(sender->channel(),
316 loop->node())) {
317 fetchers.push_back(std::make_pair(
318 loop->node(),
319 loop->MakeRawFetcher(configuration::GetChannel(
320 replay_factory.configuration(), sender->channel(),
321 loop->name(), loop->node()))));
322 }
James Kuszmaul827bd212023-05-15 23:57:39 -0700323 }
324 }
325 }
326
327 replay_factory.Run();
328
James Kuszmaul464012b2024-03-20 14:12:08 -0700329 for (auto &pair : fetchers) {
James Kuszmaul827bd212023-05-15 23:57:39 -0700330 EXPECT_TRUE(pair.second->Fetch())
331 << "Failed to log or replay any data on "
332 << configuration::StrippedChannelToString(pair.second->channel())
James Kuszmaul464012b2024-03-20 14:12:08 -0700333 << " reading from " << logger::MaybeNodeName(pair.first)
334 << " with source node "
335 << (pair.second->channel()->has_source_node()
336 ? pair.second->channel()->source_node()->string_view()
337 : "")
338 << ".";
James Kuszmaul827bd212023-05-15 23:57:39 -0700339 }
340
341 reader.Deregister();
342
343 // Clean up the logs.
344 UnlinkRecursive(log_path);
345 }
346 }
347}
348
349} // namespace aos::util