blob: a00c8e76a73d858aa9db9bd792d2e16cccae2fd5 [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
63 CHECK_GT(buffer.size(), 0u) << ": Failed to parse JSON file";
64
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 Schuh40485ed2019-10-26 21:51:44 -070094bool operator==(const FlatbufferDetachedBuffer<Application> &lhs,
95 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -070096 return lhs.message().name()->string_view() ==
97 rhs.message().name()->string_view();
98}
99
Austin Schuh40485ed2019-10-26 21:51:44 -0700100bool operator<(const FlatbufferDetachedBuffer<Application> &lhs,
101 const FlatbufferDetachedBuffer<Application> &rhs) {
Austin Schuhcb108412019-10-13 16:09:54 -0700102 return lhs.message().name()->string_view() <
103 rhs.message().name()->string_view();
104}
105
Austin Schuh217a9782019-12-21 23:02:50 -0800106bool operator==(const FlatbufferDetachedBuffer<Node> &lhs,
107 const FlatbufferDetachedBuffer<Node> &rhs) {
108 return lhs.message().name()->string_view() ==
109 rhs.message().name()->string_view();
110}
111
112bool operator<(const FlatbufferDetachedBuffer<Node> &lhs,
113 const FlatbufferDetachedBuffer<Node> &rhs) {
114 return lhs.message().name()->string_view() <
115 rhs.message().name()->string_view();
116}
117
Brian Silverman66f079a2013-08-26 16:24:30 -0700118namespace configuration {
119namespace {
120
Austin Schuhcb108412019-10-13 16:09:54 -0700121// Extracts the folder part of a path. Returns ./ if there is no path.
Austin Schuhf1fff282020-03-28 16:57:32 -0700122std::string_view ExtractFolder(const std::string_view filename) {
Austin Schuhcb108412019-10-13 16:09:54 -0700123 auto last_slash_pos = filename.find_last_of("/\\");
124
James Kuszmaul3ae42262019-11-08 12:33:41 -0800125 return last_slash_pos == std::string_view::npos
126 ? std::string_view("./")
Austin Schuhcb108412019-10-13 16:09:54 -0700127 : filename.substr(0, last_slash_pos + 1);
128}
129
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700130std::string AbsolutePath(const std::string_view filename) {
131 // Uses an std::string so that we know the input will be null-terminated.
132 const std::string terminated_file(filename);
133 char buffer[PATH_MAX];
134 PCHECK(NULL != realpath(terminated_file.c_str(), buffer));
135 return buffer;
136}
137
Austin Schuhef38cd22021-07-21 15:24:23 -0700138std::string RemoveDotDots(const std::string_view filename) {
139 std::vector<std::string> split = absl::StrSplit(filename, '/');
140 auto iterator = split.begin();
141 while (iterator != split.end()) {
142 if (iterator->empty()) {
143 iterator = split.erase(iterator);
144 } else if (*iterator == ".") {
145 iterator = split.erase(iterator);
146 } else if (*iterator == "..") {
147 CHECK(iterator != split.begin())
148 << ": Import path may not start with ..: " << filename;
149 auto previous = iterator;
150 --previous;
151 split.erase(iterator);
152 iterator = split.erase(previous);
153 } else {
154 ++iterator;
155 }
156 }
157 return absl::StrJoin(split, "/");
158}
159
Austin Schuh40485ed2019-10-26 21:51:44 -0700160FlatbufferDetachedBuffer<Configuration> ReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700161 const std::string_view path, absl::btree_set<std::string> *visited_paths,
162 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuh15182322020-10-10 15:25:21 -0700163 std::string binary_path = MaybeReplaceExtension(path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700164 VLOG(1) << "Looking up: " << path << ", starting with: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700165 bool binary_path_exists = util::PathExists(binary_path);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700166 std::string raw_path(path);
Austin Schuh15182322020-10-10 15:25:21 -0700167 // For each .json file, look and see if we can find a .bfbs file next to it
168 // with the same base name. If we can, assume it is the same and use it
169 // instead. It is much faster to load .bfbs files than .json files.
170 if (!binary_path_exists && !util::PathExists(raw_path)) {
171 const bool path_is_absolute = raw_path.size() > 0 && raw_path[0] == '/';
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700172 if (path_is_absolute) {
173 CHECK(extra_import_paths.empty())
174 << "Can't specify extra import paths if attempting to read a config "
175 "file from an absolute path (path is "
Austin Schuh15182322020-10-10 15:25:21 -0700176 << raw_path << ").";
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700177 }
178
179 bool found_path = false;
180 for (const auto &import_path : extra_import_paths) {
Austin Schuhef38cd22021-07-21 15:24:23 -0700181 raw_path = std::string(import_path) + "/" + RemoveDotDots(path);
Austin Schuh15182322020-10-10 15:25:21 -0700182 binary_path = MaybeReplaceExtension(raw_path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700183 VLOG(1) << "Checking: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700184 binary_path_exists = util::PathExists(binary_path);
185 if (binary_path_exists) {
186 found_path = true;
187 break;
188 }
Austin Schuhef38cd22021-07-21 15:24:23 -0700189 VLOG(1) << "Checking: " << raw_path;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700190 if (util::PathExists(raw_path)) {
191 found_path = true;
192 break;
193 }
194 }
195 CHECK(found_path) << ": Failed to find file " << path << ".";
196 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197
Austin Schuh15182322020-10-10 15:25:21 -0700198 FlatbufferDetachedBuffer<Configuration> config = ReadConfigFile(
199 binary_path_exists ? binary_path : raw_path, binary_path_exists);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700200
Austin Schuhcb108412019-10-13 16:09:54 -0700201 // Depth first. Take the following example:
202 //
203 // config1.json:
204 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700205 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700206 // {
207 // "name": "/foo",
208 // "type": ".aos.bar",
209 // "max_size": 5
210 // }
211 // ],
212 // "imports": [
213 // "config2.json",
214 // ]
215 // }
216 //
217 // config2.json:
218 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700219 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700220 // {
221 // "name": "/foo",
222 // "type": ".aos.bar",
223 // "max_size": 7
224 // }
225 // ],
226 // }
227 //
228 // We want the main config (config1.json) to be able to override the imported
229 // config. That means that it needs to be merged into the imported configs,
230 // not the other way around.
231
Austin Schuh15182322020-10-10 15:25:21 -0700232 const std::string absolute_path =
233 AbsolutePath(binary_path_exists ? binary_path : raw_path);
234 // Track that we have seen this file before recursing. Track the path we
235 // actually loaded (which should be consistent if imported twice).
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700236 if (!visited_paths->insert(absolute_path).second) {
237 for (const auto &visited_path : *visited_paths) {
238 LOG(INFO) << "Already visited: " << visited_path;
239 }
240 LOG(FATAL)
241 << "Already imported " << path << " (i.e. " << absolute_path
242 << "). See above for the files that have already been processed.";
243 }
Austin Schuhcb108412019-10-13 16:09:54 -0700244
245 if (config.message().has_imports()) {
246 // Capture the imports.
247 const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *v =
248 config.message().imports();
249
250 // And then wipe them. This gets GCed when we merge later.
251 config.mutable_message()->clear_imports();
252
253 // Start with an empty configuration to merge into.
Austin Schuh40485ed2019-10-26 21:51:44 -0700254 FlatbufferDetachedBuffer<Configuration> merged_config =
255 FlatbufferDetachedBuffer<Configuration>::Empty();
Austin Schuhcb108412019-10-13 16:09:54 -0700256
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700257 const std::string path_folder(ExtractFolder(path));
Austin Schuhcb108412019-10-13 16:09:54 -0700258 for (const flatbuffers::String *str : *v) {
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700259 const std::string included_config =
260 path_folder + "/" + std::string(str->string_view());
Austin Schuhcb108412019-10-13 16:09:54 -0700261
262 // And them merge everything in.
263 merged_config = MergeFlatBuffers(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700264 merged_config,
265 ReadConfig(included_config, visited_paths, extra_import_paths));
Austin Schuhcb108412019-10-13 16:09:54 -0700266 }
267
268 // Finally, merge this file in.
269 config = MergeFlatBuffers(merged_config, config);
270 }
271 return config;
272}
273
Alex Perrycb7da4b2019-08-28 19:35:56 -0700274// Compares (c < p) a channel, and a name, type tuple.
275bool CompareChannels(const Channel *c,
James Kuszmaul3ae42262019-11-08 12:33:41 -0800276 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277 int name_compare = c->name()->string_view().compare(p.first);
278 if (name_compare == 0) {
279 return c->type()->string_view() < p.second;
280 } else if (name_compare < 0) {
281 return true;
282 } else {
283 return false;
284 }
285};
286
287// Compares for equality (c == p) a channel, and a name, type tuple.
288bool EqualsChannels(const Channel *c,
Austin Schuhf1fff282020-03-28 16:57:32 -0700289 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290 return c->name()->string_view() == p.first &&
291 c->type()->string_view() == p.second;
292}
293
294// Compares (c < p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800295bool CompareApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296 return a->name()->string_view() < name;
297};
298
299// Compares for equality (c == p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800300bool EqualsApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301 return a->name()->string_view() == name;
302}
303
Austin Schuh15182322020-10-10 15:25:21 -0700304void ValidateConfiguration(const Flatbuffer<Configuration> &config) {
305 // No imports should be left.
306 CHECK(!config.message().has_imports());
307
308 // Check that if there is a node list, all the source nodes are filled out and
309 // valid, and all the destination nodes are valid (and not the source). This
310 // is a basic consistency check.
311 if (config.message().has_channels()) {
312 const Channel *last_channel = nullptr;
313 for (const Channel *c : *config.message().channels()) {
314 CHECK(c->has_name());
315 CHECK(c->has_type());
316 if (c->name()->string_view().back() == '/') {
317 LOG(FATAL) << "Channel names can't end with '/'";
318 }
319 if (c->name()->string_view().find("//") != std::string_view::npos) {
320 LOG(FATAL) << ": Invalid channel name " << c->name()->string_view()
321 << ", can't use //.";
322 }
323 for (const char data : c->name()->string_view()) {
324 if (data >= '0' && data <= '9') {
325 continue;
326 }
327 if (data >= 'a' && data <= 'z') {
328 continue;
329 }
330 if (data >= 'A' && data <= 'Z') {
331 continue;
332 }
333 if (data == '-' || data == '_' || data == '/') {
334 continue;
335 }
336 LOG(FATAL) << "Invalid channel name " << c->name()->string_view()
337 << ", can only use [-a-zA-Z0-9_/]";
338 }
339
Austin Schuh5e95bd62021-10-11 18:40:22 -0700340 // There is no good use case today for logging timestamps but not the
341 // corresponding data. Instead of plumbing through all of this on the
342 // reader side, let'd just disallow it for now.
343 if (c->logger() == LoggerConfig::NOT_LOGGED &&
344 c->has_destination_nodes()) {
345 for (const Connection *d : *c->destination_nodes()) {
346 CHECK(d->timestamp_logger() == LoggerConfig::NOT_LOGGED)
347 << ": Logging timestamps without data is not supported. If you "
348 "have a good use case, let's talk. "
349 << CleanedChannelToString(c);
350 }
351 }
352
Austin Schuh15182322020-10-10 15:25:21 -0700353 // Make sure everything is sorted while we are here... If this fails,
354 // there will be a bunch of weird errors.
355 if (last_channel != nullptr) {
356 CHECK(CompareChannels(
357 last_channel,
358 std::make_pair(c->name()->string_view(), c->type()->string_view())))
359 << ": Channels not sorted!";
360 }
361 last_channel = c;
362 }
363 }
364
365 if (config.message().has_nodes() && config.message().has_channels()) {
366 for (const Channel *c : *config.message().channels()) {
367 CHECK(c->has_source_node()) << ": Channel " << FlatbufferToJson(c)
368 << " is missing \"source_node\"";
369 CHECK(GetNode(&config.message(), c->source_node()->string_view()) !=
370 nullptr)
371 << ": Channel " << FlatbufferToJson(c)
372 << " has an unknown \"source_node\"";
373
374 if (c->has_destination_nodes()) {
375 for (const Connection *connection : *c->destination_nodes()) {
376 CHECK(connection->has_name());
377 CHECK(GetNode(&config.message(), connection->name()->string_view()) !=
378 nullptr)
379 << ": Channel " << FlatbufferToJson(c)
380 << " has an unknown \"destination_nodes\" "
381 << connection->name()->string_view();
382
383 switch (connection->timestamp_logger()) {
384 case LoggerConfig::LOCAL_LOGGER:
385 case LoggerConfig::NOT_LOGGED:
386 CHECK(!connection->has_timestamp_logger_nodes());
387 break;
388 case LoggerConfig::REMOTE_LOGGER:
389 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
390 CHECK(connection->has_timestamp_logger_nodes());
391 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
392 for (const flatbuffers::String *timestamp_logger_node :
393 *connection->timestamp_logger_nodes()) {
394 CHECK(GetNode(&config.message(),
395 timestamp_logger_node->string_view()) != nullptr)
396 << ": Channel " << FlatbufferToJson(c)
397 << " has an unknown \"timestamp_logger_node\""
398 << connection->name()->string_view();
399 }
400 break;
401 }
402
403 CHECK_NE(connection->name()->string_view(),
404 c->source_node()->string_view())
405 << ": Channel " << FlatbufferToJson(c)
406 << " is forwarding data to itself";
407 }
408 }
409 }
410 }
411}
412
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413} // namespace
414
Austin Schuh006a9f52021-04-07 16:24:18 -0700415// Maps name for the provided maps. Modifies name.
416void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
417 std::string *name, std::string_view type, const Node *node) {
418 // For the same reason we merge configs in reverse order, we want to process
419 // maps in reverse order. That lets the outer config overwrite channels from
420 // the inner configs.
421 for (auto i = maps->rbegin(); i != maps->rend(); ++i) {
422 if (!i->has_match() || !i->match()->has_name()) {
423 continue;
424 }
425 if (!i->has_rename() || !i->rename()->has_name()) {
426 continue;
427 }
428
429 // Handle normal maps (now that we know that match and rename are filled
430 // out).
431 const std::string_view match_name = i->match()->name()->string_view();
432 if (match_name != *name) {
433 if (match_name.back() == '*' &&
434 std::string_view(*name).substr(
435 0, std::min(name->size(), match_name.size() - 1)) ==
436 match_name.substr(0, match_name.size() - 1)) {
437 CHECK_EQ(match_name.find('*'), match_name.size() - 1);
438 } else {
439 continue;
440 }
441 }
442
443 // Handle type specific maps.
444 if (i->match()->has_type() && i->match()->type()->string_view() != type) {
445 continue;
446 }
447
448 // Now handle node specific maps.
449 if (node != nullptr && i->match()->has_source_node() &&
450 i->match()->source_node()->string_view() !=
451 node->name()->string_view()) {
452 continue;
453 }
454
455 std::string new_name(i->rename()->name()->string_view());
456 if (match_name.back() == '*') {
457 new_name += std::string(name->substr(match_name.size() - 1));
458 }
459 VLOG(1) << "Renamed \"" << *name << "\" to \"" << new_name << "\"";
460 *name = std::move(new_name);
461 }
462}
463
Austin Schuh40485ed2019-10-26 21:51:44 -0700464FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
Austin Schuhcb108412019-10-13 16:09:54 -0700465 const Flatbuffer<Configuration> &config) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700466 // auto_merge_config will contain all the fields of the Configuration that are
467 // to be passed through unmodified to the result of MergeConfiguration().
468 // In the processing below, we mutate auto_merge_config to remove any fields
469 // which we do need to alter (hence why we can't use the input config
470 // directly), and then merge auto_merge_config back in at the end.
471 aos::FlatbufferDetachedBuffer<aos::Configuration> auto_merge_config =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800472 aos::RecursiveCopyFlatBuffer(&config.message());
James Kuszmaul3c998592020-07-27 21:04:47 -0700473
Austin Schuh40485ed2019-10-26 21:51:44 -0700474 // Store all the channels in a sorted set. This lets us track channels we
Austin Schuhcb108412019-10-13 16:09:54 -0700475 // have seen before and merge the updates in.
Austin Schuh40485ed2019-10-26 21:51:44 -0700476 absl::btree_set<FlatbufferDetachedBuffer<Channel>> channels;
Austin Schuhcb108412019-10-13 16:09:54 -0700477
Austin Schuh40485ed2019-10-26 21:51:44 -0700478 if (config.message().has_channels()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700479 auto_merge_config.mutable_message()->clear_channels();
Austin Schuh40485ed2019-10-26 21:51:44 -0700480 for (const Channel *c : *config.message().channels()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700481 // Ignore malformed entries.
Austin Schuh40485ed2019-10-26 21:51:44 -0700482 if (!c->has_name()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700483 continue;
484 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700485 if (!c->has_type()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700486 continue;
487 }
488
Brian Silverman77162972020-08-12 19:52:40 -0700489 CHECK_EQ(c->read_method() == ReadMethod::PIN, c->num_readers() != 0)
490 << ": num_readers may be set if and only if read_method is PIN,"
491 " if you want 0 readers do not set PIN: "
492 << CleanedChannelToString(c);
493
Austin Schuh40485ed2019-10-26 21:51:44 -0700494 // Attempt to insert the channel.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800495 auto result = channels.insert(RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700496 if (!result.second) {
497 // Already there, so merge the new table into the original.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800498 *result.first =
499 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700500 }
501 }
502 }
503
504 // Now repeat this for the application list.
Austin Schuh40485ed2019-10-26 21:51:44 -0700505 absl::btree_set<FlatbufferDetachedBuffer<Application>> applications;
Austin Schuhcb108412019-10-13 16:09:54 -0700506 if (config.message().has_applications()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700507 auto_merge_config.mutable_message()->clear_applications();
Austin Schuhcb108412019-10-13 16:09:54 -0700508 for (const Application *a : *config.message().applications()) {
509 if (!a->has_name()) {
510 continue;
511 }
512
Austin Schuha4fc60f2020-11-01 23:06:47 -0800513 auto result = applications.insert(RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700514 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800515 *result.first =
516 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700517 }
518 }
519 }
520
Austin Schuh217a9782019-12-21 23:02:50 -0800521 // Now repeat this for the node list.
522 absl::btree_set<FlatbufferDetachedBuffer<Node>> nodes;
523 if (config.message().has_nodes()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700524 auto_merge_config.mutable_message()->clear_nodes();
Austin Schuh217a9782019-12-21 23:02:50 -0800525 for (const Node *n : *config.message().nodes()) {
526 if (!n->has_name()) {
527 continue;
528 }
529
Austin Schuha4fc60f2020-11-01 23:06:47 -0800530 auto result = nodes.insert(RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800531 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800532 *result.first =
533 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800534 }
535 }
536 }
537
Austin Schuhcb108412019-10-13 16:09:54 -0700538 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800539 fbb.ForceDefaults(true);
Austin Schuhcb108412019-10-13 16:09:54 -0700540
541 // Start by building the vectors. They need to come before the final table.
Austin Schuh40485ed2019-10-26 21:51:44 -0700542 // Channels
543 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
544 channels_offset;
Austin Schuhcb108412019-10-13 16:09:54 -0700545 {
Austin Schuh40485ed2019-10-26 21:51:44 -0700546 ::std::vector<flatbuffers::Offset<Channel>> channel_offsets;
547 for (const FlatbufferDetachedBuffer<Channel> &c : channels) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800548 channel_offsets.emplace_back(
549 RecursiveCopyFlatBuffer<Channel>(&c.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700550 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700551 channels_offset = fbb.CreateVector(channel_offsets);
Austin Schuhcb108412019-10-13 16:09:54 -0700552 }
553
554 // Applications
555 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
556 applications_offset;
557 {
558 ::std::vector<flatbuffers::Offset<Application>> applications_offsets;
Austin Schuh40485ed2019-10-26 21:51:44 -0700559 for (const FlatbufferDetachedBuffer<Application> &a : applications) {
Austin Schuhcb108412019-10-13 16:09:54 -0700560 applications_offsets.emplace_back(
Austin Schuha4fc60f2020-11-01 23:06:47 -0800561 RecursiveCopyFlatBuffer<Application>(&a.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700562 }
563 applications_offset = fbb.CreateVector(applications_offsets);
564 }
565
Austin Schuh217a9782019-12-21 23:02:50 -0800566 // Nodes
567 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
568 nodes_offset;
569 {
570 ::std::vector<flatbuffers::Offset<Node>> node_offsets;
571 for (const FlatbufferDetachedBuffer<Node> &n : nodes) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800572 node_offsets.emplace_back(
573 RecursiveCopyFlatBuffer<Node>(&n.message(), &fbb));
Austin Schuh217a9782019-12-21 23:02:50 -0800574 }
575 nodes_offset = fbb.CreateVector(node_offsets);
576 }
577
Austin Schuhcb108412019-10-13 16:09:54 -0700578 // And then build a Configuration with them all.
579 ConfigurationBuilder configuration_builder(fbb);
Austin Schuh40485ed2019-10-26 21:51:44 -0700580 configuration_builder.add_channels(channels_offset);
Austin Schuh217a9782019-12-21 23:02:50 -0800581 if (config.message().has_applications()) {
582 configuration_builder.add_applications(applications_offset);
583 }
584 if (config.message().has_nodes()) {
585 configuration_builder.add_nodes(nodes_offset);
586 }
Austin Schuhcb108412019-10-13 16:09:54 -0700587
588 fbb.Finish(configuration_builder.Finish());
Austin Schuh217a9782019-12-21 23:02:50 -0800589
James Kuszmaul3c998592020-07-27 21:04:47 -0700590 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
591 fbb.Release());
592
Austin Schuh217a9782019-12-21 23:02:50 -0800593 // Now, validate that if there is a node list, every channel has a source
594 // node.
James Kuszmaul3c998592020-07-27 21:04:47 -0700595 FlatbufferDetachedBuffer<Configuration> result =
596 MergeFlatBuffers(modified_config, auto_merge_config);
Austin Schuh217a9782019-12-21 23:02:50 -0800597
Austin Schuh15182322020-10-10 15:25:21 -0700598 ValidateConfiguration(result);
Austin Schuh217a9782019-12-21 23:02:50 -0800599
600 return result;
Austin Schuhcb108412019-10-13 16:09:54 -0700601}
602
Austin Schuh40485ed2019-10-26 21:51:44 -0700603FlatbufferDetachedBuffer<Configuration> ReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700604 const std::string_view path,
Austin Schuhef38cd22021-07-21 15:24:23 -0700605 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuhcb108412019-10-13 16:09:54 -0700606 // We only want to read a file once. So track the visited files in a set.
607 absl::btree_set<std::string> visited_paths;
Austin Schuh15182322020-10-10 15:25:21 -0700608 FlatbufferDetachedBuffer<Configuration> read_config =
Austin Schuhef38cd22021-07-21 15:24:23 -0700609 ReadConfig(path, &visited_paths, extra_import_paths);
Austin Schuh15182322020-10-10 15:25:21 -0700610
611 // If we only read one file, and it had a .bfbs extension, it has to be a
612 // fully formatted config. Do a quick verification and return it.
613 if (visited_paths.size() == 1 && EndsWith(*visited_paths.begin(), ".bfbs")) {
614 ValidateConfiguration(read_config);
615 return read_config;
616 }
617
618 return MergeConfiguration(read_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700619}
620
Austin Schuh8d6cea82020-02-28 12:17:16 -0800621FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Brian Silverman24f5aa82020-06-23 16:21:28 -0700622 const Configuration *config, const Flatbuffer<Configuration> &addition) {
623 return MergeConfiguration(MergeFlatBuffers(config, &addition.message()));
624}
625
626FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Austin Schuh8d6cea82020-02-28 12:17:16 -0800627 const Configuration *config, std::string_view json) {
628 FlatbufferDetachedBuffer<Configuration> addition =
629 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
630
Brian Silverman24f5aa82020-06-23 16:21:28 -0700631 return MergeWithConfig(config, addition);
Austin Schuh8d6cea82020-02-28 12:17:16 -0800632}
633
James Kuszmaul3ae42262019-11-08 12:33:41 -0800634const Channel *GetChannel(const Configuration *config, std::string_view name,
635 std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800636 std::string_view application_name, const Node *node,
637 bool quiet) {
Brian Silverman9fcf2c72020-12-21 18:30:58 -0800638 if (!config->has_channels()) {
639 return nullptr;
640 }
641
Austin Schuhbca6cf02019-12-22 17:28:34 -0800642 const std::string_view original_name = name;
Austin Schuhf1fff282020-03-28 16:57:32 -0700643 std::string mutable_name;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700644 if (node != nullptr) {
645 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
646 << "\" } on " << aos::FlatbufferToJson(node);
647 } else {
648 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
649 << "\" }";
650 }
Austin Schuhcb108412019-10-13 16:09:54 -0700651
652 // First handle application specific maps. Only do this if we have a matching
653 // application name, and it has maps.
Austin Schuhd2e2f6a2021-02-07 20:46:16 -0800654 {
655 const Application *application =
656 GetApplication(config, node, application_name);
657 if (application != nullptr && application->has_maps()) {
658 mutable_name = std::string(name);
659 HandleMaps(application->maps(), &mutable_name, type, node);
660 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700661 }
662 }
663
664 // Now do global maps.
Austin Schuh40485ed2019-10-26 21:51:44 -0700665 if (config->has_maps()) {
Austin Schuhf1fff282020-03-28 16:57:32 -0700666 mutable_name = std::string(name);
667 HandleMaps(config->maps(), &mutable_name, type, node);
668 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700669 }
670
Austin Schuhbca6cf02019-12-22 17:28:34 -0800671 if (original_name != name) {
672 VLOG(1) << "Remapped to { \"name\": \"" << name << "\", \"type\": \""
673 << type << "\" }";
674 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700675
James Kuszmaul71a81932020-12-15 21:08:01 -0800676 // Then look for the channel (note that this relies on the channels being
677 // sorted in the config).
Austin Schuh40485ed2019-10-26 21:51:44 -0700678 auto channel_iterator =
Austin Schuhf1fff282020-03-28 16:57:32 -0700679 std::lower_bound(config->channels()->cbegin(), config->channels()->cend(),
Austin Schuh40485ed2019-10-26 21:51:44 -0700680 std::make_pair(name, type), CompareChannels);
Austin Schuhcb108412019-10-13 16:09:54 -0700681
682 // Make sure we actually found it, and it matches.
Austin Schuh40485ed2019-10-26 21:51:44 -0700683 if (channel_iterator != config->channels()->cend() &&
684 EqualsChannels(*channel_iterator, std::make_pair(name, type))) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800685 if (VLOG_IS_ON(2)) {
686 VLOG(2) << "Found: " << FlatbufferToJson(*channel_iterator);
687 } else if (VLOG_IS_ON(1)) {
688 VLOG(1) << "Found: " << CleanedChannelToString(*channel_iterator);
689 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700690 return *channel_iterator;
Austin Schuhcb108412019-10-13 16:09:54 -0700691 } else {
692 VLOG(1) << "No match for { \"name\": \"" << name << "\", \"type\": \""
693 << type << "\" }";
Austin Schuh0de30f32020-12-06 12:44:28 -0800694 if (original_name != name && !quiet) {
Austin Schuh4b42b252020-10-19 11:35:20 -0700695 LOG(WARNING) << "Remapped from {\"name\": \"" << original_name
696 << "\", \"type\": \"" << type << "\"}, to {\"name\": \""
697 << name << "\", \"type\": \"" << type
698 << "\"}, but no channel by that name exists.";
699 }
Austin Schuhcb108412019-10-13 16:09:54 -0700700 return nullptr;
701 }
702}
703
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800704size_t ChannelIndex(const Configuration *configuration,
705 const Channel *channel) {
706 CHECK(configuration->channels() != nullptr) << ": No channels";
707
708 auto c = std::find(configuration->channels()->begin(),
709 configuration->channels()->end(), channel);
710 CHECK(c != configuration->channels()->end())
711 << ": Channel pointer not found in configuration()->channels()";
712
713 return std::distance(configuration->channels()->begin(), c);
714}
715
Austin Schuhbca6cf02019-12-22 17:28:34 -0800716std::string CleanedChannelToString(const Channel *channel) {
717 FlatbufferDetachedBuffer<Channel> cleaned_channel = CopyFlatBuffer(channel);
718 cleaned_channel.mutable_message()->clear_schema();
719 return FlatbufferToJson(cleaned_channel);
720}
721
Austin Schuha81454b2020-05-12 19:58:36 -0700722std::string StrippedChannelToString(const Channel *channel) {
723 return absl::StrCat("{ \"name\": \"", channel->name()->string_view(),
724 "\", \"type\": \"", channel->type()->string_view(),
725 "\" }");
726}
727
Alex Perrycb7da4b2019-08-28 19:35:56 -0700728FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
729 const Flatbuffer<Configuration> &config,
Austin Schuh0de30f32020-12-06 12:44:28 -0800730 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700731 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800732 fbb.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700733
Austin Schuh68d98592020-11-01 23:22:57 -0800734 // Cache for holding already inserted schemas.
735 std::map<std::string_view, flatbuffers::Offset<reflection::Schema>>
736 schema_cache;
737
738 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
739 << ": Merging logic needs to be updated when the number of channel "
740 "fields changes.";
James Kuszmaul3c998592020-07-27 21:04:47 -0700741
Alex Perrycb7da4b2019-08-28 19:35:56 -0700742 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
743 channels_offset;
744 if (config.message().has_channels()) {
745 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
746 for (const Channel *c : *config.message().channels()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700747 // Search for a schema with a matching type.
Austin Schuh0de30f32020-12-06 12:44:28 -0800748 const aos::FlatbufferVector<reflection::Schema> *found_schema = nullptr;
749 for (const aos::FlatbufferVector<reflection::Schema> &schema : schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700750 if (schema.message().root_table() != nullptr) {
751 if (schema.message().root_table()->name()->string_view() ==
752 c->type()->string_view()) {
753 found_schema = &schema;
754 }
755 }
756 }
757
758 CHECK(found_schema != nullptr)
759 << ": Failed to find schema for " << FlatbufferToJson(c);
760
Austin Schuh68d98592020-11-01 23:22:57 -0800761 // Now copy the message manually.
762 auto cached_schema = schema_cache.find(c->type()->string_view());
763 flatbuffers::Offset<reflection::Schema> schema_offset;
764 if (cached_schema != schema_cache.end()) {
765 schema_offset = cached_schema->second;
766 } else {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800767 schema_offset = RecursiveCopyFlatBuffer<reflection::Schema>(
768 &found_schema->message(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800769 schema_cache.emplace(c->type()->string_view(), schema_offset);
770 }
771
772 flatbuffers::Offset<flatbuffers::String> name_offset =
773 fbb.CreateSharedString(c->name()->str());
774 flatbuffers::Offset<flatbuffers::String> type_offset =
775 fbb.CreateSharedString(c->type()->str());
776 flatbuffers::Offset<flatbuffers::String> source_node_offset =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800777 c->has_source_node() ? fbb.CreateSharedString(c->source_node()->str())
778 : 0;
Austin Schuh68d98592020-11-01 23:22:57 -0800779
780 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
781 destination_nodes_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800782 aos::RecursiveCopyVectorTable(c->destination_nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800783
784 flatbuffers::Offset<
785 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
786 logger_nodes_offset =
787 aos::CopyVectorSharedString(c->logger_nodes(), &fbb);
788
789 Channel::Builder channel_builder(fbb);
790 channel_builder.add_name(name_offset);
791 channel_builder.add_type(type_offset);
792 if (c->has_frequency()) {
793 channel_builder.add_frequency(c->frequency());
794 }
795 if (c->has_max_size()) {
796 channel_builder.add_max_size(c->max_size());
797 }
798 if (c->has_num_senders()) {
799 channel_builder.add_num_senders(c->num_senders());
800 }
801 if (c->has_num_watchers()) {
802 channel_builder.add_num_watchers(c->num_watchers());
803 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700804 channel_builder.add_schema(schema_offset);
Austin Schuh68d98592020-11-01 23:22:57 -0800805 if (!source_node_offset.IsNull()) {
806 channel_builder.add_source_node(source_node_offset);
807 }
808 if (!destination_nodes_offset.IsNull()) {
809 channel_builder.add_destination_nodes(destination_nodes_offset);
810 }
811 if (c->has_logger()) {
812 channel_builder.add_logger(c->logger());
813 }
814 if (!logger_nodes_offset.IsNull()) {
815 channel_builder.add_logger_nodes(logger_nodes_offset);
816 }
817 if (c->has_read_method()) {
818 channel_builder.add_read_method(c->read_method());
819 }
820 if (c->has_num_readers()) {
821 channel_builder.add_num_readers(c->num_readers());
822 }
823 channel_offsets.emplace_back(channel_builder.Finish());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700824 }
825 channels_offset = fbb.CreateVector(channel_offsets);
826 }
827
Austin Schuh68d98592020-11-01 23:22:57 -0800828 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800829 maps_offset =
830 aos::RecursiveCopyVectorTable(config.message().maps(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800831
832 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800833 nodes_offset =
834 aos::RecursiveCopyVectorTable(config.message().nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800835
836 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
837 applications_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800838 aos::RecursiveCopyVectorTable(config.message().applications(), &fbb);
Austin Schuh217a9782019-12-21 23:02:50 -0800839
840 // Now insert everything else in unmodified.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700841 ConfigurationBuilder configuration_builder(fbb);
842 if (config.message().has_channels()) {
843 configuration_builder.add_channels(channels_offset);
844 }
Austin Schuh68d98592020-11-01 23:22:57 -0800845 if (!maps_offset.IsNull()) {
846 configuration_builder.add_maps(maps_offset);
847 }
848 if (!nodes_offset.IsNull()) {
849 configuration_builder.add_nodes(nodes_offset);
850 }
851 if (!applications_offset.IsNull()) {
852 configuration_builder.add_applications(applications_offset);
853 }
854
855 if (config.message().has_channel_storage_duration()) {
856 configuration_builder.add_channel_storage_duration(
857 config.message().channel_storage_duration());
858 }
859
860 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
861 << ": Merging logic needs to be updated when the number of configuration "
862 "fields changes.";
863
Alex Perrycb7da4b2019-08-28 19:35:56 -0700864 fbb.Finish(configuration_builder.Finish());
James Kuszmaul3c998592020-07-27 21:04:47 -0700865 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
866 fbb.Release());
867
Austin Schuh68d98592020-11-01 23:22:57 -0800868 return modified_config;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700869}
870
Austin Schuh217a9782019-12-21 23:02:50 -0800871const Node *GetNodeFromHostname(const Configuration *config,
872 std::string_view hostname) {
873 for (const Node *node : *config->nodes()) {
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800874 if (node->has_hostname() && node->hostname()->string_view() == hostname) {
Austin Schuh217a9782019-12-21 23:02:50 -0800875 return node;
876 }
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800877 if (node->has_hostnames()) {
878 for (const auto &candidate : *node->hostnames()) {
879 if (candidate->string_view() == hostname) {
880 return node;
881 }
882 }
883 }
Austin Schuh217a9782019-12-21 23:02:50 -0800884 }
885 return nullptr;
886}
Austin Schuhac0771c2020-01-07 18:36:30 -0800887
Austin Schuh217a9782019-12-21 23:02:50 -0800888const Node *GetMyNode(const Configuration *config) {
889 const std::string hostname = (FLAGS_override_hostname.size() > 0)
890 ? FLAGS_override_hostname
891 : network::GetHostname();
892 const Node *node = GetNodeFromHostname(config, hostname);
893 if (node != nullptr) return node;
894
895 LOG(FATAL) << "Unknown node for host: " << hostname
896 << ". Consider using --override_hostname if hostname detection "
897 "is wrong.";
898 return nullptr;
899}
900
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800901const Node *GetNode(const Configuration *config, const Node *node) {
902 if (!MultiNode(config)) {
903 CHECK(node == nullptr) << ": Provided a node in a single node world.";
904 return nullptr;
905 } else {
906 CHECK(node != nullptr);
907 CHECK(node->has_name());
908 return GetNode(config, node->name()->string_view());
909 }
910}
911
Austin Schuh217a9782019-12-21 23:02:50 -0800912const Node *GetNode(const Configuration *config, std::string_view name) {
Austin Schuhfd960622020-01-01 13:22:55 -0800913 CHECK(config->has_nodes())
914 << ": Asking for a node from a single node configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800915 for (const Node *node : *config->nodes()) {
Austin Schuhfd960622020-01-01 13:22:55 -0800916 CHECK(node->has_name()) << ": Malformed node " << FlatbufferToJson(node);
Austin Schuh217a9782019-12-21 23:02:50 -0800917 if (node->name()->string_view() == name) {
918 return node;
919 }
920 }
921 return nullptr;
922}
923
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800924const Node *GetNode(const Configuration *config, size_t node_index) {
925 if (!MultiNode(config)) {
926 CHECK_EQ(node_index, 0u) << ": Invalid node in a single node world.";
927 return nullptr;
928 } else {
929 CHECK_LT(node_index, config->nodes()->size());
930 return config->nodes()->Get(node_index);
931 }
932}
933
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800934const Node *GetNodeOrDie(const Configuration *config, const Node *node) {
935 if (!MultiNode(config)) {
936 CHECK(node == nullptr) << ": Provided a node in a single node world.";
937 return nullptr;
938 } else {
939 const Node *config_node = GetNode(config, node);
940 if (config_node == nullptr) {
941 LOG(FATAL) << "Couldn't find node matching " << FlatbufferToJson(node);
942 }
943 return config_node;
944 }
945}
946
Austin Schuh8bd96322020-02-13 21:18:22 -0800947namespace {
948int GetNodeIndexFromConfig(const Configuration *config, const Node *node) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800949 int node_index = 0;
950 for (const Node *iterated_node : *config->nodes()) {
951 if (iterated_node == node) {
952 return node_index;
953 }
954 ++node_index;
955 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800956 return -1;
957}
958} // namespace
959
Austin Schuha9df9ad2021-06-16 14:49:39 -0700960aos::FlatbufferDetachedBuffer<aos::Configuration> AddSchema(
961 std::string_view json,
962 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
963 FlatbufferDetachedBuffer<Configuration> addition =
964 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
965 return MergeConfiguration(addition, schemas);
966}
967
Austin Schuh8bd96322020-02-13 21:18:22 -0800968int GetNodeIndex(const Configuration *config, const Node *node) {
969 if (!MultiNode(config)) {
970 return 0;
971 }
972
973 {
974 int node_index = GetNodeIndexFromConfig(config, node);
975 if (node_index != -1) {
976 return node_index;
977 }
978 }
979
980 const Node *result = GetNode(config, node);
981 CHECK(result != nullptr);
982
983 {
Austin Schuh04408fc2020-02-16 21:48:54 -0800984 int node_index = GetNodeIndexFromConfig(config, result);
Austin Schuh8bd96322020-02-13 21:18:22 -0800985 if (node_index != -1) {
986 return node_index;
987 }
988 }
989
990 LOG(FATAL) << "Node " << FlatbufferToJson(node)
991 << " not found in the configuration.";
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800992}
993
Austin Schuh04408fc2020-02-16 21:48:54 -0800994int GetNodeIndex(const Configuration *config, std::string_view name) {
995 if (!MultiNode(config)) {
996 return 0;
997 }
998
999 {
1000 int node_index = 0;
1001 for (const Node *iterated_node : *config->nodes()) {
1002 if (iterated_node->name()->string_view() == name) {
1003 return node_index;
1004 }
1005 ++node_index;
1006 }
1007 }
1008 LOG(FATAL) << "Node " << name << " not found in the configuration.";
1009}
1010
Austin Schuh681a2472020-12-31 23:55:40 -08001011size_t NodesCount(const Configuration *config) {
1012 if (!MultiNode(config)) {
1013 return 1u;
1014 }
1015
1016 return config->nodes()->size();
1017}
1018
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001019std::vector<const Node *> GetNodes(const Configuration *config) {
1020 std::vector<const Node *> nodes;
Austin Schuh8bd96322020-02-13 21:18:22 -08001021 if (MultiNode(config)) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001022 for (const Node *node : *config->nodes()) {
1023 nodes.emplace_back(node);
1024 }
1025 } else {
1026 nodes.emplace_back(nullptr);
1027 }
1028 return nodes;
1029}
1030
Austin Schuh65465332020-11-05 17:36:53 -08001031std::vector<const Node *> GetNodesWithTag(const Configuration *config,
1032 std::string_view tag) {
1033 std::vector<const Node *> nodes;
1034 if (!MultiNode(config)) {
1035 nodes.emplace_back(nullptr);
1036 } else {
1037 for (const Node *node : *config->nodes()) {
1038 if (!node->has_tags()) {
1039 continue;
1040 }
1041 bool did_found_tag = false;
1042 for (const flatbuffers::String *found_tag : *node->tags()) {
1043 if (found_tag->string_view() == tag) {
1044 did_found_tag = true;
1045 break;
1046 }
1047 }
1048 if (did_found_tag) {
1049 nodes.emplace_back(node);
1050 }
1051 }
1052 }
1053 return nodes;
1054}
1055
Austin Schuhac0771c2020-01-07 18:36:30 -08001056bool MultiNode(const Configuration *config) { return config->has_nodes(); }
1057
Austin Schuh217a9782019-12-21 23:02:50 -08001058bool ChannelIsSendableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001059 if (node == nullptr) {
1060 return true;
1061 }
Austin Schuh3c5dae52020-10-06 18:55:18 -07001062 CHECK(channel->has_source_node()) << FlatbufferToJson(channel);
1063 CHECK(node->has_name()) << FlatbufferToJson(node);
Austin Schuh196a4452020-03-15 23:12:03 -07001064 return (CHECK_NOTNULL(channel)->source_node()->string_view() ==
1065 node->name()->string_view());
Austin Schuh217a9782019-12-21 23:02:50 -08001066}
1067
1068bool ChannelIsReadableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001069 if (node == nullptr) {
1070 return true;
1071 }
1072
Austin Schuh217a9782019-12-21 23:02:50 -08001073 if (channel->source_node()->string_view() == node->name()->string_view()) {
1074 return true;
1075 }
1076
1077 if (!channel->has_destination_nodes()) {
1078 return false;
1079 }
1080
Austin Schuh719946b2019-12-28 14:51:01 -08001081 for (const Connection *connection : *channel->destination_nodes()) {
1082 CHECK(connection->has_name());
1083 if (connection->name()->string_view() == node->name()->string_view()) {
Austin Schuh217a9782019-12-21 23:02:50 -08001084 return true;
1085 }
1086 }
1087
1088 return false;
1089}
1090
Austin Schuh719946b2019-12-28 14:51:01 -08001091bool ChannelMessageIsLoggedOnNode(const Channel *channel, const Node *node) {
Austin Schuh48e94502021-06-18 18:35:53 -07001092 if (node == nullptr) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001093 // Single node world. If there is a local logger, then we want to use
1094 // it.
Austin Schuh48e94502021-06-18 18:35:53 -07001095 if (channel->logger() == LoggerConfig::LOCAL_LOGGER) {
1096 return true;
1097 } else if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1098 return false;
1099 }
1100 LOG(FATAL) << "Unsupported logging configuration in a single node world: "
1101 << CleanedChannelToString(channel);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001102 }
1103 return ChannelMessageIsLoggedOnNode(
1104 channel, CHECK_NOTNULL(node)->name()->string_view());
1105}
1106
1107bool ChannelMessageIsLoggedOnNode(const Channel *channel,
1108 std::string_view node_name) {
Austin Schuhf1fff282020-03-28 16:57:32 -07001109 switch (channel->logger()) {
Austin Schuh719946b2019-12-28 14:51:01 -08001110 case LoggerConfig::LOCAL_LOGGER:
Austin Schuh2bb80e02021-03-20 21:46:17 -07001111 return channel->source_node()->string_view() == node_name;
Austin Schuh719946b2019-12-28 14:51:01 -08001112 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001113 CHECK(channel->has_logger_nodes());
1114 CHECK_GT(channel->logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001115
Austin Schuh2bb80e02021-03-20 21:46:17 -07001116 if (channel->source_node()->string_view() == node_name) {
Austin Schuh719946b2019-12-28 14:51:01 -08001117 return true;
1118 }
Austin Schuhda40e472020-03-28 15:15:29 -07001119
1120 [[fallthrough]];
1121 case LoggerConfig::REMOTE_LOGGER:
1122 CHECK(channel->has_logger_nodes());
1123 CHECK_GT(channel->logger_nodes()->size(), 0u);
1124 for (const flatbuffers::String *logger_node : *channel->logger_nodes()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001125 if (logger_node->string_view() == node_name) {
Austin Schuhda40e472020-03-28 15:15:29 -07001126 return true;
1127 }
Austin Schuh719946b2019-12-28 14:51:01 -08001128 }
1129
1130 return false;
1131 case LoggerConfig::NOT_LOGGED:
1132 return false;
1133 }
1134
1135 LOG(FATAL) << "Unknown logger config " << static_cast<int>(channel->logger());
1136}
1137
Austin Schuh58646e22021-08-23 23:51:46 -07001138size_t ConnectionCount(const Channel *channel) {
1139 if (!channel->has_destination_nodes()) {
1140 return 0;
1141 }
1142 return channel->destination_nodes()->size();
1143}
1144
Austin Schuh719946b2019-12-28 14:51:01 -08001145const Connection *ConnectionToNode(const Channel *channel, const Node *node) {
1146 if (!channel->has_destination_nodes()) {
1147 return nullptr;
1148 }
1149 for (const Connection *connection : *channel->destination_nodes()) {
1150 if (connection->name()->string_view() == node->name()->string_view()) {
1151 return connection;
1152 }
1153 }
1154 return nullptr;
1155}
1156
1157bool ConnectionDeliveryTimeIsLoggedOnNode(const Channel *channel,
1158 const Node *node,
1159 const Node *logger_node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001160 return ConnectionDeliveryTimeIsLoggedOnNode(ConnectionToNode(channel, node),
1161 logger_node);
Austin Schuh719946b2019-12-28 14:51:01 -08001162}
1163
1164bool ConnectionDeliveryTimeIsLoggedOnNode(const Connection *connection,
1165 const Node *node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001166 if (connection == nullptr) {
1167 return false;
1168 }
Austin Schuh719946b2019-12-28 14:51:01 -08001169 switch (connection->timestamp_logger()) {
1170 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001171 CHECK(connection->has_timestamp_logger_nodes());
1172 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001173 if (connection->name()->string_view() == node->name()->string_view()) {
1174 return true;
1175 }
1176
Austin Schuhda40e472020-03-28 15:15:29 -07001177 [[fallthrough]];
1178 case LoggerConfig::REMOTE_LOGGER:
1179 CHECK(connection->has_timestamp_logger_nodes());
1180 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
1181 for (const flatbuffers::String *timestamp_logger_node :
1182 *connection->timestamp_logger_nodes()) {
1183 if (timestamp_logger_node->string_view() ==
1184 node->name()->string_view()) {
1185 return true;
1186 }
Austin Schuh719946b2019-12-28 14:51:01 -08001187 }
1188
1189 return false;
1190 case LoggerConfig::LOCAL_LOGGER:
1191 return connection->name()->string_view() == node->name()->string_view();
Austin Schuh719946b2019-12-28 14:51:01 -08001192 case LoggerConfig::NOT_LOGGED:
1193 return false;
1194 }
1195
1196 LOG(FATAL) << "Unknown logger config "
1197 << static_cast<int>(connection->timestamp_logger());
1198}
1199
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001200std::vector<std::string_view> SourceNodeNames(const Configuration *config,
1201 const Node *my_node) {
1202 std::set<std::string_view> result_set;
1203
1204 for (const Channel *channel : *config->channels()) {
1205 if (channel->has_destination_nodes()) {
1206 for (const Connection *connection : *channel->destination_nodes()) {
1207 if (connection->name()->string_view() ==
1208 my_node->name()->string_view()) {
1209 result_set.insert(channel->source_node()->string_view());
1210 }
1211 }
1212 }
1213 }
1214
1215 std::vector<std::string_view> result;
1216 for (const std::string_view source : result_set) {
1217 VLOG(1) << "Found a source node of " << source;
1218 result.emplace_back(source);
1219 }
1220 return result;
1221}
1222
1223std::vector<std::string_view> DestinationNodeNames(const Configuration *config,
1224 const Node *my_node) {
1225 std::vector<std::string_view> result;
1226
1227 for (const Channel *channel : *config->channels()) {
1228 if (channel->has_source_node() && channel->source_node()->string_view() ==
1229 my_node->name()->string_view()) {
1230 if (!channel->has_destination_nodes()) continue;
1231
1232 if (channel->source_node()->string_view() !=
1233 my_node->name()->string_view()) {
1234 continue;
1235 }
1236
1237 for (const Connection *connection : *channel->destination_nodes()) {
1238 if (std::find(result.begin(), result.end(),
1239 connection->name()->string_view()) == result.end()) {
1240 result.emplace_back(connection->name()->string_view());
1241 }
1242 }
1243 }
1244 }
1245
1246 for (const std::string_view destination : result) {
1247 VLOG(1) << "Found a destination node of " << destination;
1248 }
1249 return result;
1250}
1251
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001252std::vector<const Node *> TimestampNodes(const Configuration *config,
1253 const Node *my_node) {
1254 if (!configuration::MultiNode(config)) {
1255 CHECK(my_node == nullptr);
1256 return std::vector<const Node *>{};
1257 }
1258
1259 std::set<const Node *> timestamp_logger_nodes;
1260 for (const Channel *channel : *config->channels()) {
1261 if (!configuration::ChannelIsSendableOnNode(channel, my_node)) {
1262 continue;
1263 }
1264 if (!channel->has_destination_nodes()) {
1265 continue;
1266 }
1267 for (const Connection *connection : *channel->destination_nodes()) {
1268 const Node *other_node =
1269 configuration::GetNode(config, connection->name()->string_view());
1270
1271 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
1272 my_node)) {
1273 VLOG(1) << "Timestamps are logged from "
1274 << FlatbufferToJson(other_node);
1275 timestamp_logger_nodes.insert(other_node);
1276 }
1277 }
1278 }
1279
1280 std::vector<const Node *> result;
1281 for (const Node *node : timestamp_logger_nodes) {
1282 result.emplace_back(node);
1283 }
1284 return result;
1285}
1286
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001287const Application *GetApplication(const Configuration *config,
1288 const Node *my_node,
1289 std::string_view application_name) {
1290 if (config->has_applications()) {
1291 auto application_iterator = std::lower_bound(
1292 config->applications()->cbegin(), config->applications()->cend(),
1293 application_name, CompareApplications);
1294 if (application_iterator != config->applications()->cend() &&
1295 EqualsApplications(*application_iterator, application_name)) {
1296 if (MultiNode(config)) {
1297 // Ok, we need
1298 CHECK(application_iterator->has_nodes());
1299 CHECK(my_node != nullptr);
1300 for (const flatbuffers::String *str : *application_iterator->nodes()) {
1301 if (str->string_view() == my_node->name()->string_view()) {
1302 return *application_iterator;
1303 }
1304 }
1305 } else {
1306 return *application_iterator;
1307 }
1308 }
1309 }
1310 return nullptr;
1311}
1312
Austin Schuhfc7b6a02021-07-12 21:19:07 -07001313std::vector<size_t> SourceNodeIndex(const Configuration *config) {
1314 CHECK(config->has_channels());
1315 std::vector<size_t> result;
1316 result.resize(config->channels()->size(), 0u);
1317 if (MultiNode(config)) {
1318 for (size_t i = 0; i < config->channels()->size(); ++i) {
1319 result[i] = GetNodeIndex(
1320 config, config->channels()->Get(i)->source_node()->string_view());
1321 }
1322 }
1323 return result;
1324}
1325
Brian Silverman66f079a2013-08-26 16:24:30 -07001326} // namespace configuration
1327} // namespace aos