blob: 8d9dbf7781124c1f6877628e1f3b57c1f00337da [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
Austin Schuh40485ed2019-10-26 21:51:44 -0700172FlatbufferDetachedBuffer<Configuration> ReadConfig(
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] == '/';
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700184 if (path_is_absolute) {
185 CHECK(extra_import_paths.empty())
186 << "Can't specify extra import paths if attempting to read a config "
187 "file from an absolute path (path is "
Austin Schuh15182322020-10-10 15:25:21 -0700188 << raw_path << ").";
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700189 }
190
191 bool found_path = false;
192 for (const auto &import_path : extra_import_paths) {
Austin Schuhef38cd22021-07-21 15:24:23 -0700193 raw_path = std::string(import_path) + "/" + RemoveDotDots(path);
Austin Schuh15182322020-10-10 15:25:21 -0700194 binary_path = MaybeReplaceExtension(raw_path, ".json", ".bfbs");
Austin Schuhef38cd22021-07-21 15:24:23 -0700195 VLOG(1) << "Checking: " << binary_path;
Austin Schuh15182322020-10-10 15:25:21 -0700196 binary_path_exists = util::PathExists(binary_path);
197 if (binary_path_exists) {
198 found_path = true;
199 break;
200 }
Austin Schuhef38cd22021-07-21 15:24:23 -0700201 VLOG(1) << "Checking: " << raw_path;
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700202 if (util::PathExists(raw_path)) {
203 found_path = true;
204 break;
205 }
206 }
207 CHECK(found_path) << ": Failed to find file " << path << ".";
208 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209
Austin Schuh15182322020-10-10 15:25:21 -0700210 FlatbufferDetachedBuffer<Configuration> config = ReadConfigFile(
211 binary_path_exists ? binary_path : raw_path, binary_path_exists);
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700212
Austin Schuhcb108412019-10-13 16:09:54 -0700213 // Depth first. Take the following example:
214 //
215 // config1.json:
216 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700217 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700218 // {
219 // "name": "/foo",
220 // "type": ".aos.bar",
221 // "max_size": 5
222 // }
223 // ],
224 // "imports": [
225 // "config2.json",
226 // ]
227 // }
228 //
229 // config2.json:
230 // {
Austin Schuh40485ed2019-10-26 21:51:44 -0700231 // "channels": [
Austin Schuhcb108412019-10-13 16:09:54 -0700232 // {
233 // "name": "/foo",
234 // "type": ".aos.bar",
235 // "max_size": 7
236 // }
237 // ],
238 // }
239 //
240 // We want the main config (config1.json) to be able to override the imported
241 // config. That means that it needs to be merged into the imported configs,
242 // not the other way around.
243
Austin Schuh15182322020-10-10 15:25:21 -0700244 const std::string absolute_path =
245 AbsolutePath(binary_path_exists ? binary_path : raw_path);
246 // Track that we have seen this file before recursing. Track the path we
247 // actually loaded (which should be consistent if imported twice).
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700248 if (!visited_paths->insert(absolute_path).second) {
249 for (const auto &visited_path : *visited_paths) {
250 LOG(INFO) << "Already visited: " << visited_path;
251 }
252 LOG(FATAL)
253 << "Already imported " << path << " (i.e. " << absolute_path
254 << "). See above for the files that have already been processed.";
255 }
Austin Schuhcb108412019-10-13 16:09:54 -0700256
257 if (config.message().has_imports()) {
258 // Capture the imports.
259 const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *v =
260 config.message().imports();
261
262 // And then wipe them. This gets GCed when we merge later.
263 config.mutable_message()->clear_imports();
264
265 // Start with an empty configuration to merge into.
Austin Schuh40485ed2019-10-26 21:51:44 -0700266 FlatbufferDetachedBuffer<Configuration> merged_config =
267 FlatbufferDetachedBuffer<Configuration>::Empty();
Austin Schuhcb108412019-10-13 16:09:54 -0700268
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700269 const std::string path_folder(ExtractFolder(path));
Austin Schuhcb108412019-10-13 16:09:54 -0700270 for (const flatbuffers::String *str : *v) {
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700271 const std::string included_config =
272 path_folder + "/" + std::string(str->string_view());
Austin Schuhcb108412019-10-13 16:09:54 -0700273
274 // And them merge everything in.
275 merged_config = MergeFlatBuffers(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700276 merged_config,
277 ReadConfig(included_config, visited_paths, extra_import_paths));
Austin Schuhcb108412019-10-13 16:09:54 -0700278 }
279
280 // Finally, merge this file in.
281 config = MergeFlatBuffers(merged_config, config);
282 }
283 return config;
284}
285
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286// Compares (c < p) a channel, and a name, type tuple.
287bool CompareChannels(const Channel *c,
James Kuszmaul3ae42262019-11-08 12:33:41 -0800288 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289 int name_compare = c->name()->string_view().compare(p.first);
290 if (name_compare == 0) {
291 return c->type()->string_view() < p.second;
292 } else if (name_compare < 0) {
293 return true;
294 } else {
295 return false;
296 }
297};
298
299// Compares for equality (c == p) a channel, and a name, type tuple.
300bool EqualsChannels(const Channel *c,
Austin Schuhf1fff282020-03-28 16:57:32 -0700301 ::std::pair<std::string_view, std::string_view> p) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700302 return c->name()->string_view() == p.first &&
303 c->type()->string_view() == p.second;
304}
305
306// Compares (c < p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800307bool CompareApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 return a->name()->string_view() < name;
309};
310
311// Compares for equality (c == p) an application, and a name;
James Kuszmaul3ae42262019-11-08 12:33:41 -0800312bool EqualsApplications(const Application *a, std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313 return a->name()->string_view() == name;
314}
315
Austin Schuh15182322020-10-10 15:25:21 -0700316void ValidateConfiguration(const Flatbuffer<Configuration> &config) {
317 // No imports should be left.
318 CHECK(!config.message().has_imports());
319
320 // Check that if there is a node list, all the source nodes are filled out and
321 // valid, and all the destination nodes are valid (and not the source). This
322 // is a basic consistency check.
323 if (config.message().has_channels()) {
324 const Channel *last_channel = nullptr;
325 for (const Channel *c : *config.message().channels()) {
326 CHECK(c->has_name());
327 CHECK(c->has_type());
328 if (c->name()->string_view().back() == '/') {
329 LOG(FATAL) << "Channel names can't end with '/'";
330 }
331 if (c->name()->string_view().find("//") != std::string_view::npos) {
332 LOG(FATAL) << ": Invalid channel name " << c->name()->string_view()
333 << ", can't use //.";
334 }
335 for (const char data : c->name()->string_view()) {
336 if (data >= '0' && data <= '9') {
337 continue;
338 }
339 if (data >= 'a' && data <= 'z') {
340 continue;
341 }
342 if (data >= 'A' && data <= 'Z') {
343 continue;
344 }
345 if (data == '-' || data == '_' || data == '/') {
346 continue;
347 }
348 LOG(FATAL) << "Invalid channel name " << c->name()->string_view()
349 << ", can only use [-a-zA-Z0-9_/]";
350 }
351
Austin Schuha156fb22021-10-11 19:23:21 -0700352 if (c->has_logger_nodes()) {
353 // Confirm that we don't have duplicate logger nodes.
354 absl::btree_set<std::string_view> logger_nodes;
355 for (const flatbuffers::String *s : *c->logger_nodes()) {
356 logger_nodes.insert(s->string_view());
357 }
358 CHECK_EQ(static_cast<size_t>(logger_nodes.size()),
359 c->logger_nodes()->size())
360 << ": Found duplicate logger_nodes in "
361 << CleanedChannelToString(c);
362 }
363
364 if (c->has_destination_nodes()) {
365 // Confirm that we don't have duplicate timestamp logger nodes.
Austin Schuh5e95bd62021-10-11 18:40:22 -0700366 for (const Connection *d : *c->destination_nodes()) {
Austin Schuha156fb22021-10-11 19:23:21 -0700367 if (d->has_timestamp_logger_nodes()) {
368 absl::btree_set<std::string_view> timestamp_logger_nodes;
369 for (const flatbuffers::String *s : *d->timestamp_logger_nodes()) {
370 timestamp_logger_nodes.insert(s->string_view());
371 }
372 CHECK_EQ(static_cast<size_t>(timestamp_logger_nodes.size()),
373 d->timestamp_logger_nodes()->size())
374 << ": Found duplicate timestamp_logger_nodes in "
375 << CleanedChannelToString(c);
376 }
377 }
378
379 // There is no good use case today for logging timestamps but not the
380 // corresponding data. Instead of plumbing through all of this on the
381 // reader side, let'd just disallow it for now.
382 if (c->logger() == LoggerConfig::NOT_LOGGED) {
383 for (const Connection *d : *c->destination_nodes()) {
384 CHECK(d->timestamp_logger() == LoggerConfig::NOT_LOGGED)
385 << ": Logging timestamps without data is not supported. If "
386 "you have a good use case, let's talk. "
387 << CleanedChannelToString(c);
388 }
Austin Schuh5e95bd62021-10-11 18:40:22 -0700389 }
390 }
391
Austin Schuh15182322020-10-10 15:25:21 -0700392 // Make sure everything is sorted while we are here... If this fails,
393 // there will be a bunch of weird errors.
394 if (last_channel != nullptr) {
395 CHECK(CompareChannels(
396 last_channel,
397 std::make_pair(c->name()->string_view(), c->type()->string_view())))
398 << ": Channels not sorted!";
399 }
400 last_channel = c;
401 }
402 }
403
404 if (config.message().has_nodes() && config.message().has_channels()) {
405 for (const Channel *c : *config.message().channels()) {
406 CHECK(c->has_source_node()) << ": Channel " << FlatbufferToJson(c)
407 << " is missing \"source_node\"";
408 CHECK(GetNode(&config.message(), c->source_node()->string_view()) !=
409 nullptr)
410 << ": Channel " << FlatbufferToJson(c)
411 << " has an unknown \"source_node\"";
412
413 if (c->has_destination_nodes()) {
414 for (const Connection *connection : *c->destination_nodes()) {
415 CHECK(connection->has_name());
416 CHECK(GetNode(&config.message(), connection->name()->string_view()) !=
417 nullptr)
418 << ": Channel " << FlatbufferToJson(c)
419 << " has an unknown \"destination_nodes\" "
420 << connection->name()->string_view();
421
422 switch (connection->timestamp_logger()) {
423 case LoggerConfig::LOCAL_LOGGER:
424 case LoggerConfig::NOT_LOGGED:
425 CHECK(!connection->has_timestamp_logger_nodes());
426 break;
427 case LoggerConfig::REMOTE_LOGGER:
428 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
429 CHECK(connection->has_timestamp_logger_nodes());
430 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
431 for (const flatbuffers::String *timestamp_logger_node :
432 *connection->timestamp_logger_nodes()) {
433 CHECK(GetNode(&config.message(),
434 timestamp_logger_node->string_view()) != nullptr)
435 << ": Channel " << FlatbufferToJson(c)
436 << " has an unknown \"timestamp_logger_node\""
437 << connection->name()->string_view();
438 }
439 break;
440 }
441
442 CHECK_NE(connection->name()->string_view(),
443 c->source_node()->string_view())
444 << ": Channel " << FlatbufferToJson(c)
445 << " is forwarding data to itself";
446 }
447 }
448 }
449 }
450}
451
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452} // namespace
453
Austin Schuh006a9f52021-04-07 16:24:18 -0700454// Maps name for the provided maps. Modifies name.
455void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
456 std::string *name, std::string_view type, const Node *node) {
457 // For the same reason we merge configs in reverse order, we want to process
458 // maps in reverse order. That lets the outer config overwrite channels from
459 // the inner configs.
460 for (auto i = maps->rbegin(); i != maps->rend(); ++i) {
461 if (!i->has_match() || !i->match()->has_name()) {
462 continue;
463 }
464 if (!i->has_rename() || !i->rename()->has_name()) {
465 continue;
466 }
467
468 // Handle normal maps (now that we know that match and rename are filled
469 // out).
470 const std::string_view match_name = i->match()->name()->string_view();
471 if (match_name != *name) {
472 if (match_name.back() == '*' &&
473 std::string_view(*name).substr(
474 0, std::min(name->size(), match_name.size() - 1)) ==
475 match_name.substr(0, match_name.size() - 1)) {
476 CHECK_EQ(match_name.find('*'), match_name.size() - 1);
477 } else {
478 continue;
479 }
480 }
481
482 // Handle type specific maps.
483 if (i->match()->has_type() && i->match()->type()->string_view() != type) {
484 continue;
485 }
486
487 // Now handle node specific maps.
488 if (node != nullptr && i->match()->has_source_node() &&
489 i->match()->source_node()->string_view() !=
490 node->name()->string_view()) {
491 continue;
492 }
493
494 std::string new_name(i->rename()->name()->string_view());
495 if (match_name.back() == '*') {
496 new_name += std::string(name->substr(match_name.size() - 1));
497 }
498 VLOG(1) << "Renamed \"" << *name << "\" to \"" << new_name << "\"";
499 *name = std::move(new_name);
500 }
501}
502
Austin Schuh40485ed2019-10-26 21:51:44 -0700503FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
Austin Schuhcb108412019-10-13 16:09:54 -0700504 const Flatbuffer<Configuration> &config) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700505 // auto_merge_config will contain all the fields of the Configuration that are
506 // to be passed through unmodified to the result of MergeConfiguration().
507 // In the processing below, we mutate auto_merge_config to remove any fields
508 // which we do need to alter (hence why we can't use the input config
509 // directly), and then merge auto_merge_config back in at the end.
510 aos::FlatbufferDetachedBuffer<aos::Configuration> auto_merge_config =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800511 aos::RecursiveCopyFlatBuffer(&config.message());
James Kuszmaul3c998592020-07-27 21:04:47 -0700512
Austin Schuh40485ed2019-10-26 21:51:44 -0700513 // Store all the channels in a sorted set. This lets us track channels we
Austin Schuhcb108412019-10-13 16:09:54 -0700514 // have seen before and merge the updates in.
Austin Schuh40485ed2019-10-26 21:51:44 -0700515 absl::btree_set<FlatbufferDetachedBuffer<Channel>> channels;
Austin Schuhcb108412019-10-13 16:09:54 -0700516
Austin Schuh40485ed2019-10-26 21:51:44 -0700517 if (config.message().has_channels()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700518 auto_merge_config.mutable_message()->clear_channels();
Austin Schuh40485ed2019-10-26 21:51:44 -0700519 for (const Channel *c : *config.message().channels()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700520 // Ignore malformed entries.
Austin Schuh40485ed2019-10-26 21:51:44 -0700521 if (!c->has_name()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700522 continue;
523 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700524 if (!c->has_type()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700525 continue;
526 }
527
Brian Silverman77162972020-08-12 19:52:40 -0700528 CHECK_EQ(c->read_method() == ReadMethod::PIN, c->num_readers() != 0)
529 << ": num_readers may be set if and only if read_method is PIN,"
530 " if you want 0 readers do not set PIN: "
531 << CleanedChannelToString(c);
532
Austin Schuh40485ed2019-10-26 21:51:44 -0700533 // Attempt to insert the channel.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800534 auto result = channels.insert(RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700535 if (!result.second) {
536 // Already there, so merge the new table into the original.
Austin Schuh4a5f5d22021-10-12 15:09:35 -0700537 // Schemas merge poorly, so pick the newest one.
538 if (result.first->message().has_schema() && c->has_schema()) {
539 result.first->mutable_message()->clear_schema();
540 }
Austin Schuha7996eb2021-10-11 19:03:24 -0700541 auto merged =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800542 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(c));
Austin Schuha7996eb2021-10-11 19:03:24 -0700543
544 if (merged.message().has_destination_nodes()) {
545 absl::btree_set<FlatbufferDetachedBuffer<Connection>> connections;
546 for (const Connection *connection :
547 *merged.message().destination_nodes()) {
548 auto connection_result =
549 connections.insert(RecursiveCopyFlatBuffer(connection));
550 if (!connection_result.second) {
551 *connection_result.first =
552 MergeFlatBuffers(*connection_result.first,
553 RecursiveCopyFlatBuffer(connection));
554 }
555 }
556 if (static_cast<size_t>(connections.size()) !=
557 merged.message().destination_nodes()->size()) {
558 merged.mutable_message()->clear_destination_nodes();
559 flatbuffers::FlatBufferBuilder fbb;
560 fbb.ForceDefaults(true);
561 std::vector<flatbuffers::Offset<Connection>> connection_offsets;
562 for (const FlatbufferDetachedBuffer<Connection> &connection :
563 connections) {
564 connection_offsets.push_back(
565 RecursiveCopyFlatBuffer(&connection.message(), &fbb));
566 }
567 flatbuffers::Offset<
568 flatbuffers::Vector<flatbuffers::Offset<Connection>>>
569 destination_nodes_offset = fbb.CreateVector(connection_offsets);
570 Channel::Builder channel_builder(fbb);
571 channel_builder.add_destination_nodes(destination_nodes_offset);
572 fbb.Finish(channel_builder.Finish());
573 FlatbufferDetachedBuffer<Channel> destinations_channel(
574 fbb.Release());
575 merged = MergeFlatBuffers(merged, destinations_channel);
576 }
577 }
578
579 *result.first = std::move(merged);
Austin Schuhcb108412019-10-13 16:09:54 -0700580 }
581 }
582 }
583
584 // Now repeat this for the application list.
Austin Schuh40485ed2019-10-26 21:51:44 -0700585 absl::btree_set<FlatbufferDetachedBuffer<Application>> applications;
Austin Schuhcb108412019-10-13 16:09:54 -0700586 if (config.message().has_applications()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700587 auto_merge_config.mutable_message()->clear_applications();
Austin Schuhcb108412019-10-13 16:09:54 -0700588 for (const Application *a : *config.message().applications()) {
589 if (!a->has_name()) {
590 continue;
591 }
592
Austin Schuha4fc60f2020-11-01 23:06:47 -0800593 auto result = applications.insert(RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700594 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800595 *result.first =
596 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700597 }
598 }
599 }
600
Austin Schuh217a9782019-12-21 23:02:50 -0800601 // Now repeat this for the node list.
602 absl::btree_set<FlatbufferDetachedBuffer<Node>> nodes;
603 if (config.message().has_nodes()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700604 auto_merge_config.mutable_message()->clear_nodes();
Austin Schuh217a9782019-12-21 23:02:50 -0800605 for (const Node *n : *config.message().nodes()) {
606 if (!n->has_name()) {
607 continue;
608 }
609
Austin Schuha4fc60f2020-11-01 23:06:47 -0800610 auto result = nodes.insert(RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800611 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800612 *result.first =
613 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800614 }
615 }
616 }
617
Austin Schuhcb108412019-10-13 16:09:54 -0700618 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800619 fbb.ForceDefaults(true);
Austin Schuhcb108412019-10-13 16:09:54 -0700620
621 // Start by building the vectors. They need to come before the final table.
Austin Schuh40485ed2019-10-26 21:51:44 -0700622 // Channels
623 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
624 channels_offset;
Austin Schuhcb108412019-10-13 16:09:54 -0700625 {
Austin Schuh40485ed2019-10-26 21:51:44 -0700626 ::std::vector<flatbuffers::Offset<Channel>> channel_offsets;
627 for (const FlatbufferDetachedBuffer<Channel> &c : channels) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800628 channel_offsets.emplace_back(
629 RecursiveCopyFlatBuffer<Channel>(&c.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700630 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700631 channels_offset = fbb.CreateVector(channel_offsets);
Austin Schuhcb108412019-10-13 16:09:54 -0700632 }
633
634 // Applications
635 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
636 applications_offset;
637 {
638 ::std::vector<flatbuffers::Offset<Application>> applications_offsets;
Austin Schuh40485ed2019-10-26 21:51:44 -0700639 for (const FlatbufferDetachedBuffer<Application> &a : applications) {
Austin Schuhcb108412019-10-13 16:09:54 -0700640 applications_offsets.emplace_back(
Austin Schuha4fc60f2020-11-01 23:06:47 -0800641 RecursiveCopyFlatBuffer<Application>(&a.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700642 }
643 applications_offset = fbb.CreateVector(applications_offsets);
644 }
645
Austin Schuh217a9782019-12-21 23:02:50 -0800646 // Nodes
647 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
648 nodes_offset;
649 {
650 ::std::vector<flatbuffers::Offset<Node>> node_offsets;
651 for (const FlatbufferDetachedBuffer<Node> &n : nodes) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800652 node_offsets.emplace_back(
653 RecursiveCopyFlatBuffer<Node>(&n.message(), &fbb));
Austin Schuh217a9782019-12-21 23:02:50 -0800654 }
655 nodes_offset = fbb.CreateVector(node_offsets);
656 }
657
Austin Schuhcb108412019-10-13 16:09:54 -0700658 // And then build a Configuration with them all.
659 ConfigurationBuilder configuration_builder(fbb);
Austin Schuh40485ed2019-10-26 21:51:44 -0700660 configuration_builder.add_channels(channels_offset);
Austin Schuh217a9782019-12-21 23:02:50 -0800661 if (config.message().has_applications()) {
662 configuration_builder.add_applications(applications_offset);
663 }
664 if (config.message().has_nodes()) {
665 configuration_builder.add_nodes(nodes_offset);
666 }
Austin Schuhcb108412019-10-13 16:09:54 -0700667
668 fbb.Finish(configuration_builder.Finish());
Austin Schuh217a9782019-12-21 23:02:50 -0800669
James Kuszmaul3c998592020-07-27 21:04:47 -0700670 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
671 fbb.Release());
672
Austin Schuh217a9782019-12-21 23:02:50 -0800673 // Now, validate that if there is a node list, every channel has a source
674 // node.
James Kuszmaul3c998592020-07-27 21:04:47 -0700675 FlatbufferDetachedBuffer<Configuration> result =
676 MergeFlatBuffers(modified_config, auto_merge_config);
Austin Schuh217a9782019-12-21 23:02:50 -0800677
Austin Schuh15182322020-10-10 15:25:21 -0700678 ValidateConfiguration(result);
Austin Schuh217a9782019-12-21 23:02:50 -0800679
680 return result;
Austin Schuhcb108412019-10-13 16:09:54 -0700681}
682
Austin Schuh40485ed2019-10-26 21:51:44 -0700683FlatbufferDetachedBuffer<Configuration> ReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700684 const std::string_view path,
Austin Schuhef38cd22021-07-21 15:24:23 -0700685 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuhcb108412019-10-13 16:09:54 -0700686 // We only want to read a file once. So track the visited files in a set.
687 absl::btree_set<std::string> visited_paths;
Austin Schuh15182322020-10-10 15:25:21 -0700688 FlatbufferDetachedBuffer<Configuration> read_config =
Austin Schuhef38cd22021-07-21 15:24:23 -0700689 ReadConfig(path, &visited_paths, extra_import_paths);
Austin Schuh15182322020-10-10 15:25:21 -0700690
691 // If we only read one file, and it had a .bfbs extension, it has to be a
692 // fully formatted config. Do a quick verification and return it.
693 if (visited_paths.size() == 1 && EndsWith(*visited_paths.begin(), ".bfbs")) {
694 ValidateConfiguration(read_config);
695 return read_config;
696 }
697
698 return MergeConfiguration(read_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700699}
700
Austin Schuh8d6cea82020-02-28 12:17:16 -0800701FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Brian Silverman24f5aa82020-06-23 16:21:28 -0700702 const Configuration *config, const Flatbuffer<Configuration> &addition) {
703 return MergeConfiguration(MergeFlatBuffers(config, &addition.message()));
704}
705
706FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Austin Schuh8d6cea82020-02-28 12:17:16 -0800707 const Configuration *config, std::string_view json) {
708 FlatbufferDetachedBuffer<Configuration> addition =
709 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
710
Brian Silverman24f5aa82020-06-23 16:21:28 -0700711 return MergeWithConfig(config, addition);
Austin Schuh8d6cea82020-02-28 12:17:16 -0800712}
713
James Kuszmaul3ae42262019-11-08 12:33:41 -0800714const Channel *GetChannel(const Configuration *config, std::string_view name,
715 std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800716 std::string_view application_name, const Node *node,
717 bool quiet) {
Brian Silverman9fcf2c72020-12-21 18:30:58 -0800718 if (!config->has_channels()) {
719 return nullptr;
720 }
721
Austin Schuhbca6cf02019-12-22 17:28:34 -0800722 const std::string_view original_name = name;
Austin Schuhf1fff282020-03-28 16:57:32 -0700723 std::string mutable_name;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700724 if (node != nullptr) {
725 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
726 << "\" } on " << aos::FlatbufferToJson(node);
727 } else {
728 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
729 << "\" }";
730 }
Austin Schuhcb108412019-10-13 16:09:54 -0700731
732 // First handle application specific maps. Only do this if we have a matching
733 // application name, and it has maps.
Austin Schuhd2e2f6a2021-02-07 20:46:16 -0800734 {
735 const Application *application =
736 GetApplication(config, node, application_name);
737 if (application != nullptr && application->has_maps()) {
738 mutable_name = std::string(name);
739 HandleMaps(application->maps(), &mutable_name, type, node);
740 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700741 }
742 }
743
744 // Now do global maps.
Austin Schuh40485ed2019-10-26 21:51:44 -0700745 if (config->has_maps()) {
Austin Schuhf1fff282020-03-28 16:57:32 -0700746 mutable_name = std::string(name);
747 HandleMaps(config->maps(), &mutable_name, type, node);
748 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700749 }
750
Austin Schuhbca6cf02019-12-22 17:28:34 -0800751 if (original_name != name) {
752 VLOG(1) << "Remapped to { \"name\": \"" << name << "\", \"type\": \""
753 << type << "\" }";
754 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700755
James Kuszmaul71a81932020-12-15 21:08:01 -0800756 // Then look for the channel (note that this relies on the channels being
757 // sorted in the config).
Austin Schuh40485ed2019-10-26 21:51:44 -0700758 auto channel_iterator =
Austin Schuhf1fff282020-03-28 16:57:32 -0700759 std::lower_bound(config->channels()->cbegin(), config->channels()->cend(),
Austin Schuh40485ed2019-10-26 21:51:44 -0700760 std::make_pair(name, type), CompareChannels);
Austin Schuhcb108412019-10-13 16:09:54 -0700761
762 // Make sure we actually found it, and it matches.
Austin Schuh40485ed2019-10-26 21:51:44 -0700763 if (channel_iterator != config->channels()->cend() &&
764 EqualsChannels(*channel_iterator, std::make_pair(name, type))) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800765 if (VLOG_IS_ON(2)) {
766 VLOG(2) << "Found: " << FlatbufferToJson(*channel_iterator);
767 } else if (VLOG_IS_ON(1)) {
768 VLOG(1) << "Found: " << CleanedChannelToString(*channel_iterator);
769 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700770 return *channel_iterator;
Austin Schuhcb108412019-10-13 16:09:54 -0700771 } else {
772 VLOG(1) << "No match for { \"name\": \"" << name << "\", \"type\": \""
773 << type << "\" }";
Austin Schuh0de30f32020-12-06 12:44:28 -0800774 if (original_name != name && !quiet) {
Austin Schuh4b42b252020-10-19 11:35:20 -0700775 LOG(WARNING) << "Remapped from {\"name\": \"" << original_name
776 << "\", \"type\": \"" << type << "\"}, to {\"name\": \""
777 << name << "\", \"type\": \"" << type
778 << "\"}, but no channel by that name exists.";
779 }
Austin Schuhcb108412019-10-13 16:09:54 -0700780 return nullptr;
781 }
782}
783
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800784size_t ChannelIndex(const Configuration *configuration,
785 const Channel *channel) {
786 CHECK(configuration->channels() != nullptr) << ": No channels";
787
Brian Silvermana9698c92021-11-10 12:27:04 -0800788 const auto c = std::lower_bound(
789 configuration->channels()->cbegin(), configuration->channels()->cend(),
790 std::make_pair(channel->name()->string_view(),
791 channel->type()->string_view()),
792 CompareChannels);
793 CHECK(c != configuration->channels()->cend())
794 << ": Channel pointer not found in configuration()->channels()";
795 CHECK(*c == channel)
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800796 << ": Channel pointer not found in configuration()->channels()";
797
Brian Silvermana9698c92021-11-10 12:27:04 -0800798 return std::distance(configuration->channels()->cbegin(), c);
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800799}
800
Austin Schuhbca6cf02019-12-22 17:28:34 -0800801std::string CleanedChannelToString(const Channel *channel) {
802 FlatbufferDetachedBuffer<Channel> cleaned_channel = CopyFlatBuffer(channel);
803 cleaned_channel.mutable_message()->clear_schema();
804 return FlatbufferToJson(cleaned_channel);
805}
806
Austin Schuha81454b2020-05-12 19:58:36 -0700807std::string StrippedChannelToString(const Channel *channel) {
808 return absl::StrCat("{ \"name\": \"", channel->name()->string_view(),
809 "\", \"type\": \"", channel->type()->string_view(),
810 "\" }");
811}
812
Alex Perrycb7da4b2019-08-28 19:35:56 -0700813FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
814 const Flatbuffer<Configuration> &config,
Austin Schuh0de30f32020-12-06 12:44:28 -0800815 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700816 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800817 fbb.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700818
Austin Schuh68d98592020-11-01 23:22:57 -0800819 // Cache for holding already inserted schemas.
820 std::map<std::string_view, flatbuffers::Offset<reflection::Schema>>
821 schema_cache;
822
823 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
824 << ": Merging logic needs to be updated when the number of channel "
825 "fields changes.";
James Kuszmaul3c998592020-07-27 21:04:47 -0700826
Alex Perrycb7da4b2019-08-28 19:35:56 -0700827 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
828 channels_offset;
829 if (config.message().has_channels()) {
830 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
831 for (const Channel *c : *config.message().channels()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700832 // Search for a schema with a matching type.
Austin Schuh0de30f32020-12-06 12:44:28 -0800833 const aos::FlatbufferVector<reflection::Schema> *found_schema = nullptr;
834 for (const aos::FlatbufferVector<reflection::Schema> &schema : schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700835 if (schema.message().root_table() != nullptr) {
836 if (schema.message().root_table()->name()->string_view() ==
837 c->type()->string_view()) {
838 found_schema = &schema;
839 }
840 }
841 }
842
843 CHECK(found_schema != nullptr)
844 << ": Failed to find schema for " << FlatbufferToJson(c);
845
Austin Schuh68d98592020-11-01 23:22:57 -0800846 // Now copy the message manually.
847 auto cached_schema = schema_cache.find(c->type()->string_view());
848 flatbuffers::Offset<reflection::Schema> schema_offset;
849 if (cached_schema != schema_cache.end()) {
850 schema_offset = cached_schema->second;
851 } else {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800852 schema_offset = RecursiveCopyFlatBuffer<reflection::Schema>(
853 &found_schema->message(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800854 schema_cache.emplace(c->type()->string_view(), schema_offset);
855 }
856
857 flatbuffers::Offset<flatbuffers::String> name_offset =
858 fbb.CreateSharedString(c->name()->str());
859 flatbuffers::Offset<flatbuffers::String> type_offset =
860 fbb.CreateSharedString(c->type()->str());
861 flatbuffers::Offset<flatbuffers::String> source_node_offset =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800862 c->has_source_node() ? fbb.CreateSharedString(c->source_node()->str())
863 : 0;
Austin Schuh68d98592020-11-01 23:22:57 -0800864
865 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
866 destination_nodes_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800867 aos::RecursiveCopyVectorTable(c->destination_nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800868
869 flatbuffers::Offset<
870 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
871 logger_nodes_offset =
872 aos::CopyVectorSharedString(c->logger_nodes(), &fbb);
873
874 Channel::Builder channel_builder(fbb);
875 channel_builder.add_name(name_offset);
876 channel_builder.add_type(type_offset);
877 if (c->has_frequency()) {
878 channel_builder.add_frequency(c->frequency());
879 }
880 if (c->has_max_size()) {
881 channel_builder.add_max_size(c->max_size());
882 }
883 if (c->has_num_senders()) {
884 channel_builder.add_num_senders(c->num_senders());
885 }
886 if (c->has_num_watchers()) {
887 channel_builder.add_num_watchers(c->num_watchers());
888 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700889 channel_builder.add_schema(schema_offset);
Austin Schuh68d98592020-11-01 23:22:57 -0800890 if (!source_node_offset.IsNull()) {
891 channel_builder.add_source_node(source_node_offset);
892 }
893 if (!destination_nodes_offset.IsNull()) {
894 channel_builder.add_destination_nodes(destination_nodes_offset);
895 }
896 if (c->has_logger()) {
897 channel_builder.add_logger(c->logger());
898 }
899 if (!logger_nodes_offset.IsNull()) {
900 channel_builder.add_logger_nodes(logger_nodes_offset);
901 }
902 if (c->has_read_method()) {
903 channel_builder.add_read_method(c->read_method());
904 }
905 if (c->has_num_readers()) {
906 channel_builder.add_num_readers(c->num_readers());
907 }
908 channel_offsets.emplace_back(channel_builder.Finish());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700909 }
910 channels_offset = fbb.CreateVector(channel_offsets);
911 }
912
Austin Schuh68d98592020-11-01 23:22:57 -0800913 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800914 maps_offset =
915 aos::RecursiveCopyVectorTable(config.message().maps(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800916
917 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800918 nodes_offset =
919 aos::RecursiveCopyVectorTable(config.message().nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800920
921 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
922 applications_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800923 aos::RecursiveCopyVectorTable(config.message().applications(), &fbb);
Austin Schuh217a9782019-12-21 23:02:50 -0800924
925 // Now insert everything else in unmodified.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700926 ConfigurationBuilder configuration_builder(fbb);
927 if (config.message().has_channels()) {
928 configuration_builder.add_channels(channels_offset);
929 }
Austin Schuh68d98592020-11-01 23:22:57 -0800930 if (!maps_offset.IsNull()) {
931 configuration_builder.add_maps(maps_offset);
932 }
933 if (!nodes_offset.IsNull()) {
934 configuration_builder.add_nodes(nodes_offset);
935 }
936 if (!applications_offset.IsNull()) {
937 configuration_builder.add_applications(applications_offset);
938 }
939
940 if (config.message().has_channel_storage_duration()) {
941 configuration_builder.add_channel_storage_duration(
942 config.message().channel_storage_duration());
943 }
944
945 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
946 << ": Merging logic needs to be updated when the number of configuration "
947 "fields changes.";
948
Alex Perrycb7da4b2019-08-28 19:35:56 -0700949 fbb.Finish(configuration_builder.Finish());
James Kuszmaul3c998592020-07-27 21:04:47 -0700950 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
951 fbb.Release());
952
Austin Schuh68d98592020-11-01 23:22:57 -0800953 return modified_config;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700954}
955
Austin Schuh217a9782019-12-21 23:02:50 -0800956const Node *GetNodeFromHostname(const Configuration *config,
957 std::string_view hostname) {
958 for (const Node *node : *config->nodes()) {
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800959 if (node->has_hostname() && node->hostname()->string_view() == hostname) {
Austin Schuh217a9782019-12-21 23:02:50 -0800960 return node;
961 }
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800962 if (node->has_hostnames()) {
963 for (const auto &candidate : *node->hostnames()) {
964 if (candidate->string_view() == hostname) {
965 return node;
966 }
967 }
968 }
Austin Schuh217a9782019-12-21 23:02:50 -0800969 }
970 return nullptr;
971}
Austin Schuhac0771c2020-01-07 18:36:30 -0800972
Austin Schuh217a9782019-12-21 23:02:50 -0800973const Node *GetMyNode(const Configuration *config) {
974 const std::string hostname = (FLAGS_override_hostname.size() > 0)
975 ? FLAGS_override_hostname
976 : network::GetHostname();
977 const Node *node = GetNodeFromHostname(config, hostname);
978 if (node != nullptr) return node;
979
980 LOG(FATAL) << "Unknown node for host: " << hostname
981 << ". Consider using --override_hostname if hostname detection "
982 "is wrong.";
983 return nullptr;
984}
985
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800986const Node *GetNode(const Configuration *config, const Node *node) {
987 if (!MultiNode(config)) {
988 CHECK(node == nullptr) << ": Provided a node in a single node world.";
989 return nullptr;
990 } else {
991 CHECK(node != nullptr);
992 CHECK(node->has_name());
993 return GetNode(config, node->name()->string_view());
994 }
995}
996
Austin Schuh217a9782019-12-21 23:02:50 -0800997const Node *GetNode(const Configuration *config, std::string_view name) {
Austin Schuhfd960622020-01-01 13:22:55 -0800998 CHECK(config->has_nodes())
999 << ": Asking for a node from a single node configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -08001000 for (const Node *node : *config->nodes()) {
Austin Schuhfd960622020-01-01 13:22:55 -08001001 CHECK(node->has_name()) << ": Malformed node " << FlatbufferToJson(node);
Austin Schuh217a9782019-12-21 23:02:50 -08001002 if (node->name()->string_view() == name) {
1003 return node;
1004 }
1005 }
1006 return nullptr;
1007}
1008
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001009const Node *GetNode(const Configuration *config, size_t node_index) {
1010 if (!MultiNode(config)) {
1011 CHECK_EQ(node_index, 0u) << ": Invalid node in a single node world.";
1012 return nullptr;
1013 } else {
1014 CHECK_LT(node_index, config->nodes()->size());
1015 return config->nodes()->Get(node_index);
1016 }
1017}
1018
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001019const Node *GetNodeOrDie(const Configuration *config, const Node *node) {
1020 if (!MultiNode(config)) {
1021 CHECK(node == nullptr) << ": Provided a node in a single node world.";
1022 return nullptr;
1023 } else {
1024 const Node *config_node = GetNode(config, node);
1025 if (config_node == nullptr) {
1026 LOG(FATAL) << "Couldn't find node matching " << FlatbufferToJson(node);
1027 }
1028 return config_node;
1029 }
1030}
1031
Austin Schuh8bd96322020-02-13 21:18:22 -08001032namespace {
1033int GetNodeIndexFromConfig(const Configuration *config, const Node *node) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001034 int node_index = 0;
1035 for (const Node *iterated_node : *config->nodes()) {
1036 if (iterated_node == node) {
1037 return node_index;
1038 }
1039 ++node_index;
1040 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001041 return -1;
1042}
1043} // namespace
1044
Austin Schuha9df9ad2021-06-16 14:49:39 -07001045aos::FlatbufferDetachedBuffer<aos::Configuration> AddSchema(
1046 std::string_view json,
1047 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
1048 FlatbufferDetachedBuffer<Configuration> addition =
1049 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
1050 return MergeConfiguration(addition, schemas);
1051}
1052
Austin Schuh8bd96322020-02-13 21:18:22 -08001053int GetNodeIndex(const Configuration *config, const Node *node) {
1054 if (!MultiNode(config)) {
1055 return 0;
1056 }
1057
1058 {
1059 int node_index = GetNodeIndexFromConfig(config, node);
1060 if (node_index != -1) {
1061 return node_index;
1062 }
1063 }
1064
1065 const Node *result = GetNode(config, node);
1066 CHECK(result != nullptr);
1067
1068 {
Austin Schuh04408fc2020-02-16 21:48:54 -08001069 int node_index = GetNodeIndexFromConfig(config, result);
Austin Schuh8bd96322020-02-13 21:18:22 -08001070 if (node_index != -1) {
1071 return node_index;
1072 }
1073 }
1074
1075 LOG(FATAL) << "Node " << FlatbufferToJson(node)
1076 << " not found in the configuration.";
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001077}
1078
Austin Schuh04408fc2020-02-16 21:48:54 -08001079int GetNodeIndex(const Configuration *config, std::string_view name) {
1080 if (!MultiNode(config)) {
1081 return 0;
1082 }
1083
1084 {
1085 int node_index = 0;
1086 for (const Node *iterated_node : *config->nodes()) {
1087 if (iterated_node->name()->string_view() == name) {
1088 return node_index;
1089 }
1090 ++node_index;
1091 }
1092 }
1093 LOG(FATAL) << "Node " << name << " not found in the configuration.";
1094}
1095
Austin Schuh681a2472020-12-31 23:55:40 -08001096size_t NodesCount(const Configuration *config) {
1097 if (!MultiNode(config)) {
1098 return 1u;
1099 }
1100
1101 return config->nodes()->size();
1102}
1103
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001104std::vector<const Node *> GetNodes(const Configuration *config) {
1105 std::vector<const Node *> nodes;
Austin Schuh8bd96322020-02-13 21:18:22 -08001106 if (MultiNode(config)) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001107 for (const Node *node : *config->nodes()) {
1108 nodes.emplace_back(node);
1109 }
1110 } else {
1111 nodes.emplace_back(nullptr);
1112 }
1113 return nodes;
1114}
1115
Austin Schuh65465332020-11-05 17:36:53 -08001116std::vector<const Node *> GetNodesWithTag(const Configuration *config,
1117 std::string_view tag) {
1118 std::vector<const Node *> nodes;
1119 if (!MultiNode(config)) {
1120 nodes.emplace_back(nullptr);
1121 } else {
1122 for (const Node *node : *config->nodes()) {
1123 if (!node->has_tags()) {
1124 continue;
1125 }
1126 bool did_found_tag = false;
1127 for (const flatbuffers::String *found_tag : *node->tags()) {
1128 if (found_tag->string_view() == tag) {
1129 did_found_tag = true;
1130 break;
1131 }
1132 }
1133 if (did_found_tag) {
1134 nodes.emplace_back(node);
1135 }
1136 }
1137 }
1138 return nodes;
1139}
1140
Austin Schuhac0771c2020-01-07 18:36:30 -08001141bool MultiNode(const Configuration *config) { return config->has_nodes(); }
1142
Austin Schuh217a9782019-12-21 23:02:50 -08001143bool ChannelIsSendableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001144 if (node == nullptr) {
1145 return true;
1146 }
Austin Schuh3c5dae52020-10-06 18:55:18 -07001147 CHECK(channel->has_source_node()) << FlatbufferToJson(channel);
1148 CHECK(node->has_name()) << FlatbufferToJson(node);
Austin Schuh196a4452020-03-15 23:12:03 -07001149 return (CHECK_NOTNULL(channel)->source_node()->string_view() ==
1150 node->name()->string_view());
Austin Schuh217a9782019-12-21 23:02:50 -08001151}
1152
1153bool ChannelIsReadableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001154 if (node == nullptr) {
1155 return true;
1156 }
1157
Austin Schuh217a9782019-12-21 23:02:50 -08001158 if (channel->source_node()->string_view() == node->name()->string_view()) {
1159 return true;
1160 }
1161
1162 if (!channel->has_destination_nodes()) {
1163 return false;
1164 }
1165
Austin Schuh719946b2019-12-28 14:51:01 -08001166 for (const Connection *connection : *channel->destination_nodes()) {
1167 CHECK(connection->has_name());
1168 if (connection->name()->string_view() == node->name()->string_view()) {
Austin Schuh217a9782019-12-21 23:02:50 -08001169 return true;
1170 }
1171 }
1172
1173 return false;
1174}
1175
Austin Schuh719946b2019-12-28 14:51:01 -08001176bool ChannelMessageIsLoggedOnNode(const Channel *channel, const Node *node) {
Austin Schuh48e94502021-06-18 18:35:53 -07001177 if (node == nullptr) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001178 // Single node world. If there is a local logger, then we want to use
1179 // it.
Austin Schuh48e94502021-06-18 18:35:53 -07001180 if (channel->logger() == LoggerConfig::LOCAL_LOGGER) {
1181 return true;
1182 } else if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1183 return false;
1184 }
1185 LOG(FATAL) << "Unsupported logging configuration in a single node world: "
1186 << CleanedChannelToString(channel);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001187 }
1188 return ChannelMessageIsLoggedOnNode(
1189 channel, CHECK_NOTNULL(node)->name()->string_view());
1190}
1191
1192bool ChannelMessageIsLoggedOnNode(const Channel *channel,
1193 std::string_view node_name) {
Austin Schuhf1fff282020-03-28 16:57:32 -07001194 switch (channel->logger()) {
Austin Schuh719946b2019-12-28 14:51:01 -08001195 case LoggerConfig::LOCAL_LOGGER:
Austin Schuh2bb80e02021-03-20 21:46:17 -07001196 return channel->source_node()->string_view() == node_name;
Austin Schuh719946b2019-12-28 14:51:01 -08001197 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001198 CHECK(channel->has_logger_nodes());
1199 CHECK_GT(channel->logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001200
Austin Schuh2bb80e02021-03-20 21:46:17 -07001201 if (channel->source_node()->string_view() == node_name) {
Austin Schuh719946b2019-12-28 14:51:01 -08001202 return true;
1203 }
Austin Schuhda40e472020-03-28 15:15:29 -07001204
1205 [[fallthrough]];
1206 case LoggerConfig::REMOTE_LOGGER:
1207 CHECK(channel->has_logger_nodes());
1208 CHECK_GT(channel->logger_nodes()->size(), 0u);
1209 for (const flatbuffers::String *logger_node : *channel->logger_nodes()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001210 if (logger_node->string_view() == node_name) {
Austin Schuhda40e472020-03-28 15:15:29 -07001211 return true;
1212 }
Austin Schuh719946b2019-12-28 14:51:01 -08001213 }
1214
1215 return false;
1216 case LoggerConfig::NOT_LOGGED:
1217 return false;
1218 }
1219
1220 LOG(FATAL) << "Unknown logger config " << static_cast<int>(channel->logger());
1221}
1222
Austin Schuh58646e22021-08-23 23:51:46 -07001223size_t ConnectionCount(const Channel *channel) {
1224 if (!channel->has_destination_nodes()) {
1225 return 0;
1226 }
1227 return channel->destination_nodes()->size();
1228}
1229
Austin Schuh719946b2019-12-28 14:51:01 -08001230const Connection *ConnectionToNode(const Channel *channel, const Node *node) {
1231 if (!channel->has_destination_nodes()) {
1232 return nullptr;
1233 }
1234 for (const Connection *connection : *channel->destination_nodes()) {
1235 if (connection->name()->string_view() == node->name()->string_view()) {
1236 return connection;
1237 }
1238 }
1239 return nullptr;
1240}
1241
1242bool ConnectionDeliveryTimeIsLoggedOnNode(const Channel *channel,
1243 const Node *node,
1244 const Node *logger_node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001245 return ConnectionDeliveryTimeIsLoggedOnNode(ConnectionToNode(channel, node),
1246 logger_node);
Austin Schuh719946b2019-12-28 14:51:01 -08001247}
1248
1249bool ConnectionDeliveryTimeIsLoggedOnNode(const Connection *connection,
1250 const Node *node) {
Austin Schuh72211ae2021-08-05 14:02:30 -07001251 if (connection == nullptr) {
1252 return false;
1253 }
Austin Schuh719946b2019-12-28 14:51:01 -08001254 switch (connection->timestamp_logger()) {
1255 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001256 CHECK(connection->has_timestamp_logger_nodes());
1257 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001258 if (connection->name()->string_view() == node->name()->string_view()) {
1259 return true;
1260 }
1261
Austin Schuhda40e472020-03-28 15:15:29 -07001262 [[fallthrough]];
1263 case LoggerConfig::REMOTE_LOGGER:
1264 CHECK(connection->has_timestamp_logger_nodes());
1265 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
1266 for (const flatbuffers::String *timestamp_logger_node :
1267 *connection->timestamp_logger_nodes()) {
1268 if (timestamp_logger_node->string_view() ==
1269 node->name()->string_view()) {
1270 return true;
1271 }
Austin Schuh719946b2019-12-28 14:51:01 -08001272 }
1273
1274 return false;
1275 case LoggerConfig::LOCAL_LOGGER:
1276 return connection->name()->string_view() == node->name()->string_view();
Austin Schuh719946b2019-12-28 14:51:01 -08001277 case LoggerConfig::NOT_LOGGED:
1278 return false;
1279 }
1280
1281 LOG(FATAL) << "Unknown logger config "
1282 << static_cast<int>(connection->timestamp_logger());
1283}
1284
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001285std::vector<std::string_view> SourceNodeNames(const Configuration *config,
1286 const Node *my_node) {
1287 std::set<std::string_view> result_set;
1288
1289 for (const Channel *channel : *config->channels()) {
1290 if (channel->has_destination_nodes()) {
1291 for (const Connection *connection : *channel->destination_nodes()) {
1292 if (connection->name()->string_view() ==
1293 my_node->name()->string_view()) {
1294 result_set.insert(channel->source_node()->string_view());
1295 }
1296 }
1297 }
1298 }
1299
1300 std::vector<std::string_view> result;
1301 for (const std::string_view source : result_set) {
1302 VLOG(1) << "Found a source node of " << source;
1303 result.emplace_back(source);
1304 }
1305 return result;
1306}
1307
1308std::vector<std::string_view> DestinationNodeNames(const Configuration *config,
1309 const Node *my_node) {
1310 std::vector<std::string_view> result;
1311
1312 for (const Channel *channel : *config->channels()) {
1313 if (channel->has_source_node() && channel->source_node()->string_view() ==
1314 my_node->name()->string_view()) {
1315 if (!channel->has_destination_nodes()) continue;
1316
1317 if (channel->source_node()->string_view() !=
1318 my_node->name()->string_view()) {
1319 continue;
1320 }
1321
1322 for (const Connection *connection : *channel->destination_nodes()) {
1323 if (std::find(result.begin(), result.end(),
1324 connection->name()->string_view()) == result.end()) {
1325 result.emplace_back(connection->name()->string_view());
1326 }
1327 }
1328 }
1329 }
1330
1331 for (const std::string_view destination : result) {
1332 VLOG(1) << "Found a destination node of " << destination;
1333 }
1334 return result;
1335}
1336
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001337std::vector<const Node *> TimestampNodes(const Configuration *config,
1338 const Node *my_node) {
1339 if (!configuration::MultiNode(config)) {
1340 CHECK(my_node == nullptr);
1341 return std::vector<const Node *>{};
1342 }
1343
1344 std::set<const Node *> timestamp_logger_nodes;
1345 for (const Channel *channel : *config->channels()) {
1346 if (!configuration::ChannelIsSendableOnNode(channel, my_node)) {
1347 continue;
1348 }
1349 if (!channel->has_destination_nodes()) {
1350 continue;
1351 }
1352 for (const Connection *connection : *channel->destination_nodes()) {
1353 const Node *other_node =
1354 configuration::GetNode(config, connection->name()->string_view());
1355
1356 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
1357 my_node)) {
1358 VLOG(1) << "Timestamps are logged from "
1359 << FlatbufferToJson(other_node);
1360 timestamp_logger_nodes.insert(other_node);
1361 }
1362 }
1363 }
1364
1365 std::vector<const Node *> result;
1366 for (const Node *node : timestamp_logger_nodes) {
1367 result.emplace_back(node);
1368 }
1369 return result;
1370}
1371
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001372bool ApplicationShouldStart(const Configuration *config, const Node *my_node,
1373 const Application *application) {
1374 if (MultiNode(config)) {
1375 // Ok, we need
1376 CHECK(application->has_nodes());
1377 CHECK(my_node != nullptr);
1378 for (const flatbuffers::String *str : *application->nodes()) {
1379 if (str->string_view() == my_node->name()->string_view()) {
1380 return true;
1381 }
1382 }
1383 return false;
1384 } else {
1385 return true;
1386 }
1387}
1388
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001389const Application *GetApplication(const Configuration *config,
1390 const Node *my_node,
1391 std::string_view application_name) {
1392 if (config->has_applications()) {
1393 auto application_iterator = std::lower_bound(
1394 config->applications()->cbegin(), config->applications()->cend(),
1395 application_name, CompareApplications);
1396 if (application_iterator != config->applications()->cend() &&
1397 EqualsApplications(*application_iterator, application_name)) {
Austin Schuhc41fa3c2021-10-16 14:35:35 -07001398 if (ApplicationShouldStart(config, my_node, *application_iterator)) {
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001399 return *application_iterator;
1400 }
1401 }
1402 }
1403 return nullptr;
1404}
1405
Austin Schuhfc7b6a02021-07-12 21:19:07 -07001406std::vector<size_t> SourceNodeIndex(const Configuration *config) {
1407 CHECK(config->has_channels());
1408 std::vector<size_t> result;
1409 result.resize(config->channels()->size(), 0u);
1410 if (MultiNode(config)) {
1411 for (size_t i = 0; i < config->channels()->size(); ++i) {
1412 result[i] = GetNodeIndex(
1413 config, config->channels()->Get(i)->source_node()->string_view());
1414 }
1415 }
1416 return result;
1417}
1418
Brian Silverman66f079a2013-08-26 16:24:30 -07001419} // namespace configuration
1420} // namespace aos