blob: db00ce77df1571ebe19b0b80bab42f41ee078527 [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 {
32bool EndsWith(std::string_view str, std::string_view end) {
33 if (str.size() < end.size()) {
34 return false;
35 }
36 if (str.substr(str.size() - end.size(), end.size()) != end) {
37 return false;
38 }
39 return true;
40}
41
42std::string MaybeReplaceExtension(std::string_view filename,
43 std::string_view extension,
44 std::string_view replacement) {
45 if (!EndsWith(filename, extension)) {
46 return std::string(filename);
47 }
48 filename.remove_suffix(extension.size());
49 return absl::StrCat(filename, replacement);
50}
51
52FlatbufferDetachedBuffer<Configuration> ReadConfigFile(std::string_view path,
53 bool binary) {
54 if (binary) {
55 FlatbufferVector<Configuration> config =
56 FileToFlatbuffer<Configuration>(path);
57 return CopySpanAsDetachedBuffer(config.span());
58 }
59
60 flatbuffers::DetachedBuffer buffer = JsonToFlatbuffer(
61 util::ReadFileToStringOrDie(path), ConfigurationTypeTable());
62
Austin Schuh84a039a2021-11-03 16:50:34 -070063 CHECK_GT(buffer.size(), 0u) << ": Failed to parse JSON file: " << path;
Austin Schuh15182322020-10-10 15:25:21 -070064
65 return FlatbufferDetachedBuffer<Configuration>(std::move(buffer));
66}
67
68} // namespace
Austin Schuhcb108412019-10-13 16:09:54 -070069
Austin Schuh40485ed2019-10-26 21:51:44 -070070// Define the compare and equal operators for Channel and Application so we can
Austin Schuhcb108412019-10-13 16:09:54 -070071// insert them in the btree below.
Austin Schuh40485ed2019-10-26 21:51:44 -070072bool operator<(const FlatbufferDetachedBuffer<Channel> &lhs,
73 const FlatbufferDetachedBuffer<Channel> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -070074 int name_compare = lhs.message().name()->string_view().compare(
75 rhs.message().name()->string_view());
76 if (name_compare == 0) {
77 return lhs.message().type()->string_view() <
78 rhs.message().type()->string_view();
79 } else if (name_compare < 0) {
80 return true;
81 } else {
82 return false;
83 }
84}
85
Austin Schuh40485ed2019-10-26 21:51:44 -070086bool operator==(const FlatbufferDetachedBuffer<Channel> &lhs,
87 const FlatbufferDetachedBuffer<Channel> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -070088 return lhs.message().name()->string_view() ==
89 rhs.message().name()->string_view() &&
90 lhs.message().type()->string_view() ==
91 rhs.message().type()->string_view();
92}
93
Austin Schuha7996eb2021-10-11 19:03:24 -070094bool operator<(const FlatbufferDetachedBuffer<Connection> &lhs,
95 const FlatbufferDetachedBuffer<Connection> &rhs) {
96 return lhs.message().name()->string_view() <
97 rhs.message().name()->string_view();
98}
99
100bool operator==(const FlatbufferDetachedBuffer<Connection> &lhs,
101 const FlatbufferDetachedBuffer<Connection> &rhs) {
102 return lhs.message().name()->string_view() ==
103 rhs.message().name()->string_view();
104}
105
Austin Schuh40485ed2019-10-26 21:51:44 -0700106bool operator==(const FlatbufferDetachedBuffer<Application> &lhs,
107 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -0700108 return lhs.message().name()->string_view() ==
109 rhs.message().name()->string_view();
110}
111
Austin Schuh40485ed2019-10-26 21:51:44 -0700112bool operator<(const FlatbufferDetachedBuffer<Application> &lhs,
113 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -0700114 return lhs.message().name()->string_view() <
115 rhs.message().name()->string_view();
116}
117
Austin Schuh217a9782019-12-21 23:02:50 -0800118bool operator==(const FlatbufferDetachedBuffer<Node> &lhs,
119 const FlatbufferDetachedBuffer<Node> &rhs) {
120 return lhs.message().name()->string_view() ==
121 rhs.message().name()->string_view();
122}
123
124bool operator<(const FlatbufferDetachedBuffer<Node> &lhs,
125 const FlatbufferDetachedBuffer<Node> &rhs) {
126 return lhs.message().name()->string_view() <
127 rhs.message().name()->string_view();
128}
129
Brian Silverman66f079a2013-08-26 16:24:30 -0700130namespace configuration {
131namespace {
132
Austin Schuhcb108412019-10-13 16:09:54 -0700133// Extracts the folder part of a path. Returns ./ if there is no path.
Austin Schuhf1fff282020-03-28 16:57:32 -0700134std::string_view ExtractFolder(const std::string_view filename) {
Austin Schuhcb108412019-10-13 16:09:54 -0700135 auto last_slash_pos = filename.find_last_of("/\\");
136
James Kuszmaul3ae42262019-11-08 12:33:41 -0800137 return last_slash_pos == std::string_view::npos
138 ? std::string_view("./")
Austin Schuhcb108412019-10-13 16:09:54 -0700139 : filename.substr(0, last_slash_pos + 1);
140}
141
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700142std::string AbsolutePath(const std::string_view filename) {
143 // Uses an std::string so that we know the input will be null-terminated.
144 const std::string terminated_file(filename);
145 char buffer[PATH_MAX];
146 PCHECK(NULL != realpath(terminated_file.c_str(), buffer));
147 return buffer;
148}
149
Austin Schuhef38cd22021-07-21 15:24:23 -0700150std::string RemoveDotDots(const std::string_view filename) {
151 std::vector<std::string> split = absl::StrSplit(filename, '/');
152 auto iterator = split.begin();
153 while (iterator != split.end()) {
154 if (iterator->empty()) {
155 iterator = split.erase(iterator);
156 } else if (*iterator == ".") {
157 iterator = split.erase(iterator);
158 } else if (*iterator == "..") {
159 CHECK(iterator != split.begin())
160 << ": Import path may not start with ..: " << filename;
161 auto previous = iterator;
162 --previous;
163 split.erase(iterator);
164 iterator = split.erase(previous);
165 } else {
166 ++iterator;
167 }
168 }
169 return absl::StrJoin(split, "/");
170}
171
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700172std::optional<FlatbufferDetachedBuffer<Configuration>> MaybeReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700173 const std::string_view path, absl::btree_set<std::string> *visited_paths,
174 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuh15182322020-10-10 15:25:21 -0700175 std::string binary_path = MaybeReplaceExtension(path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700176 VLOG(1) << "Looking up: " << path << ", starting with: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700177 bool binary_path_exists = util::PathExists(binary_path);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700178 std::string raw_path(path);
Austin Schuh15182322020-10-10 15:25:21 -0700179 // For each .json file, look and see if we can find a .bfbs file next to it
180 // with the same base name. If we can, assume it is the same and use it
181 // instead. It is much faster to load .bfbs files than .json files.
182 if (!binary_path_exists && !util::PathExists(raw_path)) {
183 const bool path_is_absolute = raw_path.size() > 0 && raw_path[0] == '/';
Brian Silvermand0588192022-07-26 00:35:22 -0700184 if (path_is_absolute) {
185 // Nowhere else to look up an absolute path, so fail now. Note that we
186 // always have at least one extra import path based on /proc/self/exe, so
187 // warning about those paths existing isn't helpful.
188 LOG(ERROR) << ": Failed to find file " << path << ".";
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700189 return std::nullopt;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700190 }
191
192 bool found_path = false;
193 for (const auto &import_path : extra_import_paths) {
Austin Schuhef38cd22021-07-21 15:24:23 -0700194 raw_path = std::string(import_path) + "/" + RemoveDotDots(path);
Austin Schuh15182322020-10-10 15:25:21 -0700195 binary_path = MaybeReplaceExtension(raw_path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700196 VLOG(1) << "Checking: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700197 binary_path_exists = util::PathExists(binary_path);
198 if (binary_path_exists) {
199 found_path = true;
200 break;
201 }
Austin Schuhef38cd22021-07-21 15:24:23 -0700202 VLOG(1) << "Checking: " << raw_path;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700203 if (util::PathExists(raw_path)) {
204 found_path = true;
205 break;
206 }
207 }
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700208 if (!found_path) {
209 LOG(ERROR) << ": Failed to find file " << path << ".";
210 return std::nullopt;
211 }
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700212 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700214 std::optional<FlatbufferDetachedBuffer<Configuration>> config =
215 ReadConfigFile(binary_path_exists ? binary_path : raw_path,
216 binary_path_exists);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700217
Austin Schuhcb108412019-10-13 16:09:54 -0700218 // Depth first. Take the following example:
219 //
220 // config1.json:
221 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700222 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700223 // {
224 // "name": "/foo",
225 // "type": ".aos.bar",
226 // "max_size": 5
227 // }
228 // ],
229 // "imports": [
230 // "config2.json",
231 // ]
232 // }
233 //
234 // config2.json:
235 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700236 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700237 // {
238 // "name": "/foo",
239 // "type": ".aos.bar",
240 // "max_size": 7
241 // }
242 // ],
243 // }
244 //
245 // We want the main config (config1.json) to be able to override the imported
246 // config. That means that it needs to be merged into the imported configs,
247 // not the other way around.
248
Austin Schuh15182322020-10-10 15:25:21 -0700249 const std::string absolute_path =
250 AbsolutePath(binary_path_exists ? binary_path : raw_path);
251 // Track that we have seen this file before recursing. Track the path we
252 // actually loaded (which should be consistent if imported twice).
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700253 if (!visited_paths->insert(absolute_path).second) {
254 for (const auto &visited_path : *visited_paths) {
255 LOG(INFO) << "Already visited: " << visited_path;
256 }
257 LOG(FATAL)
258 << "Already imported " << path << " (i.e. " << absolute_path
259 << "). See above for the files that have already been processed.";
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700260 return std::nullopt;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700261 }
Austin Schuhcb108412019-10-13 16:09:54 -0700262
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700263 if (config->message().has_imports()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700264 // Capture the imports.
265 const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *v =
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700266 config->message().imports();
Austin Schuhcb108412019-10-13 16:09:54 -0700267
268 // And then wipe them. This gets GCed when we merge later.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700269 config->mutable_message()->clear_imports();
Austin Schuhcb108412019-10-13 16:09:54 -0700270
271 // Start with an empty configuration to merge into.
Austin Schuh40485ed2019-10-26 21:51:44 -0700272 FlatbufferDetachedBuffer<Configuration> merged_config =
273 FlatbufferDetachedBuffer<Configuration>::Empty();
Austin Schuhcb108412019-10-13 16:09:54 -0700274
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700275 const std::string path_folder(ExtractFolder(path));
Austin Schuhcb108412019-10-13 16:09:54 -0700276 for (const flatbuffers::String *str : *v) {
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700277 const std::string included_config =
278 path_folder + "/" + std::string(str->string_view());
Austin Schuhcb108412019-10-13 16:09:54 -0700279
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700280 const auto optional_config =
281 MaybeReadConfig(included_config, visited_paths, extra_import_paths);
282 if (!optional_config.has_value()) {
283 return std::nullopt;
284 }
Austin Schuhcb108412019-10-13 16:09:54 -0700285 // And them merge everything in.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700286 merged_config = MergeFlatBuffers(merged_config, *optional_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700287 }
288
289 // Finally, merge this file in.
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700290 config = MergeFlatBuffers(merged_config, *config);
Austin Schuhcb108412019-10-13 16:09:54 -0700291 }
292 return config;
293}
294
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295// Compares (c < p) a channel, and a name, type tuple.
296bool CompareChannels(const Channel *c,
James Kuszmaul3ae42262019-11-08 12:33:41 -0800297 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298 int name_compare = c->name()->string_view().compare(p.first);
299 if (name_compare == 0) {
300 return c->type()->string_view() < p.second;
301 } else if (name_compare < 0) {
302 return true;
303 } else {
304 return false;
305 }
306};
307
308// Compares for equality (c == p) a channel, and a name, type tuple.
309bool EqualsChannels(const Channel *c,
Austin Schuhf1fff282020-03-28 16:57:32 -0700310 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311 return c->name()->string_view() == p.first &&
312 c->type()->string_view() == p.second;
313}
314
315// Compares (c < p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800316bool CompareApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700317 return a->name()->string_view() < name;
318};
319
320// Compares for equality (c == p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800321bool EqualsApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322 return a->name()->string_view() == name;
323}
324
Austin Schuh15182322020-10-10 15:25:21 -0700325void ValidateConfiguration(const Flatbuffer<Configuration> &config) {
326 // No imports should be left.
327 CHECK(!config.message().has_imports());
328
329 // Check that if there is a node list, all the source nodes are filled out and
330 // valid, and all the destination nodes are valid (and not the source). This
331 // is a basic consistency check.
332 if (config.message().has_channels()) {
333 const Channel *last_channel = nullptr;
334 for (const Channel *c : *config.message().channels()) {
335 CHECK(c->has_name());
336 CHECK(c->has_type());
337 if (c->name()->string_view().back() == '/') {
338 LOG(FATAL) << "Channel names can't end with '/'";
339 }
340 if (c->name()->string_view().find("//") != std::string_view::npos) {
341 LOG(FATAL) << ": Invalid channel name " << c->name()->string_view()
342 << ", can't use //.";
343 }
344 for (const char data : c->name()->string_view()) {
345 if (data >= '0' && data <= '9') {
346 continue;
347 }
348 if (data >= 'a' && data <= 'z') {
349 continue;
350 }
351 if (data >= 'A' && data <= 'Z') {
352 continue;
353 }
354 if (data == '-' || data == '_' || data == '/') {
355 continue;
356 }
357 LOG(FATAL) << "Invalid channel name " << c->name()->string_view()
358 << ", can only use [-a-zA-Z0-9_/]";
359 }
360
Austin Schuha156fb22021-10-11 19:23:21 -0700361 if (c->has_logger_nodes()) {
362 // Confirm that we don't have duplicate logger nodes.
363 absl::btree_set<std::string_view> logger_nodes;
364 for (const flatbuffers::String *s : *c->logger_nodes()) {
365 logger_nodes.insert(s->string_view());
366 }
367 CHECK_EQ(static_cast<size_t>(logger_nodes.size()),
368 c->logger_nodes()->size())
369 << ": Found duplicate logger_nodes in "
370 << CleanedChannelToString(c);
371 }
372
373 if (c->has_destination_nodes()) {
374 // Confirm that we don't have duplicate timestamp logger nodes.
Austin Schuh5e95bd62021-10-11 18:40:22 -0700375 for (const Connection *d : *c->destination_nodes()) {
Austin Schuha156fb22021-10-11 19:23:21 -0700376 if (d->has_timestamp_logger_nodes()) {
377 absl::btree_set<std::string_view> timestamp_logger_nodes;
378 for (const flatbuffers::String *s : *d->timestamp_logger_nodes()) {
379 timestamp_logger_nodes.insert(s->string_view());
380 }
381 CHECK_EQ(static_cast<size_t>(timestamp_logger_nodes.size()),
382 d->timestamp_logger_nodes()->size())
383 << ": Found duplicate timestamp_logger_nodes in "
384 << CleanedChannelToString(c);
385 }
386 }
387
388 // There is no good use case today for logging timestamps but not the
389 // corresponding data. Instead of plumbing through all of this on the
390 // reader side, let'd just disallow it for now.
391 if (c->logger() == LoggerConfig::NOT_LOGGED) {
392 for (const Connection *d : *c->destination_nodes()) {
393 CHECK(d->timestamp_logger() == LoggerConfig::NOT_LOGGED)
394 << ": Logging timestamps without data is not supported. If "
395 "you have a good use case, let's talk. "
396 << CleanedChannelToString(c);
397 }
Austin Schuh5e95bd62021-10-11 18:40:22 -0700398 }
399 }
400
Austin Schuh15182322020-10-10 15:25:21 -0700401 // Make sure everything is sorted while we are here... If this fails,
402 // there will be a bunch of weird errors.
403 if (last_channel != nullptr) {
404 CHECK(CompareChannels(
405 last_channel,
406 std::make_pair(c->name()->string_view(), c->type()->string_view())))
407 << ": Channels not sorted!";
408 }
409 last_channel = c;
410 }
411 }
412
413 if (config.message().has_nodes() && config.message().has_channels()) {
414 for (const Channel *c : *config.message().channels()) {
415 CHECK(c->has_source_node()) << ": Channel " << FlatbufferToJson(c)
416 << " is missing \"source_node\"";
417 CHECK(GetNode(&config.message(), c->source_node()->string_view()) !=
418 nullptr)
419 << ": Channel " << FlatbufferToJson(c)
420 << " has an unknown \"source_node\"";
421
422 if (c->has_destination_nodes()) {
423 for (const Connection *connection : *c->destination_nodes()) {
424 CHECK(connection->has_name());
425 CHECK(GetNode(&config.message(), connection->name()->string_view()) !=
426 nullptr)
427 << ": Channel " << FlatbufferToJson(c)
428 << " has an unknown \"destination_nodes\" "
429 << connection->name()->string_view();
430
431 switch (connection->timestamp_logger()) {
432 case LoggerConfig::LOCAL_LOGGER:
433 case LoggerConfig::NOT_LOGGED:
434 CHECK(!connection->has_timestamp_logger_nodes());
435 break;
436 case LoggerConfig::REMOTE_LOGGER:
437 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
438 CHECK(connection->has_timestamp_logger_nodes());
439 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
440 for (const flatbuffers::String *timestamp_logger_node :
441 *connection->timestamp_logger_nodes()) {
442 CHECK(GetNode(&config.message(),
443 timestamp_logger_node->string_view()) != nullptr)
444 << ": Channel " << FlatbufferToJson(c)
445 << " has an unknown \"timestamp_logger_node\""
446 << connection->name()->string_view();
447 }
448 break;
449 }
450
451 CHECK_NE(connection->name()->string_view(),
452 c->source_node()->string_view())
453 << ": Channel " << FlatbufferToJson(c)
454 << " is forwarding data to itself";
455 }
456 }
457 }
458 }
459}
460
James Kuszmaulc8503f32022-06-25 16:17:12 -0700461void HandleReverseMaps(
462 const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
463 std::string_view type, const Node *node, std::set<std::string> *names) {
464 for (const Map *map : *maps) {
465 CHECK_NOTNULL(map);
466 const Channel *const match = CHECK_NOTNULL(map->match());
467 const Channel *const rename = CHECK_NOTNULL(map->rename());
468
469 // Handle type specific maps.
470 const flatbuffers::String *const match_type_string = match->type();
471 if (match_type_string != nullptr &&
472 match_type_string->string_view() != type) {
473 continue;
474 }
475
476 // Now handle node specific maps.
477 const flatbuffers::String *const match_source_node_string =
478 match->source_node();
479 if (node != nullptr && match_source_node_string != nullptr &&
480 match_source_node_string->string_view() !=
481 node->name()->string_view()) {
482 continue;
483 }
484
485 const flatbuffers::String *const match_name_string = match->name();
486 const flatbuffers::String *const rename_name_string = rename->name();
487 if (match_name_string == nullptr || rename_name_string == nullptr) {
488 continue;
489 }
490
491 const std::string rename_name = rename_name_string->str();
492 const std::string_view match_name = match_name_string->string_view();
493
494 std::set<std::string> possible_renames;
495
496 // Check if the current name(s) could have been reached using the provided
497 // rename.
498 if (match_name.back() == '*') {
499 for (const std::string &option : *names) {
500 if (option.substr(0, rename_name.size()) == rename_name) {
501 possible_renames.insert(
502 absl::StrCat(match_name.substr(0, match_name.size() - 1),
503 option.substr(rename_name.size())));
504 }
505 }
506 names->insert(possible_renames.begin(), possible_renames.end());
507 } else if (names->count(rename_name) != 0) {
508 names->insert(std::string(match_name));
509 }
510 }
511}
512
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513} // namespace
514
Austin Schuh006a9f52021-04-07 16:24:18 -0700515// Maps name for the provided maps. Modifies name.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800516//
517// This is called many times during startup, and it dereferences a lot of
518// pointers. These combine to make it a performance hotspot during many tests
519// under msan, so there is some optimizing around caching intermediates instead
520// of dereferencing the pointer multiple times.
James Kuszmaulc8503f32022-06-25 16:17:12 -0700521//
522// Deliberately not in an anonymous namespace so that the log-reading code can
523// reference it.
Austin Schuh006a9f52021-04-07 16:24:18 -0700524void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
525 std::string *name, std::string_view type, const Node *node) {
526 // For the same reason we merge configs in reverse order, we want to process
527 // maps in reverse order. That lets the outer config overwrite channels from
528 // the inner configs.
529 for (auto i = maps->rbegin(); i != maps->rend(); ++i) {
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800530 const Channel *const match = i->match();
531 if (!match) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700532 continue;
533 }
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800534 const flatbuffers::String *const match_name_string = match->name();
535 if (!match_name_string) {
536 continue;
537 }
538 const Channel *const rename = i->rename();
539 if (!rename) {
540 continue;
541 }
542 const flatbuffers::String *const rename_name_string = rename->name();
543 if (!rename_name_string) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700544 continue;
545 }
546
547 // Handle normal maps (now that we know that match and rename are filled
548 // out).
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800549 const std::string_view match_name = match_name_string->string_view();
Austin Schuh006a9f52021-04-07 16:24:18 -0700550 if (match_name != *name) {
551 if (match_name.back() == '*' &&
552 std::string_view(*name).substr(
553 0, std::min(name->size(), match_name.size() - 1)) ==
554 match_name.substr(0, match_name.size() - 1)) {
555 CHECK_EQ(match_name.find('*'), match_name.size() - 1);
556 } else {
557 continue;
558 }
559 }
560
561 // Handle type specific maps.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800562 const flatbuffers::String *const match_type_string = match->type();
563 if (match_type_string && match_type_string->string_view() != type) {
Austin Schuh006a9f52021-04-07 16:24:18 -0700564 continue;
565 }
566
567 // Now handle node specific maps.
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800568 const flatbuffers::String *const match_source_node_string =
569 match->source_node();
570 if (node && match_source_node_string &&
571 match_source_node_string->string_view() !=
Austin Schuh006a9f52021-04-07 16:24:18 -0700572 node->name()->string_view()) {
573 continue;
574 }
575
Brian Silvermanf3798cb2021-11-10 12:26:34 -0800576 std::string new_name(rename_name_string->string_view());
Austin Schuh006a9f52021-04-07 16:24:18 -0700577 if (match_name.back() == '*') {
578 new_name += std::string(name->substr(match_name.size() - 1));
579 }
580 VLOG(1) << "Renamed \"" << *name << "\" to \"" << new_name << "\"";
581 *name = std::move(new_name);
582 }
583}
584
James Kuszmaulc8503f32022-06-25 16:17:12 -0700585std::set<std::string> GetChannelAliases(const Configuration *config,
586 std::string_view name,
587 std::string_view type,
588 const std::string_view application_name,
589 const Node *node) {
590 std::set<std::string> names{std::string(name)};
591 if (config->has_maps()) {
592 HandleReverseMaps(config->maps(), type, node, &names);
593 }
594 {
595 const Application *application =
596 GetApplication(config, node, application_name);
597 if (application != nullptr && application->has_maps()) {
598 HandleReverseMaps(application->maps(), type, node, &names);
599 }
600 }
601 return names;
602}
603
Austin Schuh40485ed2019-10-26 21:51:44 -0700604FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
Austin Schuhcb108412019-10-13 16:09:54 -0700605 const Flatbuffer<Configuration> &config) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700606 // auto_merge_config will contain all the fields of the Configuration that are
607 // to be passed through unmodified to the result of MergeConfiguration().
608 // In the processing below, we mutate auto_merge_config to remove any fields
609 // which we do need to alter (hence why we can't use the input config
610 // directly), and then merge auto_merge_config back in at the end.
611 aos::FlatbufferDetachedBuffer<aos::Configuration> auto_merge_config =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800612 aos::RecursiveCopyFlatBuffer(&config.message());
James Kuszmaul3c998592020-07-27 21:04:47 -0700613
Austin Schuh40485ed2019-10-26 21:51:44 -0700614 // Store all the channels in a sorted set. This lets us track channels we
Austin Schuhcb108412019-10-13 16:09:54 -0700615 // have seen before and merge the updates in.
Austin Schuh40485ed2019-10-26 21:51:44 -0700616 absl::btree_set<FlatbufferDetachedBuffer<Channel>> channels;
Austin Schuhcb108412019-10-13 16:09:54 -0700617
Austin Schuh40485ed2019-10-26 21:51:44 -0700618 if (config.message().has_channels()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700619 auto_merge_config.mutable_message()->clear_channels();
Austin Schuh40485ed2019-10-26 21:51:44 -0700620 for (const Channel *c : *config.message().channels()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700621 // Ignore malformed entries.
Austin Schuh40485ed2019-10-26 21:51:44 -0700622 if (!c->has_name()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700623 continue;
624 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700625 if (!c->has_type()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700626 continue;
627 }
628
Brian Silverman77162972020-08-12 19:52:40 -0700629 CHECK_EQ(c->read_method() == ReadMethod::PIN, c->num_readers() != 0)
630 << ": num_readers may be set if and only if read_method is PIN,"
631 " if you want 0 readers do not set PIN: "
632 << CleanedChannelToString(c);
633
Austin Schuh40485ed2019-10-26 21:51:44 -0700634 // Attempt to insert the channel.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800635 auto result = channels.insert(RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700636 if (!result.second) {
637 // Already there, so merge the new table into the original.
Austin Schuh4a5f5d22021-10-12 15:09:35 -0700638 // Schemas merge poorly, so pick the newest one.
639 if (result.first->message().has_schema() && c->has_schema()) {
640 result.first->mutable_message()->clear_schema();
641 }
Austin Schuha7996eb2021-10-11 19:03:24 -0700642 auto merged =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800643 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(c));
Austin Schuha7996eb2021-10-11 19:03:24 -0700644
645 if (merged.message().has_destination_nodes()) {
646 absl::btree_set<FlatbufferDetachedBuffer<Connection>> connections;
647 for (const Connection *connection :
648 *merged.message().destination_nodes()) {
649 auto connection_result =
650 connections.insert(RecursiveCopyFlatBuffer(connection));
651 if (!connection_result.second) {
652 *connection_result.first =
653 MergeFlatBuffers(*connection_result.first,
654 RecursiveCopyFlatBuffer(connection));
655 }
656 }
657 if (static_cast<size_t>(connections.size()) !=
658 merged.message().destination_nodes()->size()) {
659 merged.mutable_message()->clear_destination_nodes();
660 flatbuffers::FlatBufferBuilder fbb;
661 fbb.ForceDefaults(true);
662 std::vector<flatbuffers::Offset<Connection>> connection_offsets;
663 for (const FlatbufferDetachedBuffer<Connection> &connection :
664 connections) {
665 connection_offsets.push_back(
666 RecursiveCopyFlatBuffer(&connection.message(), &fbb));
667 }
668 flatbuffers::Offset<
669 flatbuffers::Vector<flatbuffers::Offset<Connection>>>
670 destination_nodes_offset = fbb.CreateVector(connection_offsets);
671 Channel::Builder channel_builder(fbb);
672 channel_builder.add_destination_nodes(destination_nodes_offset);
673 fbb.Finish(channel_builder.Finish());
674 FlatbufferDetachedBuffer<Channel> destinations_channel(
675 fbb.Release());
676 merged = MergeFlatBuffers(merged, destinations_channel);
677 }
678 }
679
680 *result.first = std::move(merged);
Austin Schuhcb108412019-10-13 16:09:54 -0700681 }
682 }
683 }
684
685 // Now repeat this for the application list.
Austin Schuh40485ed2019-10-26 21:51:44 -0700686 absl::btree_set<FlatbufferDetachedBuffer<Application>> applications;
Austin Schuhcb108412019-10-13 16:09:54 -0700687 if (config.message().has_applications()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700688 auto_merge_config.mutable_message()->clear_applications();
Austin Schuhcb108412019-10-13 16:09:54 -0700689 for (const Application *a : *config.message().applications()) {
690 if (!a->has_name()) {
691 continue;
692 }
693
Austin Schuha4fc60f2020-11-01 23:06:47 -0800694 auto result = applications.insert(RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700695 if (!result.second) {
Austin Schuhf81c2522021-12-08 12:03:30 -0800696 if (a->has_args()) {
697 result.first->mutable_message()->clear_args();
698 }
Austin Schuha4fc60f2020-11-01 23:06:47 -0800699 *result.first =
700 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700701 }
702 }
703 }
704
Austin Schuh217a9782019-12-21 23:02:50 -0800705 // Now repeat this for the node list.
706 absl::btree_set<FlatbufferDetachedBuffer<Node>> nodes;
707 if (config.message().has_nodes()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700708 auto_merge_config.mutable_message()->clear_nodes();
Austin Schuh217a9782019-12-21 23:02:50 -0800709 for (const Node *n : *config.message().nodes()) {
710 if (!n->has_name()) {
711 continue;
712 }
713
Austin Schuha4fc60f2020-11-01 23:06:47 -0800714 auto result = nodes.insert(RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800715 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800716 *result.first =
717 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800718 }
719 }
720 }
721
Austin Schuhcb108412019-10-13 16:09:54 -0700722 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800723 fbb.ForceDefaults(true);
Austin Schuhcb108412019-10-13 16:09:54 -0700724
725 // Start by building the vectors. They need to come before the final table.
Austin Schuh40485ed2019-10-26 21:51:44 -0700726 // Channels
727 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
728 channels_offset;
Austin Schuhcb108412019-10-13 16:09:54 -0700729 {
Austin Schuh40485ed2019-10-26 21:51:44 -0700730 ::std::vector<flatbuffers::Offset<Channel>> channel_offsets;
731 for (const FlatbufferDetachedBuffer<Channel> &c : channels) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800732 channel_offsets.emplace_back(
733 RecursiveCopyFlatBuffer<Channel>(&c.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700734 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700735 channels_offset = fbb.CreateVector(channel_offsets);
Austin Schuhcb108412019-10-13 16:09:54 -0700736 }
737
738 // Applications
739 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
740 applications_offset;
741 {
742 ::std::vector<flatbuffers::Offset<Application>> applications_offsets;
Austin Schuh40485ed2019-10-26 21:51:44 -0700743 for (const FlatbufferDetachedBuffer<Application> &a : applications) {
Austin Schuhcb108412019-10-13 16:09:54 -0700744 applications_offsets.emplace_back(
Austin Schuha4fc60f2020-11-01 23:06:47 -0800745 RecursiveCopyFlatBuffer<Application>(&a.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700746 }
747 applications_offset = fbb.CreateVector(applications_offsets);
748 }
749
Austin Schuh217a9782019-12-21 23:02:50 -0800750 // Nodes
751 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
752 nodes_offset;
753 {
754 ::std::vector<flatbuffers::Offset<Node>> node_offsets;
755 for (const FlatbufferDetachedBuffer<Node> &n : nodes) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800756 node_offsets.emplace_back(
757 RecursiveCopyFlatBuffer<Node>(&n.message(), &fbb));
Austin Schuh217a9782019-12-21 23:02:50 -0800758 }
759 nodes_offset = fbb.CreateVector(node_offsets);
760 }
761
Austin Schuhcb108412019-10-13 16:09:54 -0700762 // And then build a Configuration with them all.
763 ConfigurationBuilder configuration_builder(fbb);
Austin Schuh40485ed2019-10-26 21:51:44 -0700764 configuration_builder.add_channels(channels_offset);
Austin Schuh217a9782019-12-21 23:02:50 -0800765 if (config.message().has_applications()) {
766 configuration_builder.add_applications(applications_offset);
767 }
768 if (config.message().has_nodes()) {
769 configuration_builder.add_nodes(nodes_offset);
770 }
Austin Schuhcb108412019-10-13 16:09:54 -0700771
772 fbb.Finish(configuration_builder.Finish());
Austin Schuh217a9782019-12-21 23:02:50 -0800773
James Kuszmaul3c998592020-07-27 21:04:47 -0700774 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
775 fbb.Release());
776
Austin Schuh217a9782019-12-21 23:02:50 -0800777 // Now, validate that if there is a node list, every channel has a source
778 // node.
James Kuszmaul3c998592020-07-27 21:04:47 -0700779 FlatbufferDetachedBuffer<Configuration> result =
780 MergeFlatBuffers(modified_config, auto_merge_config);
Austin Schuh217a9782019-12-21 23:02:50 -0800781
Austin Schuh15182322020-10-10 15:25:21 -0700782 ValidateConfiguration(result);
Austin Schuh217a9782019-12-21 23:02:50 -0800783
784 return result;
Austin Schuhcb108412019-10-13 16:09:54 -0700785}
786
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700787std::optional<FlatbufferDetachedBuffer<Configuration>> MaybeReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700788 const std::string_view path,
Austin Schuhef38cd22021-07-21 15:24:23 -0700789 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuh89026f52022-02-25 14:24:04 -0800790 // Add the executable directory to the search path. That makes it so that
791 // tools can be run from any directory without hard-coding an absolute path to
792 // the config into all binaries.
793 std::vector<std::string_view> extra_import_paths_with_exe =
794 extra_import_paths;
795 char proc_self_exec_buffer[PATH_MAX + 1];
796 std::memset(proc_self_exec_buffer, 0, sizeof(proc_self_exec_buffer));
797 ssize_t s = readlink("/proc/self/exe", proc_self_exec_buffer, PATH_MAX);
798 if (s > 0) {
799 // If the readlink call fails, the worst thing that happens is that we don't
800 // automatically find the config next to the binary. VLOG to make it easier
801 // to debug.
802 std::string_view proc_self_exec(proc_self_exec_buffer);
803
804 extra_import_paths_with_exe.emplace_back(
805 proc_self_exec.substr(0, proc_self_exec.rfind("/")));
806 } else {
807 VLOG(1) << "Failed to read /proc/self/exe";
808 }
809
Austin Schuhcb108412019-10-13 16:09:54 -0700810 // We only want to read a file once. So track the visited files in a set.
811 absl::btree_set<std::string> visited_paths;
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700812 std::optional<FlatbufferDetachedBuffer<Configuration>> read_config =
813 MaybeReadConfig(path, &visited_paths, extra_import_paths_with_exe);
814
815 if (read_config == std::nullopt) {
816 return read_config;
817 }
Austin Schuh15182322020-10-10 15:25:21 -0700818
819 // If we only read one file, and it had a .bfbs extension, it has to be a
820 // fully formatted config. Do a quick verification and return it.
821 if (visited_paths.size() == 1 && EndsWith(*visited_paths.begin(), ".bfbs")) {
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700822 ValidateConfiguration(*read_config);
Austin Schuh15182322020-10-10 15:25:21 -0700823 return read_config;
824 }
825
Milind Upadhyay17098ba2022-04-15 22:18:50 -0700826 return MergeConfiguration(*read_config);
827}
828
829FlatbufferDetachedBuffer<Configuration> ReadConfig(
830 const std::string_view path,
831 const std::vector<std::string_view> &extra_import_paths) {
832 auto optional_config = MaybeReadConfig(path, extra_import_paths);
833 CHECK(optional_config) << "Could not read config. See above errors";
834 return std::move(*optional_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700835}
836
Austin Schuh8d6cea82020-02-28 12:17:16 -0800837FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Brian Silverman24f5aa82020-06-23 16:21:28 -0700838 const Configuration *config, const Flatbuffer<Configuration> &addition) {
839 return MergeConfiguration(MergeFlatBuffers(config, &addition.message()));
840}
841
842FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Austin Schuh8d6cea82020-02-28 12:17:16 -0800843 const Configuration *config, std::string_view json) {
844 FlatbufferDetachedBuffer<Configuration> addition =
845 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
846
Brian Silverman24f5aa82020-06-23 16:21:28 -0700847 return MergeWithConfig(config, addition);
Austin Schuh8d6cea82020-02-28 12:17:16 -0800848}
849
James Kuszmaul3ae42262019-11-08 12:33:41 -0800850const Channel *GetChannel(const Configuration *config, std::string_view name,
851 std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800852 std::string_view application_name, const Node *node,
853 bool quiet) {
Brian Silverman9fcf2c72020-12-21 18:30:58 -0800854 if (!config->has_channels()) {
855 return nullptr;
856 }
857
Austin Schuhbca6cf02019-12-22 17:28:34 -0800858 const std::string_view original_name = name;
Austin Schuhf1fff282020-03-28 16:57:32 -0700859 std::string mutable_name;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700860 if (node != nullptr) {
861 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
862 << "\" } on " << aos::FlatbufferToJson(node);
863 } else {
864 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
865 << "\" }";
866 }
Austin Schuhcb108412019-10-13 16:09:54 -0700867
868 // First handle application specific maps. Only do this if we have a matching
869 // application name, and it has maps.
Austin Schuhd2e2f6a2021-02-07 20:46:16 -0800870 {
871 const Application *application =
872 GetApplication(config, node, application_name);
873 if (application != nullptr && application->has_maps()) {
874 mutable_name = std::string(name);
875 HandleMaps(application->maps(), &mutable_name, type, node);
876 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700877 }
878 }
879
880 // Now do global maps.
Austin Schuh40485ed2019-10-26 21:51:44 -0700881 if (config->has_maps()) {
Austin Schuhf1fff282020-03-28 16:57:32 -0700882 mutable_name = std::string(name);
883 HandleMaps(config->maps(), &mutable_name, type, node);
884 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700885 }
886
Austin Schuhbca6cf02019-12-22 17:28:34 -0800887 if (original_name != name) {
888 VLOG(1) << "Remapped to { \"name\": \"" << name << "\", \"type\": \""
889 << type << "\" }";
890 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700891
James Kuszmaul71a81932020-12-15 21:08:01 -0800892 // Then look for the channel (note that this relies on the channels being
893 // sorted in the config).
Austin Schuh40485ed2019-10-26 21:51:44 -0700894 auto channel_iterator =
Austin Schuhf1fff282020-03-28 16:57:32 -0700895 std::lower_bound(config->channels()->cbegin(), config->channels()->cend(),
Austin Schuh40485ed2019-10-26 21:51:44 -0700896 std::make_pair(name, type), CompareChannels);
Austin Schuhcb108412019-10-13 16:09:54 -0700897
898 // Make sure we actually found it, and it matches.
Austin Schuh40485ed2019-10-26 21:51:44 -0700899 if (channel_iterator != config->channels()->cend() &&
900 EqualsChannels(*channel_iterator, std::make_pair(name, type))) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800901 if (VLOG_IS_ON(2)) {
902 VLOG(2) << "Found: " << FlatbufferToJson(*channel_iterator);
903 } else if (VLOG_IS_ON(1)) {
904 VLOG(1) << "Found: " << CleanedChannelToString(*channel_iterator);
905 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700906 return *channel_iterator;
Austin Schuhcb108412019-10-13 16:09:54 -0700907 } else {
908 VLOG(1) << "No match for { \"name\": \"" << name << "\", \"type\": \""
909 << type << "\" }";
Austin Schuh0de30f32020-12-06 12:44:28 -0800910 if (original_name != name && !quiet) {
Austin Schuh4b42b252020-10-19 11:35:20 -0700911 LOG(WARNING) << "Remapped from {\"name\": \"" << original_name
912 << "\", \"type\": \"" << type << "\"}, to {\"name\": \""
913 << name << "\", \"type\": \"" << type
914 << "\"}, but no channel by that name exists.";
915 }
Austin Schuhcb108412019-10-13 16:09:54 -0700916 return nullptr;
917 }
918}
919
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800920size_t ChannelIndex(const Configuration *configuration,
921 const Channel *channel) {
922 CHECK(configuration->channels() != nullptr) << ": No channels";
923
Brian Silvermana9698c92021-11-10 12:27:04 -0800924 const auto c = std::lower_bound(
925 configuration->channels()->cbegin(), configuration->channels()->cend(),
926 std::make_pair(channel->name()->string_view(),
927 channel->type()->string_view()),
928 CompareChannels);
929 CHECK(c != configuration->channels()->cend())
930 << ": Channel pointer not found in configuration()->channels()";
931 CHECK(*c == channel)
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800932 << ": Channel pointer not found in configuration()->channels()";
933
Brian Silvermana9698c92021-11-10 12:27:04 -0800934 return std::distance(configuration->channels()->cbegin(), c);
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800935}
936
Austin Schuhbca6cf02019-12-22 17:28:34 -0800937std::string CleanedChannelToString(const Channel *channel) {
938 FlatbufferDetachedBuffer<Channel> cleaned_channel = CopyFlatBuffer(channel);
939 cleaned_channel.mutable_message()->clear_schema();
940 return FlatbufferToJson(cleaned_channel);
941}
942
Austin Schuha81454b2020-05-12 19:58:36 -0700943std::string StrippedChannelToString(const Channel *channel) {
944 return absl::StrCat("{ \"name\": \"", channel->name()->string_view(),
945 "\", \"type\": \"", channel->type()->string_view(),
946 "\" }");
947}
948
Alex Perrycb7da4b2019-08-28 19:35:56 -0700949FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
950 const Flatbuffer<Configuration> &config,
Austin Schuh0de30f32020-12-06 12:44:28 -0800951 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700952 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800953 fbb.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700954
Austin Schuh68d98592020-11-01 23:22:57 -0800955 // Cache for holding already inserted schemas.
956 std::map<std::string_view, flatbuffers::Offset<reflection::Schema>>
957 schema_cache;
958
959 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
960 << ": Merging logic needs to be updated when the number of channel "
961 "fields changes.";
James Kuszmaul3c998592020-07-27 21:04:47 -0700962
Alex Perrycb7da4b2019-08-28 19:35:56 -0700963 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
964 channels_offset;
965 if (config.message().has_channels()) {
966 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
967 for (const Channel *c : *config.message().channels()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700968 // Search for a schema with a matching type.
Austin Schuh0de30f32020-12-06 12:44:28 -0800969 const aos::FlatbufferVector<reflection::Schema> *found_schema = nullptr;
970 for (const aos::FlatbufferVector<reflection::Schema> &schema : schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700971 if (schema.message().root_table() != nullptr) {
972 if (schema.message().root_table()->name()->string_view() ==
973 c->type()->string_view()) {
974 found_schema = &schema;
975 }
976 }
977 }
978
979 CHECK(found_schema != nullptr)
980 << ": Failed to find schema for " << FlatbufferToJson(c);
981
Austin Schuh68d98592020-11-01 23:22:57 -0800982 // Now copy the message manually.
983 auto cached_schema = schema_cache.find(c->type()->string_view());
984 flatbuffers::Offset<reflection::Schema> schema_offset;
985 if (cached_schema != schema_cache.end()) {
986 schema_offset = cached_schema->second;
987 } else {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800988 schema_offset = RecursiveCopyFlatBuffer<reflection::Schema>(
989 &found_schema->message(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800990 schema_cache.emplace(c->type()->string_view(), schema_offset);
991 }
992
993 flatbuffers::Offset<flatbuffers::String> name_offset =
994 fbb.CreateSharedString(c->name()->str());
995 flatbuffers::Offset<flatbuffers::String> type_offset =
996 fbb.CreateSharedString(c->type()->str());
997 flatbuffers::Offset<flatbuffers::String> source_node_offset =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800998 c->has_source_node() ? fbb.CreateSharedString(c->source_node()->str())
999 : 0;
Austin Schuh68d98592020-11-01 23:22:57 -08001000
1001 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
1002 destination_nodes_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -08001003 aos::RecursiveCopyVectorTable(c->destination_nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001004
1005 flatbuffers::Offset<
1006 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
1007 logger_nodes_offset =
1008 aos::CopyVectorSharedString(c->logger_nodes(), &fbb);
1009
1010 Channel::Builder channel_builder(fbb);
1011 channel_builder.add_name(name_offset);
1012 channel_builder.add_type(type_offset);
1013 if (c->has_frequency()) {
1014 channel_builder.add_frequency(c->frequency());
1015 }
1016 if (c->has_max_size()) {
1017 channel_builder.add_max_size(c->max_size());
1018 }
1019 if (c->has_num_senders()) {
1020 channel_builder.add_num_senders(c->num_senders());
1021 }
1022 if (c->has_num_watchers()) {
1023 channel_builder.add_num_watchers(c->num_watchers());
1024 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001025 channel_builder.add_schema(schema_offset);
Austin Schuh68d98592020-11-01 23:22:57 -08001026 if (!source_node_offset.IsNull()) {
1027 channel_builder.add_source_node(source_node_offset);
1028 }
1029 if (!destination_nodes_offset.IsNull()) {
1030 channel_builder.add_destination_nodes(destination_nodes_offset);
1031 }
1032 if (c->has_logger()) {
1033 channel_builder.add_logger(c->logger());
1034 }
1035 if (!logger_nodes_offset.IsNull()) {
1036 channel_builder.add_logger_nodes(logger_nodes_offset);
1037 }
1038 if (c->has_read_method()) {
1039 channel_builder.add_read_method(c->read_method());
1040 }
1041 if (c->has_num_readers()) {
1042 channel_builder.add_num_readers(c->num_readers());
1043 }
1044 channel_offsets.emplace_back(channel_builder.Finish());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001045 }
1046 channels_offset = fbb.CreateVector(channel_offsets);
1047 }
1048
Austin Schuh68d98592020-11-01 23:22:57 -08001049 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -08001050 maps_offset =
1051 aos::RecursiveCopyVectorTable(config.message().maps(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001052
1053 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -08001054 nodes_offset =
1055 aos::RecursiveCopyVectorTable(config.message().nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -08001056
1057 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1058 applications_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -08001059 aos::RecursiveCopyVectorTable(config.message().applications(), &fbb);
Austin Schuh217a9782019-12-21 23:02:50 -08001060
1061 // Now insert everything else in unmodified.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001062 ConfigurationBuilder configuration_builder(fbb);
1063 if (config.message().has_channels()) {
1064 configuration_builder.add_channels(channels_offset);
1065 }
Austin Schuh68d98592020-11-01 23:22:57 -08001066 if (!maps_offset.IsNull()) {
1067 configuration_builder.add_maps(maps_offset);
1068 }
1069 if (!nodes_offset.IsNull()) {
1070 configuration_builder.add_nodes(nodes_offset);
1071 }
1072 if (!applications_offset.IsNull()) {
1073 configuration_builder.add_applications(applications_offset);
1074 }
1075
1076 if (config.message().has_channel_storage_duration()) {
1077 configuration_builder.add_channel_storage_duration(
1078 config.message().channel_storage_duration());
1079 }
1080
1081 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1082 << ": Merging logic needs to be updated when the number of configuration "
1083 "fields changes.";
1084
Alex Perrycb7da4b2019-08-28 19:35:56 -07001085 fbb.Finish(configuration_builder.Finish());
James Kuszmaul3c998592020-07-27 21:04:47 -07001086 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
1087 fbb.Release());
1088
Austin Schuh68d98592020-11-01 23:22:57 -08001089 return modified_config;
Alex Perrycb7da4b2019-08-28 19:35:56 -07001090}
1091
Austin Schuh217a9782019-12-21 23:02:50 -08001092const Node *GetNodeFromHostname(const Configuration *config,
1093 std::string_view hostname) {
1094 for (const Node *node : *config->nodes()) {
Brian Silvermanaa2633f2020-02-17 21:04:14 -08001095 if (node->has_hostname() && node->hostname()->string_view() == hostname) {
Austin Schuh217a9782019-12-21 23:02:50 -08001096 return node;
1097 }
Brian Silvermanaa2633f2020-02-17 21:04:14 -08001098 if (node->has_hostnames()) {
1099 for (const auto &candidate : *node->hostnames()) {
1100 if (candidate->string_view() == hostname) {
1101 return node;
1102 }
1103 }
1104 }
Austin Schuh217a9782019-12-21 23:02:50 -08001105 }
1106 return nullptr;
1107}
Austin Schuhac0771c2020-01-07 18:36:30 -08001108
Austin Schuh217a9782019-12-21 23:02:50 -08001109const Node *GetMyNode(const Configuration *config) {
1110 const std::string hostname = (FLAGS_override_hostname.size() > 0)
1111 ? FLAGS_override_hostname
1112 : network::GetHostname();
1113 const Node *node = GetNodeFromHostname(config, hostname);
1114 if (node != nullptr) return node;
1115
1116 LOG(FATAL) << "Unknown node for host: " << hostname
1117 << ". Consider using --override_hostname if hostname detection "
1118 "is wrong.";
1119 return nullptr;
1120}
1121
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001122const Node *GetNode(const Configuration *config, const Node *node) {
1123 if (!MultiNode(config)) {
1124 CHECK(node == nullptr) << ": Provided a node in a single node world.";
1125 return nullptr;
1126 } else {
1127 CHECK(node != nullptr);
1128 CHECK(node->has_name());
1129 return GetNode(config, node->name()->string_view());
1130 }
1131}
1132
Austin Schuh217a9782019-12-21 23:02:50 -08001133const Node *GetNode(const Configuration *config, std::string_view name) {
Austin Schuhfd960622020-01-01 13:22:55 -08001134 CHECK(config->has_nodes())
1135 << ": Asking for a node from a single node configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -08001136 for (const Node *node : *config->nodes()) {
Austin Schuhfd960622020-01-01 13:22:55 -08001137 CHECK(node->has_name()) << ": Malformed node " << FlatbufferToJson(node);
Austin Schuh217a9782019-12-21 23:02:50 -08001138 if (node->name()->string_view() == name) {
1139 return node;
1140 }
1141 }
1142 return nullptr;
1143}
1144
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001145const Node *GetNode(const Configuration *config, size_t node_index) {
1146 if (!MultiNode(config)) {
1147 CHECK_EQ(node_index, 0u) << ": Invalid node in a single node world.";
1148 return nullptr;
1149 } else {
1150 CHECK_LT(node_index, config->nodes()->size());
1151 return config->nodes()->Get(node_index);
1152 }
1153}
1154
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001155const Node *GetNodeOrDie(const Configuration *config, const Node *node) {
1156 if (!MultiNode(config)) {
1157 CHECK(node == nullptr) << ": Provided a node in a single node world.";
1158 return nullptr;
1159 } else {
1160 const Node *config_node = GetNode(config, node);
1161 if (config_node == nullptr) {
1162 LOG(FATAL) << "Couldn't find node matching " << FlatbufferToJson(node);
1163 }
1164 return config_node;
1165 }
1166}
1167
Austin Schuh8bd96322020-02-13 21:18:22 -08001168namespace {
1169int GetNodeIndexFromConfig(const Configuration *config, const Node *node) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001170 int node_index = 0;
1171 for (const Node *iterated_node : *config->nodes()) {
1172 if (iterated_node == node) {
1173 return node_index;
1174 }
1175 ++node_index;
1176 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001177 return -1;
1178}
1179} // namespace
1180
Austin Schuha9df9ad2021-06-16 14:49:39 -07001181aos::FlatbufferDetachedBuffer<aos::Configuration> AddSchema(
1182 std::string_view json,
1183 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
1184 FlatbufferDetachedBuffer<Configuration> addition =
1185 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
1186 return MergeConfiguration(addition, schemas);
1187}
1188
Austin Schuh8bd96322020-02-13 21:18:22 -08001189int GetNodeIndex(const Configuration *config, const Node *node) {
1190 if (!MultiNode(config)) {
1191 return 0;
1192 }
1193
1194 {
1195 int node_index = GetNodeIndexFromConfig(config, node);
1196 if (node_index != -1) {
1197 return node_index;
1198 }
1199 }
1200
1201 const Node *result = GetNode(config, node);
1202 CHECK(result != nullptr);
1203
1204 {
Austin Schuh04408fc2020-02-16 21:48:54 -08001205 int node_index = GetNodeIndexFromConfig(config, result);
Austin Schuh8bd96322020-02-13 21:18:22 -08001206 if (node_index != -1) {
1207 return node_index;
1208 }
1209 }
1210
1211 LOG(FATAL) << "Node " << FlatbufferToJson(node)
1212 << " not found in the configuration.";
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001213}
1214
Austin Schuh04408fc2020-02-16 21:48:54 -08001215int GetNodeIndex(const Configuration *config, std::string_view name) {
1216 if (!MultiNode(config)) {
1217 return 0;
1218 }
1219
1220 {
1221 int node_index = 0;
1222 for (const Node *iterated_node : *config->nodes()) {
1223 if (iterated_node->name()->string_view() == name) {
1224 return node_index;
1225 }
1226 ++node_index;
1227 }
1228 }
1229 LOG(FATAL) << "Node " << name << " not found in the configuration.";
1230}
1231
Austin Schuh681a2472020-12-31 23:55:40 -08001232size_t NodesCount(const Configuration *config) {
1233 if (!MultiNode(config)) {
1234 return 1u;
1235 }
1236
1237 return config->nodes()->size();
1238}
1239
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001240std::vector<const Node *> GetNodes(const Configuration *config) {
1241 std::vector<const Node *> nodes;
Austin Schuh8bd96322020-02-13 21:18:22 -08001242 if (MultiNode(config)) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001243 for (const Node *node : *config->nodes()) {
1244 nodes.emplace_back(node);
1245 }
1246 } else {
1247 nodes.emplace_back(nullptr);
1248 }
1249 return nodes;
1250}
1251
Austin Schuh65465332020-11-05 17:36:53 -08001252std::vector<const Node *> GetNodesWithTag(const Configuration *config,
1253 std::string_view tag) {
1254 std::vector<const Node *> nodes;
1255 if (!MultiNode(config)) {
1256 nodes.emplace_back(nullptr);
1257 } else {
1258 for (const Node *node : *config->nodes()) {
1259 if (!node->has_tags()) {
1260 continue;
1261 }
1262 bool did_found_tag = false;
1263 for (const flatbuffers::String *found_tag : *node->tags()) {
1264 if (found_tag->string_view() == tag) {
1265 did_found_tag = true;
1266 break;
1267 }
1268 }
1269 if (did_found_tag) {
1270 nodes.emplace_back(node);
1271 }
1272 }
1273 }
1274 return nodes;
1275}
1276
Brian Silverman631b6262021-11-10 12:25:08 -08001277bool NodeHasTag(const Node *node, std::string_view tag) {
1278 if (node == nullptr) {
1279 return true;
1280 }
1281
1282 const auto *const tags = node->tags();
1283 return std::find_if(tags->begin(), tags->end(),
1284 [tag](const flatbuffers::String *candidate) {
1285 return candidate->string_view() == tag;
1286 }) != tags->end();
1287}
1288
Austin Schuhac0771c2020-01-07 18:36:30 -08001289bool MultiNode(const Configuration *config) { return config->has_nodes(); }
1290
Austin Schuh217a9782019-12-21 23:02:50 -08001291bool ChannelIsSendableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001292 if (node == nullptr) {
1293 return true;
1294 }
Austin Schuh3c5dae52020-10-06 18:55:18 -07001295 CHECK(channel->has_source_node()) << FlatbufferToJson(channel);
1296 CHECK(node->has_name()) << FlatbufferToJson(node);
Austin Schuh196a4452020-03-15 23:12:03 -07001297 return (CHECK_NOTNULL(channel)->source_node()->string_view() ==
1298 node->name()->string_view());
Austin Schuh217a9782019-12-21 23:02:50 -08001299}
1300
1301bool ChannelIsReadableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001302 if (node == nullptr) {
1303 return true;
1304 }
1305
Austin Schuh217a9782019-12-21 23:02:50 -08001306 if (channel->source_node()->string_view() == node->name()->string_view()) {
1307 return true;
1308 }
1309
1310 if (!channel->has_destination_nodes()) {
1311 return false;
1312 }
1313
Austin Schuh719946b2019-12-28 14:51:01 -08001314 for (const Connection *connection : *channel->destination_nodes()) {
1315 CHECK(connection->has_name());
1316 if (connection->name()->string_view() == node->name()->string_view()) {
Austin Schuh217a9782019-12-21 23:02:50 -08001317 return true;
1318 }
1319 }
1320
1321 return false;
1322}
1323
Austin Schuh719946b2019-12-28 14:51:01 -08001324bool ChannelMessageIsLoggedOnNode(const Channel *channel, const Node *node) {
Austin Schuh48e94502021-06-18 18:35:53 -07001325 if (node == nullptr) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001326 // Single node world. If there is a local logger, then we want to use
1327 // it.
Austin Schuh48e94502021-06-18 18:35:53 -07001328 if (channel->logger() == LoggerConfig::LOCAL_LOGGER) {
1329 return true;
1330 } else if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1331 return false;
1332 }
1333 LOG(FATAL) << "Unsupported logging configuration in a single node world: "
1334 << CleanedChannelToString(channel);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001335 }
1336 return ChannelMessageIsLoggedOnNode(
1337 channel, CHECK_NOTNULL(node)->name()->string_view());
1338}
1339
1340bool ChannelMessageIsLoggedOnNode(const Channel *channel,
1341 std::string_view node_name) {
Austin Schuhf1fff282020-03-28 16:57:32 -07001342 switch (channel->logger()) {
Austin Schuh719946b2019-12-28 14:51:01 -08001343 case LoggerConfig::LOCAL_LOGGER:
Austin Schuh2bb80e02021-03-20 21:46:17 -07001344 return channel->source_node()->string_view() == node_name;
Austin Schuh719946b2019-12-28 14:51:01 -08001345 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001346 CHECK(channel->has_logger_nodes());
1347 CHECK_GT(channel->logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001348
Austin Schuh2bb80e02021-03-20 21:46:17 -07001349 if (channel->source_node()->string_view() == node_name) {
Austin Schuh719946b2019-12-28 14:51:01 -08001350 return true;
1351 }
Austin Schuhda40e472020-03-28 15:15:29 -07001352
1353 [[fallthrough]];
1354 case LoggerConfig::REMOTE_LOGGER:
1355 CHECK(channel->has_logger_nodes());
1356 CHECK_GT(channel->logger_nodes()->size(), 0u);
1357 for (const flatbuffers::String *logger_node : *channel->logger_nodes()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001358 if (logger_node->string_view() == node_name) {
Austin Schuhda40e472020-03-28 15:15:29 -07001359 return true;
1360 }
Austin Schuh719946b2019-12-28 14:51:01 -08001361 }
1362
1363 return false;
1364 case LoggerConfig::NOT_LOGGED:
1365 return false;
1366 }
1367
1368 LOG(FATAL) << "Unknown logger config " << static_cast<int>(channel->logger());
1369}
1370
Austin Schuh58646e22021-08-23 23:51:46 -07001371size_t ConnectionCount(const Channel *channel) {
1372 if (!channel->has_destination_nodes()) {
1373 return 0;
1374 }
1375 return channel->destination_nodes()->size();
1376}
1377
Austin Schuh719946b2019-12-28 14:51:01 -08001378const Connection *ConnectionToNode(const Channel *channel, const Node *node) {
1379 if (!channel->has_destination_nodes()) {
1380 return nullptr;
1381 }
1382 for (const Connection *connection : *channel->destination_nodes()) {
1383 if (connection->name()->string_view() == node->name()->string_view()) {
1384 return connection;
1385 }
1386 }
1387 return nullptr;
1388}
1389
1390bool ConnectionDeliveryTimeIsLoggedOnNode(const Channel *channel,
1391 const Node *node,
1392 const Node *logger_node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001393 return ConnectionDeliveryTimeIsLoggedOnNode(ConnectionToNode(channel, node),
1394 logger_node);
Austin Schuh719946b2019-12-28 14:51:01 -08001395}
1396
1397bool ConnectionDeliveryTimeIsLoggedOnNode(const Connection *connection,
1398 const Node *node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001399 if (connection == nullptr) {
1400 return false;
1401 }
Austin Schuh719946b2019-12-28 14:51:01 -08001402 switch (connection->timestamp_logger()) {
1403 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001404 CHECK(connection->has_timestamp_logger_nodes());
1405 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001406 if (connection->name()->string_view() == node->name()->string_view()) {
1407 return true;
1408 }
1409
Austin Schuhda40e472020-03-28 15:15:29 -07001410 [[fallthrough]];
1411 case LoggerConfig::REMOTE_LOGGER:
1412 CHECK(connection->has_timestamp_logger_nodes());
1413 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
1414 for (const flatbuffers::String *timestamp_logger_node :
1415 *connection->timestamp_logger_nodes()) {
1416 if (timestamp_logger_node->string_view() ==
1417 node->name()->string_view()) {
1418 return true;
1419 }
Austin Schuh719946b2019-12-28 14:51:01 -08001420 }
1421
1422 return false;
1423 case LoggerConfig::LOCAL_LOGGER:
1424 return connection->name()->string_view() == node->name()->string_view();
Austin Schuh719946b2019-12-28 14:51:01 -08001425 case LoggerConfig::NOT_LOGGED:
1426 return false;
1427 }
1428
1429 LOG(FATAL) << "Unknown logger config "
1430 << static_cast<int>(connection->timestamp_logger());
1431}
1432
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001433std::vector<std::string_view> SourceNodeNames(const Configuration *config,
1434 const Node *my_node) {
1435 std::set<std::string_view> result_set;
1436
1437 for (const Channel *channel : *config->channels()) {
1438 if (channel->has_destination_nodes()) {
1439 for (const Connection *connection : *channel->destination_nodes()) {
1440 if (connection->name()->string_view() ==
1441 my_node->name()->string_view()) {
1442 result_set.insert(channel->source_node()->string_view());
1443 }
1444 }
1445 }
1446 }
1447
1448 std::vector<std::string_view> result;
1449 for (const std::string_view source : result_set) {
1450 VLOG(1) << "Found a source node of " << source;
1451 result.emplace_back(source);
1452 }
1453 return result;
1454}
1455
1456std::vector<std::string_view> DestinationNodeNames(const Configuration *config,
1457 const Node *my_node) {
1458 std::vector<std::string_view> result;
1459
1460 for (const Channel *channel : *config->channels()) {
1461 if (channel->has_source_node() && channel->source_node()->string_view() ==
1462 my_node->name()->string_view()) {
1463 if (!channel->has_destination_nodes()) continue;
1464
1465 if (channel->source_node()->string_view() !=
1466 my_node->name()->string_view()) {
1467 continue;
1468 }
1469
1470 for (const Connection *connection : *channel->destination_nodes()) {
1471 if (std::find(result.begin(), result.end(),
1472 connection->name()->string_view()) == result.end()) {
1473 result.emplace_back(connection->name()->string_view());
1474 }
1475 }
1476 }
1477 }
1478
1479 for (const std::string_view destination : result) {
1480 VLOG(1) << "Found a destination node of " << destination;
1481 }
1482 return result;
1483}
1484
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001485std::vector<const Node *> TimestampNodes(const Configuration *config,
1486 const Node *my_node) {
1487 if (!configuration::MultiNode(config)) {
1488 CHECK(my_node == nullptr);
1489 return std::vector<const Node *>{};
1490 }
1491
1492 std::set<const Node *> timestamp_logger_nodes;
1493 for (const Channel *channel : *config->channels()) {
1494 if (!configuration::ChannelIsSendableOnNode(channel, my_node)) {
1495 continue;
1496 }
1497 if (!channel->has_destination_nodes()) {
1498 continue;
1499 }
1500 for (const Connection *connection : *channel->destination_nodes()) {
1501 const Node *other_node =
1502 configuration::GetNode(config, connection->name()->string_view());
1503
1504 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
1505 my_node)) {
1506 VLOG(1) << "Timestamps are logged from "
1507 << FlatbufferToJson(other_node);
1508 timestamp_logger_nodes.insert(other_node);
1509 }
1510 }
1511 }
1512
1513 std::vector<const Node *> result;
1514 for (const Node *node : timestamp_logger_nodes) {
1515 result.emplace_back(node);
1516 }
1517 return result;
1518}
1519
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001520bool ApplicationShouldStart(const Configuration *config, const Node *my_node,
1521 const Application *application) {
1522 if (MultiNode(config)) {
1523 // Ok, we need
1524 CHECK(application->has_nodes());
1525 CHECK(my_node != nullptr);
1526 for (const flatbuffers::String *str : *application->nodes()) {
1527 if (str->string_view() == my_node->name()->string_view()) {
1528 return true;
1529 }
1530 }
1531 return false;
1532 } else {
1533 return true;
1534 }
1535}
1536
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001537const Application *GetApplication(const Configuration *config,
1538 const Node *my_node,
1539 std::string_view application_name) {
1540 if (config->has_applications()) {
1541 auto application_iterator = std::lower_bound(
1542 config->applications()->cbegin(), config->applications()->cend(),
1543 application_name, CompareApplications);
1544 if (application_iterator != config->applications()->cend() &&
1545 EqualsApplications(*application_iterator, application_name)) {
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001546 if (ApplicationShouldStart(config, my_node, *application_iterator)) {
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001547 return *application_iterator;
1548 }
1549 }
1550 }
1551 return nullptr;
1552}
1553
Austin Schuhfc7b6a02021-07-12 21:19:07 -07001554std::vector<size_t> SourceNodeIndex(const Configuration *config) {
1555 CHECK(config->has_channels());
1556 std::vector<size_t> result;
1557 result.resize(config->channels()->size(), 0u);
1558 if (MultiNode(config)) {
1559 for (size_t i = 0; i < config->channels()->size(); ++i) {
1560 result[i] = GetNodeIndex(
1561 config, config->channels()->Get(i)->source_node()->string_view());
1562 }
1563 }
1564 return result;
1565}
1566
Brian Silverman66f079a2013-08-26 16:24:30 -07001567} // namespace configuration
1568} // namespace aos