blob: 4e1316d26e60e6b57272ba660e7cad1594288b3c [file] [log] [blame]
John Park398c74a2018-10-20 21:17:39 -07001#include "aos/configuration.h"
Brian Silverman66f079a2013-08-26 16:24:30 -07002
Brian Silverman66f079a2013-08-26 16:24:30 -07003#include <arpa/inet.h>
4#include <ifaddrs.h>
Austin Schuhf1fff282020-03-28 16:57:32 -07005#include <netinet/in.h>
Austin Schuhf1fff282020-03-28 16:57:32 -07006#include <sys/types.h>
Brian Silverman66f079a2013-08-26 16:24:30 -07007#include <unistd.h>
Austin Schuhe84c3ed2019-12-14 15:29:48 -08008
Tyler Chatowbf0609c2021-07-31 16:13:27 -07009#include <cstdlib>
10#include <cstring>
Austin Schuh68d98592020-11-01 23:22:57 -080011#include <map>
Austin Schuhe84c3ed2019-12-14 15:29:48 -080012#include <set>
Austin Schuhef38cd22021-07-21 15:24:23 -070013#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -080014#include <string_view>
Austin Schuhef38cd22021-07-21 15:24:23 -070015#include <vector>
Brian Silverman66f079a2013-08-26 16:24:30 -070016
Austin Schuhcb108412019-10-13 16:09:54 -070017#include "absl/container/btree_set.h"
Austin Schuha81454b2020-05-12 19:58:36 -070018#include "absl/strings/str_cat.h"
Austin Schuhef38cd22021-07-21 15:24:23 -070019#include "absl/strings/str_join.h"
20#include "absl/strings/str_split.h"
Austin Schuhcb108412019-10-13 16:09:54 -070021#include "aos/configuration_generated.h"
22#include "aos/flatbuffer_merge.h"
23#include "aos/json_to_flatbuffer.h"
Austin Schuh217a9782019-12-21 23:02:50 -080024#include "aos/network/team_number.h"
Austin Schuhcb108412019-10-13 16:09:54 -070025#include "aos/unique_malloc_ptr.h"
26#include "aos/util/file.h"
Austin Schuh217a9782019-12-21 23:02:50 -080027#include "gflags/gflags.h"
Austin Schuhcb108412019-10-13 16:09:54 -070028#include "glog/logging.h"
Austin Schuh217a9782019-12-21 23:02:50 -080029
Brian Silverman66f079a2013-08-26 16:24:30 -070030namespace aos {
Austin Schuh15182322020-10-10 15:25:21 -070031namespace {
Austin Schuhfb37c612022-08-11 15:24:51 -070032namespace chrono = std::chrono;
33
Austin Schuh15182322020-10-10 15:25:21 -070034bool EndsWith(std::string_view str, std::string_view end) {
35 if (str.size() < end.size()) {
36 return false;
37 }
38 if (str.substr(str.size() - end.size(), end.size()) != end) {
39 return false;
40 }
41 return true;
42}
43
44std::string MaybeReplaceExtension(std::string_view filename,
45 std::string_view extension,
46 std::string_view replacement) {
47 if (!EndsWith(filename, extension)) {
48 return std::string(filename);
49 }
50 filename.remove_suffix(extension.size());
51 return absl::StrCat(filename, replacement);
52}
53
54FlatbufferDetachedBuffer<Configuration> ReadConfigFile(std::string_view path,
55 bool binary) {
56 if (binary) {
57 FlatbufferVector<Configuration> config =
58 FileToFlatbuffer<Configuration>(path);
59 return CopySpanAsDetachedBuffer(config.span());
60 }
61
62 flatbuffers::DetachedBuffer buffer = JsonToFlatbuffer(
63 util::ReadFileToStringOrDie(path), ConfigurationTypeTable());
64
Austin Schuh84a039a2021-11-03 16:50:34 -070065 CHECK_GT(buffer.size(), 0u) << ": Failed to parse JSON file: " << path;
Austin Schuh15182322020-10-10 15:25:21 -070066
67 return FlatbufferDetachedBuffer<Configuration>(std::move(buffer));
68}
69
70} // namespace
Austin Schuh40485ed2019-10-26 21:51:44 -070071// Define the compare and equal operators for Channel and Application so we can
Austin Schuhcb108412019-10-13 16:09:54 -070072// insert them in the btree below.
Austin Schuh40485ed2019-10-26 21:51:44 -070073bool operator<(const FlatbufferDetachedBuffer<Channel> &lhs,
74 const FlatbufferDetachedBuffer<Channel> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -070075 int name_compare = lhs.message().name()->string_view().compare(
76 rhs.message().name()->string_view());
77 if (name_compare == 0) {
78 return lhs.message().type()->string_view() <
79 rhs.message().type()->string_view();
80 } else if (name_compare < 0) {
81 return true;
82 } else {
83 return false;
84 }
85}
86
Austin Schuh40485ed2019-10-26 21:51:44 -070087bool operator==(const FlatbufferDetachedBuffer<Channel> &lhs,
88 const FlatbufferDetachedBuffer<Channel> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -070089 return lhs.message().name()->string_view() ==
90 rhs.message().name()->string_view() &&
91 lhs.message().type()->string_view() ==
92 rhs.message().type()->string_view();
93}
94
Austin Schuha7996eb2021-10-11 19:03:24 -070095bool operator<(const FlatbufferDetachedBuffer<Connection> &lhs,
96 const FlatbufferDetachedBuffer<Connection> &rhs) {
97 return lhs.message().name()->string_view() <
98 rhs.message().name()->string_view();
99}
100
101bool operator==(const FlatbufferDetachedBuffer<Connection> &lhs,
102 const FlatbufferDetachedBuffer<Connection> &rhs) {
103 return lhs.message().name()->string_view() ==
104 rhs.message().name()->string_view();
105}
106
Austin Schuh40485ed2019-10-26 21:51:44 -0700107bool operator==(const FlatbufferDetachedBuffer<Application> &lhs,
108 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -0700109 return lhs.message().name()->string_view() ==
110 rhs.message().name()->string_view();
111}
112
Austin Schuh40485ed2019-10-26 21:51:44 -0700113bool operator<(const FlatbufferDetachedBuffer<Application> &lhs,
114 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -0700115 return lhs.message().name()->string_view() <
116 rhs.message().name()->string_view();
117}
118
Austin Schuh217a9782019-12-21 23:02:50 -0800119bool operator==(const FlatbufferDetachedBuffer<Node> &lhs,
120 const FlatbufferDetachedBuffer<Node> &rhs) {
121 return lhs.message().name()->string_view() ==
122 rhs.message().name()->string_view();
123}
124
125bool operator<(const FlatbufferDetachedBuffer<Node> &lhs,
126 const FlatbufferDetachedBuffer<Node> &rhs) {
127 return lhs.message().name()->string_view() <
128 rhs.message().name()->string_view();
129}
130
Brian Silverman66f079a2013-08-26 16:24:30 -0700131namespace configuration {
132namespace {
133
Austin Schuhcb108412019-10-13 16:09:54 -0700134// Extracts the folder part of a path. Returns ./ if there is no path.
Austin Schuhf1fff282020-03-28 16:57:32 -0700135std::string_view ExtractFolder(const std::string_view filename) {
Austin Schuhcb108412019-10-13 16:09:54 -0700136 auto last_slash_pos = filename.find_last_of("/\\");
137
James Kuszmaul3ae42262019-11-08 12:33:41 -0800138 return last_slash_pos == std::string_view::npos
139 ? std::string_view("./")
Austin Schuhcb108412019-10-13 16:09:54 -0700140 : filename.substr(0, last_slash_pos + 1);
141}
142
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700143std::string AbsolutePath(const std::string_view filename) {
144 // Uses an std::string so that we know the input will be null-terminated.
145 const std::string terminated_file(filename);
146 char buffer[PATH_MAX];
147 PCHECK(NULL != realpath(terminated_file.c_str(), buffer));
148 return buffer;
149}
150
Austin Schuhef38cd22021-07-21 15:24:23 -0700151std::string RemoveDotDots(const std::string_view filename) {
152 std::vector<std::string> split = absl::StrSplit(filename, '/');
153 auto iterator = split.begin();
154 while (iterator != split.end()) {
155 if (iterator->empty()) {
156 iterator = split.erase(iterator);
157 } else if (*iterator == ".") {
158 iterator = split.erase(iterator);
159 } else if (*iterator == "..") {
160 CHECK(iterator != split.begin())
161 << ": Import path may not start with ..: " << filename;
162 auto previous = iterator;
163 --previous;
164 split.erase(iterator);
165 iterator = split.erase(previous);
166 } else {
167 ++iterator;
168 }
169 }
170 return absl::StrJoin(split, "/");
171}
172
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700173std::optional<FlatbufferDetachedBuffer<Configuration>> MaybeReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700174 const std::string_view path, absl::btree_set<std::string> *visited_paths,
175 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuh15182322020-10-10 15:25:21 -0700176 std::string binary_path = MaybeReplaceExtension(path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700177 VLOG(1) << "Looking up: " << path << ", starting with: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700178 bool binary_path_exists = util::PathExists(binary_path);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700179 std::string raw_path(path);
Austin Schuh15182322020-10-10 15:25:21 -0700180 // For each .json file, look and see if we can find a .bfbs file next to it
181 // with the same base name. If we can, assume it is the same and use it
182 // instead. It is much faster to load .bfbs files than .json files.
183 if (!binary_path_exists && !util::PathExists(raw_path)) {
184 const bool path_is_absolute = raw_path.size() > 0 && raw_path[0] == '/';
Brian Silvermand0588192022-07-26 00:35:22 -0700185 if (path_is_absolute) {
186 // Nowhere else to look up an absolute path, so fail now. Note that we
187 // always have at least one extra import path based on /proc/self/exe, so
188 // warning about those paths existing isn't helpful.
189 LOG(ERROR) << ": Failed to find file " << path << ".";
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700190 return std::nullopt;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700191 }
192
193 bool found_path = false;
194 for (const auto &import_path : extra_import_paths) {
Austin Schuhef38cd22021-07-21 15:24:23 -0700195 raw_path = std::string(import_path) + "/" + RemoveDotDots(path);
Austin Schuh15182322020-10-10 15:25:21 -0700196 binary_path = MaybeReplaceExtension(raw_path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700197 VLOG(1) << "Checking: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700198 binary_path_exists = util::PathExists(binary_path);
199 if (binary_path_exists) {
200 found_path = true;
201 break;
202 }
Austin Schuhef38cd22021-07-21 15:24:23 -0700203 VLOG(1) << "Checking: " << raw_path;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700204 if (util::PathExists(raw_path)) {
205 found_path = true;
206 break;
207 }
208 }
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700209 if (!found_path) {
210 LOG(ERROR) << ": Failed to find file " << path << ".";
211 return std::nullopt;
212 }
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700213 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700215 std::optional<FlatbufferDetachedBuffer<Configuration>> config =
216 ReadConfigFile(binary_path_exists ? binary_path : raw_path,
217 binary_path_exists);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700218
Austin Schuhcb108412019-10-13 16:09:54 -0700219 // Depth first. Take the following example:
220 //
221 // config1.json:
222 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700223 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700224 // {
225 // "name": "/foo",
226 // "type": ".aos.bar",
227 // "max_size": 5
228 // }
229 // ],
230 // "imports": [
231 // "config2.json",
232 // ]
233 // }
234 //
235 // config2.json:
236 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700237 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700238 // {
239 // "name": "/foo",
240 // "type": ".aos.bar",
241 // "max_size": 7
242 // }
243 // ],
244 // }
245 //
246 // We want the main config (config1.json) to be able to override the imported
247 // config. That means that it needs to be merged into the imported configs,
248 // not the other way around.
249
Austin Schuh15182322020-10-10 15:25:21 -0700250 const std::string absolute_path =
251 AbsolutePath(binary_path_exists ? binary_path : raw_path);
252 // Track that we have seen this file before recursing. Track the path we
253 // actually loaded (which should be consistent if imported twice).
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700254 if (!visited_paths->insert(absolute_path).second) {
255 for (const auto &visited_path : *visited_paths) {
256 LOG(INFO) << "Already visited: " << visited_path;
257 }
258 LOG(FATAL)
259 << "Already imported " << path << " (i.e. " << absolute_path
260 << "). See above for the files that have already been processed.";
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700261 return std::nullopt;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700262 }
Austin Schuhcb108412019-10-13 16:09:54 -0700263
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700264 if (config->message().has_imports()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700265 // Capture the imports.
266 const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *v =
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700267 config->message().imports();
Austin Schuhcb108412019-10-13 16:09:54 -0700268
269 // And then wipe them. This gets GCed when we merge later.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700270 config->mutable_message()->clear_imports();
Austin Schuhcb108412019-10-13 16:09:54 -0700271
272 // Start with an empty configuration to merge into.
Austin Schuh40485ed2019-10-26 21:51:44 -0700273 FlatbufferDetachedBuffer<Configuration> merged_config =
274 FlatbufferDetachedBuffer<Configuration>::Empty();
Austin Schuhcb108412019-10-13 16:09:54 -0700275
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700276 const std::string path_folder(ExtractFolder(path));
Austin Schuhcb108412019-10-13 16:09:54 -0700277 for (const flatbuffers::String *str : *v) {
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700278 const std::string included_config =
279 path_folder + "/" + std::string(str->string_view());
Austin Schuhcb108412019-10-13 16:09:54 -0700280
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700281 const auto optional_config =
282 MaybeReadConfig(included_config, visited_paths, extra_import_paths);
283 if (!optional_config.has_value()) {
284 return std::nullopt;
285 }
Austin Schuhcb108412019-10-13 16:09:54 -0700286 // And them merge everything in.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700287 merged_config = MergeFlatBuffers(merged_config, *optional_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700288 }
289
290 // Finally, merge this file in.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700291 config = MergeFlatBuffers(merged_config, *config);
Austin Schuhcb108412019-10-13 16:09:54 -0700292 }
293 return config;
294}
295
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296// Compares (c < p) a channel, and a name, type tuple.
297bool CompareChannels(const Channel *c,
James Kuszmaul3ae42262019-11-08 12:33:41 -0800298 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299 int name_compare = c->name()->string_view().compare(p.first);
300 if (name_compare == 0) {
301 return c->type()->string_view() < p.second;
302 } else if (name_compare < 0) {
303 return true;
304 } else {
305 return false;
306 }
307};
308
309// Compares for equality (c == p) a channel, and a name, type tuple.
310bool EqualsChannels(const Channel *c,
Austin Schuhf1fff282020-03-28 16:57:32 -0700311 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700312 return c->name()->string_view() == p.first &&
313 c->type()->string_view() == p.second;
314}
315
316// Compares (c < p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800317bool CompareApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700318 return a->name()->string_view() < name;
319};
320
321// Compares for equality (c == p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800322bool EqualsApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323 return a->name()->string_view() == name;
324}
325
Austin Schuh15182322020-10-10 15:25:21 -0700326void ValidateConfiguration(const Flatbuffer<Configuration> &config) {
327 // No imports should be left.
328 CHECK(!config.message().has_imports());
329
330 // Check that if there is a node list, all the source nodes are filled out and
331 // valid, and all the destination nodes are valid (and not the source). This
332 // is a basic consistency check.
333 if (config.message().has_channels()) {
334 const Channel *last_channel = nullptr;
335 for (const Channel *c : *config.message().channels()) {
336 CHECK(c->has_name());
337 CHECK(c->has_type());
338 if (c->name()->string_view().back() == '/') {
339 LOG(FATAL) << "Channel names can't end with '/'";
340 }
Austin Schuh47e382e2023-05-28 11:20:56 -0700341 if (c->name()->string_view().front() != '/') {
342 LOG(FATAL) << "Channel names must start with '/'";
343 }
Austin Schuh15182322020-10-10 15:25:21 -0700344 if (c->name()->string_view().find("//") != std::string_view::npos) {
345 LOG(FATAL) << ": Invalid channel name " << c->name()->string_view()
346 << ", can't use //.";
347 }
348 for (const char data : c->name()->string_view()) {
349 if (data >= '0' && data <= '9') {
350 continue;
351 }
352 if (data >= 'a' && data <= 'z') {
353 continue;
354 }
355 if (data >= 'A' && data <= 'Z') {
356 continue;
357 }
358 if (data == '-' || data == '_' || data == '/') {
359 continue;
360 }
361 LOG(FATAL) << "Invalid channel name " << c->name()->string_view()
362 << ", can only use [-a-zA-Z0-9_/]";
363 }
364
Austin Schuhfb37c612022-08-11 15:24:51 -0700365 CHECK_LT(QueueSize(&config.message(), c) + QueueScratchBufferSize(c),
366 std::numeric_limits<uint16_t>::max())
367 << ": More messages/second configured than the queue can hold on "
368 << CleanedChannelToString(c) << ", " << c->frequency() << "hz for "
369 << config.message().channel_storage_duration() << "ns";
370
Austin Schuha156fb22021-10-11 19:23:21 -0700371 if (c->has_logger_nodes()) {
372 // Confirm that we don't have duplicate logger nodes.
373 absl::btree_set<std::string_view> logger_nodes;
374 for (const flatbuffers::String *s : *c->logger_nodes()) {
375 logger_nodes.insert(s->string_view());
376 }
377 CHECK_EQ(static_cast<size_t>(logger_nodes.size()),
378 c->logger_nodes()->size())
379 << ": Found duplicate logger_nodes in "
380 << CleanedChannelToString(c);
381 }
382
383 if (c->has_destination_nodes()) {
384 // Confirm that we don't have duplicate timestamp logger nodes.
Austin Schuh5e95bd62021-10-11 18:40:22 -0700385 for (const Connection *d : *c->destination_nodes()) {
Austin Schuha156fb22021-10-11 19:23:21 -0700386 if (d->has_timestamp_logger_nodes()) {
387 absl::btree_set<std::string_view> timestamp_logger_nodes;
388 for (const flatbuffers::String *s : *d->timestamp_logger_nodes()) {
389 timestamp_logger_nodes.insert(s->string_view());
390 }
391 CHECK_EQ(static_cast<size_t>(timestamp_logger_nodes.size()),
392 d->timestamp_logger_nodes()->size())
393 << ": Found duplicate timestamp_logger_nodes in "
394 << CleanedChannelToString(c);
395 }
396 }
397
398 // There is no good use case today for logging timestamps but not the
399 // corresponding data. Instead of plumbing through all of this on the
400 // reader side, let'd just disallow it for now.
401 if (c->logger() == LoggerConfig::NOT_LOGGED) {
402 for (const Connection *d : *c->destination_nodes()) {
403 CHECK(d->timestamp_logger() == LoggerConfig::NOT_LOGGED)
404 << ": Logging timestamps without data is not supported. If "
405 "you have a good use case, let's talk. "
406 << CleanedChannelToString(c);
407 }
Austin Schuh5e95bd62021-10-11 18:40:22 -0700408 }
409 }
410
Austin Schuh15182322020-10-10 15:25:21 -0700411 // Make sure everything is sorted while we are here... If this fails,
412 // there will be a bunch of weird errors.
413 if (last_channel != nullptr) {
414 CHECK(CompareChannels(
415 last_channel,
416 std::make_pair(c->name()->string_view(), c->type()->string_view())))
417 << ": Channels not sorted!";
418 }
419 last_channel = c;
420 }
421 }
422
423 if (config.message().has_nodes() && config.message().has_channels()) {
424 for (const Channel *c : *config.message().channels()) {
425 CHECK(c->has_source_node()) << ": Channel " << FlatbufferToJson(c)
426 << " is missing \"source_node\"";
427 CHECK(GetNode(&config.message(), c->source_node()->string_view()) !=
428 nullptr)
429 << ": Channel " << FlatbufferToJson(c)
430 << " has an unknown \"source_node\"";
431
432 if (c->has_destination_nodes()) {
433 for (const Connection *connection : *c->destination_nodes()) {
434 CHECK(connection->has_name());
435 CHECK(GetNode(&config.message(), connection->name()->string_view()) !=
436 nullptr)
437 << ": Channel " << FlatbufferToJson(c)
438 << " has an unknown \"destination_nodes\" "
439 << connection->name()->string_view();
440
441 switch (connection->timestamp_logger()) {
442 case LoggerConfig::LOCAL_LOGGER:
443 case LoggerConfig::NOT_LOGGED:
Austin Schuhb98d02d2022-08-16 13:27:25 -0700444 CHECK(!connection->has_timestamp_logger_nodes())
445 << ": " << CleanedChannelToString(c);
Austin Schuh15182322020-10-10 15:25:21 -0700446 break;
447 case LoggerConfig::REMOTE_LOGGER:
448 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
449 CHECK(connection->has_timestamp_logger_nodes());
450 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
451 for (const flatbuffers::String *timestamp_logger_node :
452 *connection->timestamp_logger_nodes()) {
453 CHECK(GetNode(&config.message(),
454 timestamp_logger_node->string_view()) != nullptr)
455 << ": Channel " << FlatbufferToJson(c)
456 << " has an unknown \"timestamp_logger_node\""
457 << connection->name()->string_view();
458 }
459 break;
460 }
461
462 CHECK_NE(connection->name()->string_view(),
463 c->source_node()->string_view())
464 << ": Channel " << FlatbufferToJson(c)
465 << " is forwarding data to itself";
466 }
467 }
468 }
469 }
470}
471
James Kuszmaulc8503f32022-06-25 16:17:12 -0700472void HandleReverseMaps(
473 const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
474 std::string_view type, const Node *node, std::set<std::string> *names) {
475 for (const Map *map : *maps) {
476 CHECK_NOTNULL(map);
477 const Channel *const match = CHECK_NOTNULL(map->match());
478 const Channel *const rename = CHECK_NOTNULL(map->rename());
479
480 // Handle type specific maps.
481 const flatbuffers::String *const match_type_string = match->type();
482 if (match_type_string != nullptr &&
483 match_type_string->string_view() != type) {
484 continue;
485 }
486
487 // Now handle node specific maps.
488 const flatbuffers::String *const match_source_node_string =
489 match->source_node();
490 if (node != nullptr && match_source_node_string != nullptr &&
491 match_source_node_string->string_view() !=
492 node->name()->string_view()) {
493 continue;
494 }
495
496 const flatbuffers::String *const match_name_string = match->name();
497 const flatbuffers::String *const rename_name_string = rename->name();
498 if (match_name_string == nullptr || rename_name_string == nullptr) {
499 continue;
500 }
501
502 const std::string rename_name = rename_name_string->str();
503 const std::string_view match_name = match_name_string->string_view();
504
505 std::set<std::string> possible_renames;
506
507 // Check if the current name(s) could have been reached using the provided
508 // rename.
509 if (match_name.back() == '*') {
510 for (const std::string &option : *names) {
511 if (option.substr(0, rename_name.size()) == rename_name) {
512 possible_renames.insert(
513 absl::StrCat(match_name.substr(0, match_name.size() - 1),
514 option.substr(rename_name.size())));
515 }
516 }
517 names->insert(possible_renames.begin(), possible_renames.end());
518 } else if (names->count(rename_name) != 0) {
519 names->insert(std::string(match_name));
520 }
521 }
522}
523
Alex Perrycb7da4b2019-08-28 19:35:56 -0700524} // namespace
525
Austin Schuh006a9f52021-04-07 16:24:18 -0700526// Maps name for the provided maps. Modifies name.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800527//
528// This is called many times during startup, and it dereferences a lot of
529// pointers. These combine to make it a performance hotspot during many tests
530// under msan, so there is some optimizing around caching intermediates instead
531// of dereferencing the pointer multiple times.
James Kuszmaulc8503f32022-06-25 16:17:12 -0700532//
533// Deliberately not in an anonymous namespace so that the log-reading code can
534// reference it.
Austin Schuh006a9f52021-04-07 16:24:18 -0700535void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
536 std::string *name, std::string_view type, const Node *node) {
537 // For the same reason we merge configs in reverse order, we want to process
538 // maps in reverse order. That lets the outer config overwrite channels from
539 // the inner configs.
540 for (auto i = maps->rbegin(); i != maps->rend(); ++i) {
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800541 const Channel *const match = i->match();
542 if (!match) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700543 continue;
544 }
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800545 const flatbuffers::String *const match_name_string = match->name();
546 if (!match_name_string) {
547 continue;
548 }
549 const Channel *const rename = i->rename();
550 if (!rename) {
551 continue;
552 }
553 const flatbuffers::String *const rename_name_string = rename->name();
554 if (!rename_name_string) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700555 continue;
556 }
557
558 // Handle normal maps (now that we know that match and rename are filled
559 // out).
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800560 const std::string_view match_name = match_name_string->string_view();
Austin Schuh006a9f52021-04-07 16:24:18 -0700561 if (match_name != *name) {
562 if (match_name.back() == '*' &&
563 std::string_view(*name).substr(
564 0, std::min(name->size(), match_name.size() - 1)) ==
565 match_name.substr(0, match_name.size() - 1)) {
566 CHECK_EQ(match_name.find('*'), match_name.size() - 1);
567 } else {
568 continue;
569 }
570 }
571
572 // Handle type specific maps.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800573 const flatbuffers::String *const match_type_string = match->type();
574 if (match_type_string && match_type_string->string_view() != type) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700575 continue;
576 }
577
578 // Now handle node specific maps.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800579 const flatbuffers::String *const match_source_node_string =
580 match->source_node();
581 if (node && match_source_node_string &&
582 match_source_node_string->string_view() !=
Austin Schuh006a9f52021-04-07 16:24:18 -0700583 node->name()->string_view()) {
584 continue;
585 }
586
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800587 std::string new_name(rename_name_string->string_view());
Austin Schuh006a9f52021-04-07 16:24:18 -0700588 if (match_name.back() == '*') {
589 new_name += std::string(name->substr(match_name.size() - 1));
590 }
591 VLOG(1) << "Renamed \"" << *name << "\" to \"" << new_name << "\"";
592 *name = std::move(new_name);
593 }
594}
595
James Kuszmaulc8503f32022-06-25 16:17:12 -0700596std::set<std::string> GetChannelAliases(const Configuration *config,
597 std::string_view name,
598 std::string_view type,
599 const std::string_view application_name,
600 const Node *node) {
601 std::set<std::string> names{std::string(name)};
602 if (config->has_maps()) {
603 HandleReverseMaps(config->maps(), type, node, &names);
604 }
605 {
606 const Application *application =
607 GetApplication(config, node, application_name);
608 if (application != nullptr && application->has_maps()) {
609 HandleReverseMaps(application->maps(), type, node, &names);
610 }
611 }
612 return names;
613}
614
Austin Schuh40485ed2019-10-26 21:51:44 -0700615FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
Austin Schuhcb108412019-10-13 16:09:54 -0700616 const Flatbuffer<Configuration> &config) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700617 // auto_merge_config will contain all the fields of the Configuration that are
618 // to be passed through unmodified to the result of MergeConfiguration().
619 // In the processing below, we mutate auto_merge_config to remove any fields
620 // which we do need to alter (hence why we can't use the input config
621 // directly), and then merge auto_merge_config back in at the end.
622 aos::FlatbufferDetachedBuffer<aos::Configuration> auto_merge_config =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800623 aos::RecursiveCopyFlatBuffer(&config.message());
James Kuszmaul3c998592020-07-27 21:04:47 -0700624
Austin Schuh40485ed2019-10-26 21:51:44 -0700625 // Store all the channels in a sorted set. This lets us track channels we
Austin Schuhcb108412019-10-13 16:09:54 -0700626 // have seen before and merge the updates in.
Austin Schuh40485ed2019-10-26 21:51:44 -0700627 absl::btree_set<FlatbufferDetachedBuffer<Channel>> channels;
Austin Schuhcb108412019-10-13 16:09:54 -0700628
Austin Schuh40485ed2019-10-26 21:51:44 -0700629 if (config.message().has_channels()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700630 auto_merge_config.mutable_message()->clear_channels();
Austin Schuh40485ed2019-10-26 21:51:44 -0700631 for (const Channel *c : *config.message().channels()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700632 // Ignore malformed entries.
Austin Schuh40485ed2019-10-26 21:51:44 -0700633 if (!c->has_name()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700634 continue;
635 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700636 if (!c->has_type()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700637 continue;
638 }
639
Brian Silverman77162972020-08-12 19:52:40 -0700640 CHECK_EQ(c->read_method() == ReadMethod::PIN, c->num_readers() != 0)
641 << ": num_readers may be set if and only if read_method is PIN,"
642 " if you want 0 readers do not set PIN: "
643 << CleanedChannelToString(c);
644
Austin Schuh40485ed2019-10-26 21:51:44 -0700645 // Attempt to insert the channel.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800646 auto result = channels.insert(RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700647 if (!result.second) {
648 // Already there, so merge the new table into the original.
Austin Schuh4a5f5d22021-10-12 15:09:35 -0700649 // Schemas merge poorly, so pick the newest one.
650 if (result.first->message().has_schema() && c->has_schema()) {
651 result.first->mutable_message()->clear_schema();
652 }
Austin Schuha7996eb2021-10-11 19:03:24 -0700653 auto merged =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800654 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(c));
Austin Schuha7996eb2021-10-11 19:03:24 -0700655
656 if (merged.message().has_destination_nodes()) {
657 absl::btree_set<FlatbufferDetachedBuffer<Connection>> connections;
658 for (const Connection *connection :
659 *merged.message().destination_nodes()) {
660 auto connection_result =
661 connections.insert(RecursiveCopyFlatBuffer(connection));
662 if (!connection_result.second) {
663 *connection_result.first =
664 MergeFlatBuffers(*connection_result.first,
665 RecursiveCopyFlatBuffer(connection));
666 }
667 }
668 if (static_cast<size_t>(connections.size()) !=
669 merged.message().destination_nodes()->size()) {
670 merged.mutable_message()->clear_destination_nodes();
671 flatbuffers::FlatBufferBuilder fbb;
672 fbb.ForceDefaults(true);
673 std::vector<flatbuffers::Offset<Connection>> connection_offsets;
674 for (const FlatbufferDetachedBuffer<Connection> &connection :
675 connections) {
676 connection_offsets.push_back(
677 RecursiveCopyFlatBuffer(&connection.message(), &fbb));
678 }
679 flatbuffers::Offset<
680 flatbuffers::Vector<flatbuffers::Offset<Connection>>>
681 destination_nodes_offset = fbb.CreateVector(connection_offsets);
682 Channel::Builder channel_builder(fbb);
683 channel_builder.add_destination_nodes(destination_nodes_offset);
684 fbb.Finish(channel_builder.Finish());
685 FlatbufferDetachedBuffer<Channel> destinations_channel(
686 fbb.Release());
687 merged = MergeFlatBuffers(merged, destinations_channel);
688 }
689 }
690
691 *result.first = std::move(merged);
Austin Schuhcb108412019-10-13 16:09:54 -0700692 }
693 }
694 }
695
696 // Now repeat this for the application list.
Austin Schuh40485ed2019-10-26 21:51:44 -0700697 absl::btree_set<FlatbufferDetachedBuffer<Application>> applications;
Austin Schuhcb108412019-10-13 16:09:54 -0700698 if (config.message().has_applications()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700699 auto_merge_config.mutable_message()->clear_applications();
Austin Schuhcb108412019-10-13 16:09:54 -0700700 for (const Application *a : *config.message().applications()) {
701 if (!a->has_name()) {
702 continue;
703 }
704
Austin Schuha4fc60f2020-11-01 23:06:47 -0800705 auto result = applications.insert(RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700706 if (!result.second) {
Austin Schuhf81c2522021-12-08 12:03:30 -0800707 if (a->has_args()) {
708 result.first->mutable_message()->clear_args();
709 }
Austin Schuha4fc60f2020-11-01 23:06:47 -0800710 *result.first =
711 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700712 }
713 }
714 }
715
Austin Schuh217a9782019-12-21 23:02:50 -0800716 // Now repeat this for the node list.
717 absl::btree_set<FlatbufferDetachedBuffer<Node>> nodes;
718 if (config.message().has_nodes()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700719 auto_merge_config.mutable_message()->clear_nodes();
Austin Schuh217a9782019-12-21 23:02:50 -0800720 for (const Node *n : *config.message().nodes()) {
721 if (!n->has_name()) {
722 continue;
723 }
724
Austin Schuha4fc60f2020-11-01 23:06:47 -0800725 auto result = nodes.insert(RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800726 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800727 *result.first =
728 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800729 }
730 }
731 }
732
Austin Schuhcb108412019-10-13 16:09:54 -0700733 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800734 fbb.ForceDefaults(true);
Austin Schuhcb108412019-10-13 16:09:54 -0700735
736 // Start by building the vectors. They need to come before the final table.
Austin Schuh40485ed2019-10-26 21:51:44 -0700737 // Channels
738 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
739 channels_offset;
Austin Schuhcb108412019-10-13 16:09:54 -0700740 {
Austin Schuh40485ed2019-10-26 21:51:44 -0700741 ::std::vector<flatbuffers::Offset<Channel>> channel_offsets;
742 for (const FlatbufferDetachedBuffer<Channel> &c : channels) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800743 channel_offsets.emplace_back(
744 RecursiveCopyFlatBuffer<Channel>(&c.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700745 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700746 channels_offset = fbb.CreateVector(channel_offsets);
Austin Schuhcb108412019-10-13 16:09:54 -0700747 }
748
749 // Applications
750 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
751 applications_offset;
752 {
753 ::std::vector<flatbuffers::Offset<Application>> applications_offsets;
Austin Schuh40485ed2019-10-26 21:51:44 -0700754 for (const FlatbufferDetachedBuffer<Application> &a : applications) {
Austin Schuhcb108412019-10-13 16:09:54 -0700755 applications_offsets.emplace_back(
Austin Schuha4fc60f2020-11-01 23:06:47 -0800756 RecursiveCopyFlatBuffer<Application>(&a.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700757 }
758 applications_offset = fbb.CreateVector(applications_offsets);
759 }
760
Austin Schuh217a9782019-12-21 23:02:50 -0800761 // Nodes
762 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
763 nodes_offset;
764 {
765 ::std::vector<flatbuffers::Offset<Node>> node_offsets;
766 for (const FlatbufferDetachedBuffer<Node> &n : nodes) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800767 node_offsets.emplace_back(
768 RecursiveCopyFlatBuffer<Node>(&n.message(), &fbb));
Austin Schuh217a9782019-12-21 23:02:50 -0800769 }
770 nodes_offset = fbb.CreateVector(node_offsets);
771 }
772
Austin Schuhcb108412019-10-13 16:09:54 -0700773 // And then build a Configuration with them all.
774 ConfigurationBuilder configuration_builder(fbb);
Austin Schuh40485ed2019-10-26 21:51:44 -0700775 configuration_builder.add_channels(channels_offset);
Austin Schuh217a9782019-12-21 23:02:50 -0800776 if (config.message().has_applications()) {
777 configuration_builder.add_applications(applications_offset);
778 }
779 if (config.message().has_nodes()) {
780 configuration_builder.add_nodes(nodes_offset);
781 }
Austin Schuhcb108412019-10-13 16:09:54 -0700782
783 fbb.Finish(configuration_builder.Finish());
Austin Schuh217a9782019-12-21 23:02:50 -0800784
James Kuszmaul3c998592020-07-27 21:04:47 -0700785 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
786 fbb.Release());
787
Austin Schuh217a9782019-12-21 23:02:50 -0800788 // Now, validate that if there is a node list, every channel has a source
789 // node.
James Kuszmaul3c998592020-07-27 21:04:47 -0700790 FlatbufferDetachedBuffer<Configuration> result =
791 MergeFlatBuffers(modified_config, auto_merge_config);
Austin Schuh217a9782019-12-21 23:02:50 -0800792
Austin Schuh15182322020-10-10 15:25:21 -0700793 ValidateConfiguration(result);
Austin Schuh217a9782019-12-21 23:02:50 -0800794
795 return result;
Austin Schuhcb108412019-10-13 16:09:54 -0700796}
797
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700798std::optional<FlatbufferDetachedBuffer<Configuration>> MaybeReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700799 const std::string_view path,
Austin Schuhef38cd22021-07-21 15:24:23 -0700800 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuh89026f52022-02-25 14:24:04 -0800801 // Add the executable directory to the search path. That makes it so that
802 // tools can be run from any directory without hard-coding an absolute path to
803 // the config into all binaries.
804 std::vector<std::string_view> extra_import_paths_with_exe =
805 extra_import_paths;
806 char proc_self_exec_buffer[PATH_MAX + 1];
807 std::memset(proc_self_exec_buffer, 0, sizeof(proc_self_exec_buffer));
808 ssize_t s = readlink("/proc/self/exe", proc_self_exec_buffer, PATH_MAX);
809 if (s > 0) {
810 // If the readlink call fails, the worst thing that happens is that we don't
811 // automatically find the config next to the binary. VLOG to make it easier
812 // to debug.
813 std::string_view proc_self_exec(proc_self_exec_buffer);
814
815 extra_import_paths_with_exe.emplace_back(
816 proc_self_exec.substr(0, proc_self_exec.rfind("/")));
817 } else {
818 VLOG(1) << "Failed to read /proc/self/exe";
819 }
820
Austin Schuhcb108412019-10-13 16:09:54 -0700821 // We only want to read a file once. So track the visited files in a set.
822 absl::btree_set<std::string> visited_paths;
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700823 std::optional<FlatbufferDetachedBuffer<Configuration>> read_config =
824 MaybeReadConfig(path, &visited_paths, extra_import_paths_with_exe);
825
826 if (read_config == std::nullopt) {
827 return read_config;
828 }
Austin Schuh15182322020-10-10 15:25:21 -0700829
830 // If we only read one file, and it had a .bfbs extension, it has to be a
831 // fully formatted config. Do a quick verification and return it.
832 if (visited_paths.size() == 1 && EndsWith(*visited_paths.begin(), ".bfbs")) {
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700833 ValidateConfiguration(*read_config);
Austin Schuh15182322020-10-10 15:25:21 -0700834 return read_config;
835 }
836
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700837 return MergeConfiguration(*read_config);
838}
839
840FlatbufferDetachedBuffer<Configuration> ReadConfig(
841 const std::string_view path,
842 const std::vector<std::string_view> &extra_import_paths) {
843 auto optional_config = MaybeReadConfig(path, extra_import_paths);
844 CHECK(optional_config) << "Could not read config. See above errors";
845 return std::move(*optional_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700846}
847
Austin Schuh8d6cea82020-02-28 12:17:16 -0800848FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Brian Silverman24f5aa82020-06-23 16:21:28 -0700849 const Configuration *config, const Flatbuffer<Configuration> &addition) {
850 return MergeConfiguration(MergeFlatBuffers(config, &addition.message()));
851}
852
853FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Austin Schuh8d6cea82020-02-28 12:17:16 -0800854 const Configuration *config, std::string_view json) {
855 FlatbufferDetachedBuffer<Configuration> addition =
856 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
857
Brian Silverman24f5aa82020-06-23 16:21:28 -0700858 return MergeWithConfig(config, addition);
Austin Schuh8d6cea82020-02-28 12:17:16 -0800859}
860
James Kuszmaul3ae42262019-11-08 12:33:41 -0800861const Channel *GetChannel(const Configuration *config, std::string_view name,
862 std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800863 std::string_view application_name, const Node *node,
864 bool quiet) {
Brian Silverman9fcf2c72020-12-21 18:30:58 -0800865 if (!config->has_channels()) {
866 return nullptr;
867 }
868
Austin Schuhbca6cf02019-12-22 17:28:34 -0800869 const std::string_view original_name = name;
Austin Schuhf1fff282020-03-28 16:57:32 -0700870 std::string mutable_name;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700871 if (node != nullptr) {
872 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
873 << "\" } on " << aos::FlatbufferToJson(node);
874 } else {
875 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
876 << "\" }";
877 }
Austin Schuhcb108412019-10-13 16:09:54 -0700878
879 // First handle application specific maps. Only do this if we have a matching
880 // application name, and it has maps.
Austin Schuhd2e2f6a2021-02-07 20:46:16 -0800881 {
882 const Application *application =
883 GetApplication(config, node, application_name);
884 if (application != nullptr && application->has_maps()) {
885 mutable_name = std::string(name);
886 HandleMaps(application->maps(), &mutable_name, type, node);
887 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700888 }
889 }
890
891 // Now do global maps.
Austin Schuh40485ed2019-10-26 21:51:44 -0700892 if (config->has_maps()) {
Austin Schuhf1fff282020-03-28 16:57:32 -0700893 mutable_name = std::string(name);
894 HandleMaps(config->maps(), &mutable_name, type, node);
895 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700896 }
897
Austin Schuhbca6cf02019-12-22 17:28:34 -0800898 if (original_name != name) {
899 VLOG(1) << "Remapped to { \"name\": \"" << name << "\", \"type\": \""
900 << type << "\" }";
901 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902
James Kuszmaul71a81932020-12-15 21:08:01 -0800903 // Then look for the channel (note that this relies on the channels being
904 // sorted in the config).
Austin Schuh40485ed2019-10-26 21:51:44 -0700905 auto channel_iterator =
Austin Schuhf1fff282020-03-28 16:57:32 -0700906 std::lower_bound(config->channels()->cbegin(), config->channels()->cend(),
Austin Schuh40485ed2019-10-26 21:51:44 -0700907 std::make_pair(name, type), CompareChannels);
Austin Schuhcb108412019-10-13 16:09:54 -0700908
909 // Make sure we actually found it, and it matches.
Austin Schuh40485ed2019-10-26 21:51:44 -0700910 if (channel_iterator != config->channels()->cend() &&
911 EqualsChannels(*channel_iterator, std::make_pair(name, type))) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800912 if (VLOG_IS_ON(2)) {
913 VLOG(2) << "Found: " << FlatbufferToJson(*channel_iterator);
914 } else if (VLOG_IS_ON(1)) {
915 VLOG(1) << "Found: " << CleanedChannelToString(*channel_iterator);
916 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700917 return *channel_iterator;
Austin Schuhcb108412019-10-13 16:09:54 -0700918 } else {
919 VLOG(1) << "No match for { \"name\": \"" << name << "\", \"type\": \""
920 << type << "\" }";
Austin Schuh0de30f32020-12-06 12:44:28 -0800921 if (original_name != name && !quiet) {
Austin Schuh4b42b252020-10-19 11:35:20 -0700922 LOG(WARNING) << "Remapped from {\"name\": \"" << original_name
923 << "\", \"type\": \"" << type << "\"}, to {\"name\": \""
924 << name << "\", \"type\": \"" << type
925 << "\"}, but no channel by that name exists.";
926 }
Austin Schuhcb108412019-10-13 16:09:54 -0700927 return nullptr;
928 }
929}
930
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800931size_t ChannelIndex(const Configuration *configuration,
932 const Channel *channel) {
933 CHECK(configuration->channels() != nullptr) << ": No channels";
934
Brian Silvermana9698c92021-11-10 12:27:04 -0800935 const auto c = std::lower_bound(
936 configuration->channels()->cbegin(), configuration->channels()->cend(),
937 std::make_pair(channel->name()->string_view(),
938 channel->type()->string_view()),
939 CompareChannels);
940 CHECK(c != configuration->channels()->cend())
941 << ": Channel pointer not found in configuration()->channels()";
942 CHECK(*c == channel)
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800943 << ": Channel pointer not found in configuration()->channels()";
944
Brian Silvermana9698c92021-11-10 12:27:04 -0800945 return std::distance(configuration->channels()->cbegin(), c);
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800946}
947
Austin Schuhbca6cf02019-12-22 17:28:34 -0800948std::string CleanedChannelToString(const Channel *channel) {
949 FlatbufferDetachedBuffer<Channel> cleaned_channel = CopyFlatBuffer(channel);
950 cleaned_channel.mutable_message()->clear_schema();
951 return FlatbufferToJson(cleaned_channel);
952}
953
Austin Schuha81454b2020-05-12 19:58:36 -0700954std::string StrippedChannelToString(const Channel *channel) {
955 return absl::StrCat("{ \"name\": \"", channel->name()->string_view(),
956 "\", \"type\": \"", channel->type()->string_view(),
957 "\" }");
958}
959
Alex Perrycb7da4b2019-08-28 19:35:56 -0700960FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
961 const Flatbuffer<Configuration> &config,
Austin Schuh0de30f32020-12-06 12:44:28 -0800962 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700963 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800964 fbb.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700965
Austin Schuh68d98592020-11-01 23:22:57 -0800966 // Cache for holding already inserted schemas.
967 std::map<std::string_view, flatbuffers::Offset<reflection::Schema>>
968 schema_cache;
969
970 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
971 << ": Merging logic needs to be updated when the number of channel "
972 "fields changes.";
James Kuszmaul3c998592020-07-27 21:04:47 -0700973
Alex Perrycb7da4b2019-08-28 19:35:56 -0700974 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
975 channels_offset;
976 if (config.message().has_channels()) {
977 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
978 for (const Channel *c : *config.message().channels()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700979 // Search for a schema with a matching type.
Austin Schuh0de30f32020-12-06 12:44:28 -0800980 const aos::FlatbufferVector<reflection::Schema> *found_schema = nullptr;
981 for (const aos::FlatbufferVector<reflection::Schema> &schema : schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700982 if (schema.message().root_table() != nullptr) {
983 if (schema.message().root_table()->name()->string_view() ==
984 c->type()->string_view()) {
985 found_schema = &schema;
986 }
987 }
988 }
989
Maxwell Gumley65d06582023-03-17 09:13:50 -0600990 if (found_schema == nullptr) {
991 std::stringstream ss;
992 for (const aos::FlatbufferVector<reflection::Schema> &schema :
993 schemas) {
994 if (schema.message().root_table() == nullptr) {
995 continue;
996 }
997 auto name = schema.message().root_table()->name()->string_view();
998 ss << "\n\tname: " << name;
999 }
1000 LOG(FATAL) << ": Failed to find schema for " << FlatbufferToJson(c)
1001 << "\n\tThe following schemas were found:\n"
1002 << ss.str();
1003 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001004
Austin Schuh68d98592020-11-01 23:22:57 -08001005 // Now copy the message manually.
1006 auto cached_schema = schema_cache.find(c->type()->string_view());
1007 flatbuffers::Offset<reflection::Schema> schema_offset;
1008 if (cached_schema != schema_cache.end()) {
1009 schema_offset = cached_schema->second;
1010 } else {
Austin Schuha4fc60f2020-11-01 23:06:47 -08001011 schema_offset = RecursiveCopyFlatBuffer<reflection::Schema>(
1012 &found_schema->message(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001013 schema_cache.emplace(c->type()->string_view(), schema_offset);
1014 }
1015
1016 flatbuffers::Offset<flatbuffers::String> name_offset =
1017 fbb.CreateSharedString(c->name()->str());
1018 flatbuffers::Offset<flatbuffers::String> type_offset =
1019 fbb.CreateSharedString(c->type()->str());
1020 flatbuffers::Offset<flatbuffers::String> source_node_offset =
Austin Schuha4fc60f2020-11-01 23:06:47 -08001021 c->has_source_node() ? fbb.CreateSharedString(c->source_node()->str())
1022 : 0;
Austin Schuh68d98592020-11-01 23:22:57 -08001023
1024 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
1025 destination_nodes_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -08001026 aos::RecursiveCopyVectorTable(c->destination_nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001027
1028 flatbuffers::Offset<
1029 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
1030 logger_nodes_offset =
1031 aos::CopyVectorSharedString(c->logger_nodes(), &fbb);
1032
1033 Channel::Builder channel_builder(fbb);
1034 channel_builder.add_name(name_offset);
1035 channel_builder.add_type(type_offset);
1036 if (c->has_frequency()) {
1037 channel_builder.add_frequency(c->frequency());
1038 }
1039 if (c->has_max_size()) {
1040 channel_builder.add_max_size(c->max_size());
1041 }
1042 if (c->has_num_senders()) {
1043 channel_builder.add_num_senders(c->num_senders());
1044 }
1045 if (c->has_num_watchers()) {
1046 channel_builder.add_num_watchers(c->num_watchers());
1047 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001048 channel_builder.add_schema(schema_offset);
Austin Schuh68d98592020-11-01 23:22:57 -08001049 if (!source_node_offset.IsNull()) {
1050 channel_builder.add_source_node(source_node_offset);
1051 }
1052 if (!destination_nodes_offset.IsNull()) {
1053 channel_builder.add_destination_nodes(destination_nodes_offset);
1054 }
1055 if (c->has_logger()) {
1056 channel_builder.add_logger(c->logger());
1057 }
1058 if (!logger_nodes_offset.IsNull()) {
1059 channel_builder.add_logger_nodes(logger_nodes_offset);
1060 }
1061 if (c->has_read_method()) {
1062 channel_builder.add_read_method(c->read_method());
1063 }
1064 if (c->has_num_readers()) {
1065 channel_builder.add_num_readers(c->num_readers());
1066 }
1067 channel_offsets.emplace_back(channel_builder.Finish());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001068 }
1069 channels_offset = fbb.CreateVector(channel_offsets);
1070 }
1071
Austin Schuh68d98592020-11-01 23:22:57 -08001072 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -08001073 maps_offset =
1074 aos::RecursiveCopyVectorTable(config.message().maps(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001075
1076 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -08001077 nodes_offset =
1078 aos::RecursiveCopyVectorTable(config.message().nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001079
1080 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1081 applications_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -08001082 aos::RecursiveCopyVectorTable(config.message().applications(), &fbb);
Austin Schuh217a9782019-12-21 23:02:50 -08001083
1084 // Now insert everything else in unmodified.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001085 ConfigurationBuilder configuration_builder(fbb);
1086 if (config.message().has_channels()) {
1087 configuration_builder.add_channels(channels_offset);
1088 }
Austin Schuh68d98592020-11-01 23:22:57 -08001089 if (!maps_offset.IsNull()) {
1090 configuration_builder.add_maps(maps_offset);
1091 }
1092 if (!nodes_offset.IsNull()) {
1093 configuration_builder.add_nodes(nodes_offset);
1094 }
1095 if (!applications_offset.IsNull()) {
1096 configuration_builder.add_applications(applications_offset);
1097 }
1098
1099 if (config.message().has_channel_storage_duration()) {
1100 configuration_builder.add_channel_storage_duration(
1101 config.message().channel_storage_duration());
1102 }
1103
1104 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1105 << ": Merging logic needs to be updated when the number of configuration "
1106 "fields changes.";
1107
Alex Perrycb7da4b2019-08-28 19:35:56 -07001108 fbb.Finish(configuration_builder.Finish());
James Kuszmaul3c998592020-07-27 21:04:47 -07001109 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
1110 fbb.Release());
1111
Austin Schuh68d98592020-11-01 23:22:57 -08001112 return modified_config;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001113}
1114
Austin Schuh217a9782019-12-21 23:02:50 -08001115const Node *GetNodeFromHostname(const Configuration *config,
1116 std::string_view hostname) {
1117 for (const Node *node : *config->nodes()) {
Brian Silvermanaa2633f2020-02-17 21:04:14 -08001118 if (node->has_hostname() && node->hostname()->string_view() == hostname) {
Austin Schuh217a9782019-12-21 23:02:50 -08001119 return node;
1120 }
Brian Silvermanaa2633f2020-02-17 21:04:14 -08001121 if (node->has_hostnames()) {
1122 for (const auto &candidate : *node->hostnames()) {
1123 if (candidate->string_view() == hostname) {
1124 return node;
1125 }
1126 }
1127 }
Austin Schuh217a9782019-12-21 23:02:50 -08001128 }
1129 return nullptr;
1130}
Austin Schuhac0771c2020-01-07 18:36:30 -08001131
Austin Schuh217a9782019-12-21 23:02:50 -08001132const Node *GetMyNode(const Configuration *config) {
1133 const std::string hostname = (FLAGS_override_hostname.size() > 0)
1134 ? FLAGS_override_hostname
1135 : network::GetHostname();
1136 const Node *node = GetNodeFromHostname(config, hostname);
1137 if (node != nullptr) return node;
1138
1139 LOG(FATAL) << "Unknown node for host: " << hostname
1140 << ". Consider using --override_hostname if hostname detection "
1141 "is wrong.";
1142 return nullptr;
1143}
1144
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001145const Node *GetNode(const Configuration *config, const Node *node) {
1146 if (!MultiNode(config)) {
1147 CHECK(node == nullptr) << ": Provided a node in a single node world.";
1148 return nullptr;
1149 } else {
1150 CHECK(node != nullptr);
1151 CHECK(node->has_name());
1152 return GetNode(config, node->name()->string_view());
1153 }
1154}
1155
Austin Schuh217a9782019-12-21 23:02:50 -08001156const Node *GetNode(const Configuration *config, std::string_view name) {
Austin Schuhfd960622020-01-01 13:22:55 -08001157 CHECK(config->has_nodes())
1158 << ": Asking for a node from a single node configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -08001159 for (const Node *node : *config->nodes()) {
Austin Schuhfd960622020-01-01 13:22:55 -08001160 CHECK(node->has_name()) << ": Malformed node " << FlatbufferToJson(node);
Austin Schuh217a9782019-12-21 23:02:50 -08001161 if (node->name()->string_view() == name) {
1162 return node;
1163 }
1164 }
1165 return nullptr;
1166}
1167
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001168const Node *GetNode(const Configuration *config, size_t node_index) {
1169 if (!MultiNode(config)) {
1170 CHECK_EQ(node_index, 0u) << ": Invalid node in a single node world.";
1171 return nullptr;
1172 } else {
1173 CHECK_LT(node_index, config->nodes()->size());
1174 return config->nodes()->Get(node_index);
1175 }
1176}
1177
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001178const Node *GetNodeOrDie(const Configuration *config, const Node *node) {
1179 if (!MultiNode(config)) {
1180 CHECK(node == nullptr) << ": Provided a node in a single node world.";
1181 return nullptr;
1182 } else {
1183 const Node *config_node = GetNode(config, node);
1184 if (config_node == nullptr) {
1185 LOG(FATAL) << "Couldn't find node matching " << FlatbufferToJson(node);
1186 }
1187 return config_node;
1188 }
1189}
1190
Austin Schuh8bd96322020-02-13 21:18:22 -08001191namespace {
1192int GetNodeIndexFromConfig(const Configuration *config, const Node *node) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001193 int node_index = 0;
1194 for (const Node *iterated_node : *config->nodes()) {
1195 if (iterated_node == node) {
1196 return node_index;
1197 }
1198 ++node_index;
1199 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001200 return -1;
1201}
1202} // namespace
1203
Austin Schuha9df9ad2021-06-16 14:49:39 -07001204aos::FlatbufferDetachedBuffer<aos::Configuration> AddSchema(
1205 std::string_view json,
1206 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
1207 FlatbufferDetachedBuffer<Configuration> addition =
1208 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
1209 return MergeConfiguration(addition, schemas);
1210}
1211
Austin Schuh8bd96322020-02-13 21:18:22 -08001212int GetNodeIndex(const Configuration *config, const Node *node) {
1213 if (!MultiNode(config)) {
1214 return 0;
1215 }
1216
1217 {
1218 int node_index = GetNodeIndexFromConfig(config, node);
1219 if (node_index != -1) {
1220 return node_index;
1221 }
1222 }
1223
1224 const Node *result = GetNode(config, node);
1225 CHECK(result != nullptr);
1226
1227 {
Austin Schuh04408fc2020-02-16 21:48:54 -08001228 int node_index = GetNodeIndexFromConfig(config, result);
Austin Schuh8bd96322020-02-13 21:18:22 -08001229 if (node_index != -1) {
1230 return node_index;
1231 }
1232 }
1233
1234 LOG(FATAL) << "Node " << FlatbufferToJson(node)
1235 << " not found in the configuration.";
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001236}
1237
Austin Schuh04408fc2020-02-16 21:48:54 -08001238int GetNodeIndex(const Configuration *config, std::string_view name) {
1239 if (!MultiNode(config)) {
1240 return 0;
1241 }
1242
1243 {
1244 int node_index = 0;
1245 for (const Node *iterated_node : *config->nodes()) {
1246 if (iterated_node->name()->string_view() == name) {
1247 return node_index;
1248 }
1249 ++node_index;
1250 }
1251 }
1252 LOG(FATAL) << "Node " << name << " not found in the configuration.";
1253}
1254
Austin Schuh681a2472020-12-31 23:55:40 -08001255size_t NodesCount(const Configuration *config) {
1256 if (!MultiNode(config)) {
1257 return 1u;
1258 }
1259
1260 return config->nodes()->size();
1261}
1262
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001263std::vector<const Node *> GetNodes(const Configuration *config) {
1264 std::vector<const Node *> nodes;
Austin Schuh8bd96322020-02-13 21:18:22 -08001265 if (MultiNode(config)) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001266 for (const Node *node : *config->nodes()) {
1267 nodes.emplace_back(node);
1268 }
1269 } else {
1270 nodes.emplace_back(nullptr);
1271 }
1272 return nodes;
1273}
1274
Austin Schuh65465332020-11-05 17:36:53 -08001275std::vector<const Node *> GetNodesWithTag(const Configuration *config,
1276 std::string_view tag) {
1277 std::vector<const Node *> nodes;
1278 if (!MultiNode(config)) {
1279 nodes.emplace_back(nullptr);
1280 } else {
1281 for (const Node *node : *config->nodes()) {
1282 if (!node->has_tags()) {
1283 continue;
1284 }
1285 bool did_found_tag = false;
1286 for (const flatbuffers::String *found_tag : *node->tags()) {
1287 if (found_tag->string_view() == tag) {
1288 did_found_tag = true;
1289 break;
1290 }
1291 }
1292 if (did_found_tag) {
1293 nodes.emplace_back(node);
1294 }
1295 }
1296 }
1297 return nodes;
1298}
1299
Brian Silverman631b6262021-11-10 12:25:08 -08001300bool NodeHasTag(const Node *node, std::string_view tag) {
1301 if (node == nullptr) {
1302 return true;
1303 }
1304
Austin Schuh97a52432022-08-17 15:02:59 -07001305 if (!node->has_tags()) {
1306 return false;
1307 }
1308
Brian Silverman631b6262021-11-10 12:25:08 -08001309 const auto *const tags = node->tags();
1310 return std::find_if(tags->begin(), tags->end(),
1311 [tag](const flatbuffers::String *candidate) {
1312 return candidate->string_view() == tag;
1313 }) != tags->end();
1314}
1315
Austin Schuhac0771c2020-01-07 18:36:30 -08001316bool MultiNode(const Configuration *config) { return config->has_nodes(); }
1317
Austin Schuh217a9782019-12-21 23:02:50 -08001318bool ChannelIsSendableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001319 if (node == nullptr) {
1320 return true;
1321 }
Austin Schuh3c5dae52020-10-06 18:55:18 -07001322 CHECK(channel->has_source_node()) << FlatbufferToJson(channel);
1323 CHECK(node->has_name()) << FlatbufferToJson(node);
Austin Schuh196a4452020-03-15 23:12:03 -07001324 return (CHECK_NOTNULL(channel)->source_node()->string_view() ==
1325 node->name()->string_view());
Austin Schuh217a9782019-12-21 23:02:50 -08001326}
1327
1328bool ChannelIsReadableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001329 if (node == nullptr) {
1330 return true;
1331 }
1332
Austin Schuh217a9782019-12-21 23:02:50 -08001333 if (channel->source_node()->string_view() == node->name()->string_view()) {
1334 return true;
1335 }
1336
1337 if (!channel->has_destination_nodes()) {
1338 return false;
1339 }
1340
Austin Schuh719946b2019-12-28 14:51:01 -08001341 for (const Connection *connection : *channel->destination_nodes()) {
1342 CHECK(connection->has_name());
1343 if (connection->name()->string_view() == node->name()->string_view()) {
Austin Schuh217a9782019-12-21 23:02:50 -08001344 return true;
1345 }
1346 }
1347
1348 return false;
1349}
1350
Austin Schuh719946b2019-12-28 14:51:01 -08001351bool ChannelMessageIsLoggedOnNode(const Channel *channel, const Node *node) {
Austin Schuh48e94502021-06-18 18:35:53 -07001352 if (node == nullptr) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001353 // Single node world. If there is a local logger, then we want to use
1354 // it.
Austin Schuh48e94502021-06-18 18:35:53 -07001355 if (channel->logger() == LoggerConfig::LOCAL_LOGGER) {
1356 return true;
1357 } else if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1358 return false;
1359 }
1360 LOG(FATAL) << "Unsupported logging configuration in a single node world: "
1361 << CleanedChannelToString(channel);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001362 }
1363 return ChannelMessageIsLoggedOnNode(
1364 channel, CHECK_NOTNULL(node)->name()->string_view());
1365}
1366
1367bool ChannelMessageIsLoggedOnNode(const Channel *channel,
1368 std::string_view node_name) {
Austin Schuhf1fff282020-03-28 16:57:32 -07001369 switch (channel->logger()) {
Austin Schuh719946b2019-12-28 14:51:01 -08001370 case LoggerConfig::LOCAL_LOGGER:
Austin Schuh2bb80e02021-03-20 21:46:17 -07001371 return channel->source_node()->string_view() == node_name;
Austin Schuh719946b2019-12-28 14:51:01 -08001372 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
James Kuszmaulf645c7d2023-02-23 14:21:04 -08001373 CHECK(channel->has_logger_nodes())
1374 << "Missing logger nodes on " << StrippedChannelToString(channel);
1375 CHECK_GT(channel->logger_nodes()->size(), 0u)
1376 << "Missing logger nodes on " << StrippedChannelToString(channel);
Austin Schuh719946b2019-12-28 14:51:01 -08001377
Austin Schuh2bb80e02021-03-20 21:46:17 -07001378 if (channel->source_node()->string_view() == node_name) {
Austin Schuh719946b2019-12-28 14:51:01 -08001379 return true;
1380 }
Austin Schuhda40e472020-03-28 15:15:29 -07001381
1382 [[fallthrough]];
1383 case LoggerConfig::REMOTE_LOGGER:
James Kuszmaulf645c7d2023-02-23 14:21:04 -08001384 CHECK(channel->has_logger_nodes())
1385 << "Missing logger nodes on " << StrippedChannelToString(channel);
1386 CHECK_GT(channel->logger_nodes()->size(), 0u)
1387 << "Missing logger nodes on " << StrippedChannelToString(channel);
Austin Schuhda40e472020-03-28 15:15:29 -07001388 for (const flatbuffers::String *logger_node : *channel->logger_nodes()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001389 if (logger_node->string_view() == node_name) {
Austin Schuhda40e472020-03-28 15:15:29 -07001390 return true;
1391 }
Austin Schuh719946b2019-12-28 14:51:01 -08001392 }
1393
1394 return false;
1395 case LoggerConfig::NOT_LOGGED:
1396 return false;
1397 }
1398
1399 LOG(FATAL) << "Unknown logger config " << static_cast<int>(channel->logger());
1400}
1401
Austin Schuh58646e22021-08-23 23:51:46 -07001402size_t ConnectionCount(const Channel *channel) {
1403 if (!channel->has_destination_nodes()) {
1404 return 0;
1405 }
1406 return channel->destination_nodes()->size();
1407}
1408
Austin Schuh719946b2019-12-28 14:51:01 -08001409const Connection *ConnectionToNode(const Channel *channel, const Node *node) {
1410 if (!channel->has_destination_nodes()) {
1411 return nullptr;
1412 }
1413 for (const Connection *connection : *channel->destination_nodes()) {
1414 if (connection->name()->string_view() == node->name()->string_view()) {
1415 return connection;
1416 }
1417 }
1418 return nullptr;
1419}
1420
1421bool ConnectionDeliveryTimeIsLoggedOnNode(const Channel *channel,
1422 const Node *node,
1423 const Node *logger_node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001424 return ConnectionDeliveryTimeIsLoggedOnNode(ConnectionToNode(channel, node),
1425 logger_node);
Austin Schuh719946b2019-12-28 14:51:01 -08001426}
1427
1428bool ConnectionDeliveryTimeIsLoggedOnNode(const Connection *connection,
1429 const Node *node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001430 if (connection == nullptr) {
1431 return false;
1432 }
Austin Schuh719946b2019-12-28 14:51:01 -08001433 switch (connection->timestamp_logger()) {
1434 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001435 CHECK(connection->has_timestamp_logger_nodes());
1436 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001437 if (connection->name()->string_view() == node->name()->string_view()) {
1438 return true;
1439 }
1440
Austin Schuhda40e472020-03-28 15:15:29 -07001441 [[fallthrough]];
1442 case LoggerConfig::REMOTE_LOGGER:
1443 CHECK(connection->has_timestamp_logger_nodes());
1444 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
1445 for (const flatbuffers::String *timestamp_logger_node :
1446 *connection->timestamp_logger_nodes()) {
1447 if (timestamp_logger_node->string_view() ==
1448 node->name()->string_view()) {
1449 return true;
1450 }
Austin Schuh719946b2019-12-28 14:51:01 -08001451 }
1452
1453 return false;
1454 case LoggerConfig::LOCAL_LOGGER:
1455 return connection->name()->string_view() == node->name()->string_view();
Austin Schuh719946b2019-12-28 14:51:01 -08001456 case LoggerConfig::NOT_LOGGED:
1457 return false;
1458 }
1459
1460 LOG(FATAL) << "Unknown logger config "
1461 << static_cast<int>(connection->timestamp_logger());
1462}
1463
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001464std::vector<std::string_view> SourceNodeNames(const Configuration *config,
1465 const Node *my_node) {
1466 std::set<std::string_view> result_set;
1467
1468 for (const Channel *channel : *config->channels()) {
1469 if (channel->has_destination_nodes()) {
1470 for (const Connection *connection : *channel->destination_nodes()) {
1471 if (connection->name()->string_view() ==
1472 my_node->name()->string_view()) {
1473 result_set.insert(channel->source_node()->string_view());
1474 }
1475 }
1476 }
1477 }
1478
1479 std::vector<std::string_view> result;
1480 for (const std::string_view source : result_set) {
1481 VLOG(1) << "Found a source node of " << source;
1482 result.emplace_back(source);
1483 }
1484 return result;
1485}
1486
1487std::vector<std::string_view> DestinationNodeNames(const Configuration *config,
1488 const Node *my_node) {
1489 std::vector<std::string_view> result;
1490
1491 for (const Channel *channel : *config->channels()) {
1492 if (channel->has_source_node() && channel->source_node()->string_view() ==
1493 my_node->name()->string_view()) {
1494 if (!channel->has_destination_nodes()) continue;
1495
1496 if (channel->source_node()->string_view() !=
1497 my_node->name()->string_view()) {
1498 continue;
1499 }
1500
1501 for (const Connection *connection : *channel->destination_nodes()) {
1502 if (std::find(result.begin(), result.end(),
1503 connection->name()->string_view()) == result.end()) {
1504 result.emplace_back(connection->name()->string_view());
1505 }
1506 }
1507 }
1508 }
1509
1510 for (const std::string_view destination : result) {
1511 VLOG(1) << "Found a destination node of " << destination;
1512 }
1513 return result;
1514}
1515
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001516std::vector<const Node *> TimestampNodes(const Configuration *config,
1517 const Node *my_node) {
1518 if (!configuration::MultiNode(config)) {
1519 CHECK(my_node == nullptr);
1520 return std::vector<const Node *>{};
1521 }
1522
1523 std::set<const Node *> timestamp_logger_nodes;
1524 for (const Channel *channel : *config->channels()) {
1525 if (!configuration::ChannelIsSendableOnNode(channel, my_node)) {
1526 continue;
1527 }
1528 if (!channel->has_destination_nodes()) {
1529 continue;
1530 }
1531 for (const Connection *connection : *channel->destination_nodes()) {
1532 const Node *other_node =
1533 configuration::GetNode(config, connection->name()->string_view());
1534
1535 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
1536 my_node)) {
1537 VLOG(1) << "Timestamps are logged from "
1538 << FlatbufferToJson(other_node);
1539 timestamp_logger_nodes.insert(other_node);
1540 }
1541 }
1542 }
1543
1544 std::vector<const Node *> result;
1545 for (const Node *node : timestamp_logger_nodes) {
1546 result.emplace_back(node);
1547 }
1548 return result;
1549}
1550
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001551bool ApplicationShouldStart(const Configuration *config, const Node *my_node,
1552 const Application *application) {
1553 if (MultiNode(config)) {
1554 // Ok, we need
1555 CHECK(application->has_nodes());
1556 CHECK(my_node != nullptr);
1557 for (const flatbuffers::String *str : *application->nodes()) {
1558 if (str->string_view() == my_node->name()->string_view()) {
1559 return true;
1560 }
1561 }
1562 return false;
1563 } else {
1564 return true;
1565 }
1566}
1567
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001568const Application *GetApplication(const Configuration *config,
1569 const Node *my_node,
1570 std::string_view application_name) {
1571 if (config->has_applications()) {
1572 auto application_iterator = std::lower_bound(
1573 config->applications()->cbegin(), config->applications()->cend(),
1574 application_name, CompareApplications);
1575 if (application_iterator != config->applications()->cend() &&
1576 EqualsApplications(*application_iterator, application_name)) {
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001577 if (ApplicationShouldStart(config, my_node, *application_iterator)) {
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001578 return *application_iterator;
1579 }
1580 }
1581 }
1582 return nullptr;
1583}
1584
Austin Schuhfc7b6a02021-07-12 21:19:07 -07001585std::vector<size_t> SourceNodeIndex(const Configuration *config) {
1586 CHECK(config->has_channels());
1587 std::vector<size_t> result;
1588 result.resize(config->channels()->size(), 0u);
1589 if (MultiNode(config)) {
1590 for (size_t i = 0; i < config->channels()->size(); ++i) {
1591 result[i] = GetNodeIndex(
1592 config, config->channels()->Get(i)->source_node()->string_view());
1593 }
1594 }
1595 return result;
1596}
1597
Austin Schuhfb37c612022-08-11 15:24:51 -07001598int QueueSize(const Configuration *config, const Channel *channel) {
1599 return QueueSize(channel->frequency(),
1600 chrono::nanoseconds(config->channel_storage_duration()));
1601}
1602
1603int QueueSize(size_t frequency, chrono::nanoseconds channel_storage_duration) {
1604 // Use integer arithmetic and round up at all cost.
1605 return static_cast<int>(
1606 (999999999 + static_cast<int64_t>(frequency) *
1607 static_cast<int64_t>(channel_storage_duration.count())) /
1608 static_cast<int64_t>(1000000000));
1609}
1610
1611int QueueScratchBufferSize(const Channel *channel) {
1612 return channel->num_readers() + channel->num_senders();
1613}
1614
Nathan Leong307c9692022-10-08 15:25:03 -07001615// Searches through configurations for schemas that include a certain type
1616const reflection::Schema *GetSchema(const Configuration *config,
1617 std::string_view schema_type) {
1618 if (config->has_channels()) {
1619 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
1620 for (const Channel *c : *config->channels()) {
1621 if (schema_type == c->type()->string_view()) {
1622 return c->schema();
1623 }
1624 }
1625 }
1626 return nullptr;
1627}
1628
1629// Copy schema reflection into detached flatbuffer
1630std::optional<FlatbufferDetachedBuffer<reflection::Schema>>
1631GetSchemaDetachedBuffer(const Configuration *config,
1632 std::string_view schema_type) {
1633 const reflection::Schema *found_schema = GetSchema(config, schema_type);
1634 if (found_schema == nullptr) {
1635 return std::nullopt;
1636 }
1637 return RecursiveCopyFlatBuffer(found_schema);
1638}
1639
James Kuszmaul741a4d02023-01-05 14:59:21 -08001640aos::FlatbufferDetachedBuffer<Configuration> AddChannelToConfiguration(
1641 const Configuration *config, std::string_view name,
1642 aos::FlatbufferVector<reflection::Schema> schema, const aos::Node *node,
1643 ChannelT overrides) {
1644 overrides.name = name;
James Kuszmaul80d6c422023-01-06 14:16:04 -08001645 CHECK(schema.message().has_root_table());
James Kuszmaul741a4d02023-01-05 14:59:21 -08001646 overrides.type = schema.message().root_table()->name()->string_view();
1647 if (node != nullptr) {
1648 CHECK(node->has_name());
1649 overrides.source_node = node->name()->string_view();
1650 }
1651 flatbuffers::FlatBufferBuilder fbb;
1652 // Don't populate fields from overrides that the user doesn't explicitly
1653 // override.
1654 fbb.ForceDefaults(false);
1655 const flatbuffers::Offset<Channel> channel_offset =
1656 Channel::Pack(fbb, &overrides);
1657 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1658 channels_offset = fbb.CreateVector({channel_offset});
1659 Configuration::Builder config_builder(fbb);
1660 config_builder.add_channels(channels_offset);
1661 fbb.Finish(config_builder.Finish());
1662 FlatbufferDetachedBuffer<Configuration> new_channel_config = fbb.Release();
1663 new_channel_config = MergeConfiguration(new_channel_config, {schema});
1664 return MergeWithConfig(config, new_channel_config);
1665}
1666
Brian Silverman66f079a2013-08-26 16:24:30 -07001667} // namespace configuration
1668} // namespace aos