blob: 7fad440f2c4cc05656083518c34086fc7546f7ed [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
340 // Make sure everything is sorted while we are here... If this fails,
341 // there will be a bunch of weird errors.
342 if (last_channel != nullptr) {
343 CHECK(CompareChannels(
344 last_channel,
345 std::make_pair(c->name()->string_view(), c->type()->string_view())))
346 << ": Channels not sorted!";
347 }
348 last_channel = c;
349 }
350 }
351
352 if (config.message().has_nodes() && config.message().has_channels()) {
353 for (const Channel *c : *config.message().channels()) {
354 CHECK(c->has_source_node()) << ": Channel " << FlatbufferToJson(c)
355 << " is missing \"source_node\"";
356 CHECK(GetNode(&config.message(), c->source_node()->string_view()) !=
357 nullptr)
358 << ": Channel " << FlatbufferToJson(c)
359 << " has an unknown \"source_node\"";
360
361 if (c->has_destination_nodes()) {
362 for (const Connection *connection : *c->destination_nodes()) {
363 CHECK(connection->has_name());
364 CHECK(GetNode(&config.message(), connection->name()->string_view()) !=
365 nullptr)
366 << ": Channel " << FlatbufferToJson(c)
367 << " has an unknown \"destination_nodes\" "
368 << connection->name()->string_view();
369
370 switch (connection->timestamp_logger()) {
371 case LoggerConfig::LOCAL_LOGGER:
372 case LoggerConfig::NOT_LOGGED:
373 CHECK(!connection->has_timestamp_logger_nodes());
374 break;
375 case LoggerConfig::REMOTE_LOGGER:
376 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
377 CHECK(connection->has_timestamp_logger_nodes());
378 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
379 for (const flatbuffers::String *timestamp_logger_node :
380 *connection->timestamp_logger_nodes()) {
381 CHECK(GetNode(&config.message(),
382 timestamp_logger_node->string_view()) != nullptr)
383 << ": Channel " << FlatbufferToJson(c)
384 << " has an unknown \"timestamp_logger_node\""
385 << connection->name()->string_view();
386 }
387 break;
388 }
389
390 CHECK_NE(connection->name()->string_view(),
391 c->source_node()->string_view())
392 << ": Channel " << FlatbufferToJson(c)
393 << " is forwarding data to itself";
394 }
395 }
396 }
397 }
398}
399
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400} // namespace
401
Austin Schuh006a9f52021-04-07 16:24:18 -0700402// Maps name for the provided maps. Modifies name.
403void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
404 std::string *name, std::string_view type, const Node *node) {
405 // For the same reason we merge configs in reverse order, we want to process
406 // maps in reverse order. That lets the outer config overwrite channels from
407 // the inner configs.
408 for (auto i = maps->rbegin(); i != maps->rend(); ++i) {
409 if (!i->has_match() || !i->match()->has_name()) {
410 continue;
411 }
412 if (!i->has_rename() || !i->rename()->has_name()) {
413 continue;
414 }
415
416 // Handle normal maps (now that we know that match and rename are filled
417 // out).
418 const std::string_view match_name = i->match()->name()->string_view();
419 if (match_name != *name) {
420 if (match_name.back() == '*' &&
421 std::string_view(*name).substr(
422 0, std::min(name->size(), match_name.size() - 1)) ==
423 match_name.substr(0, match_name.size() - 1)) {
424 CHECK_EQ(match_name.find('*'), match_name.size() - 1);
425 } else {
426 continue;
427 }
428 }
429
430 // Handle type specific maps.
431 if (i->match()->has_type() && i->match()->type()->string_view() != type) {
432 continue;
433 }
434
435 // Now handle node specific maps.
436 if (node != nullptr && i->match()->has_source_node() &&
437 i->match()->source_node()->string_view() !=
438 node->name()->string_view()) {
439 continue;
440 }
441
442 std::string new_name(i->rename()->name()->string_view());
443 if (match_name.back() == '*') {
444 new_name += std::string(name->substr(match_name.size() - 1));
445 }
446 VLOG(1) << "Renamed \"" << *name << "\" to \"" << new_name << "\"";
447 *name = std::move(new_name);
448 }
449}
450
Austin Schuh40485ed2019-10-26 21:51:44 -0700451FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
Austin Schuhcb108412019-10-13 16:09:54 -0700452 const Flatbuffer<Configuration> &config) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700453 // auto_merge_config will contain all the fields of the Configuration that are
454 // to be passed through unmodified to the result of MergeConfiguration().
455 // In the processing below, we mutate auto_merge_config to remove any fields
456 // which we do need to alter (hence why we can't use the input config
457 // directly), and then merge auto_merge_config back in at the end.
458 aos::FlatbufferDetachedBuffer<aos::Configuration> auto_merge_config =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800459 aos::RecursiveCopyFlatBuffer(&config.message());
James Kuszmaul3c998592020-07-27 21:04:47 -0700460
Austin Schuh40485ed2019-10-26 21:51:44 -0700461 // Store all the channels in a sorted set. This lets us track channels we
Austin Schuhcb108412019-10-13 16:09:54 -0700462 // have seen before and merge the updates in.
Austin Schuh40485ed2019-10-26 21:51:44 -0700463 absl::btree_set<FlatbufferDetachedBuffer<Channel>> channels;
Austin Schuhcb108412019-10-13 16:09:54 -0700464
Austin Schuh40485ed2019-10-26 21:51:44 -0700465 if (config.message().has_channels()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700466 auto_merge_config.mutable_message()->clear_channels();
Austin Schuh40485ed2019-10-26 21:51:44 -0700467 for (const Channel *c : *config.message().channels()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700468 // Ignore malformed entries.
Austin Schuh40485ed2019-10-26 21:51:44 -0700469 if (!c->has_name()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700470 continue;
471 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700472 if (!c->has_type()) {
Austin Schuhcb108412019-10-13 16:09:54 -0700473 continue;
474 }
475
Brian Silverman77162972020-08-12 19:52:40 -0700476 CHECK_EQ(c->read_method() == ReadMethod::PIN, c->num_readers() != 0)
477 << ": num_readers may be set if and only if read_method is PIN,"
478 " if you want 0 readers do not set PIN: "
479 << CleanedChannelToString(c);
480
Austin Schuh40485ed2019-10-26 21:51:44 -0700481 // Attempt to insert the channel.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800482 auto result = channels.insert(RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700483 if (!result.second) {
484 // Already there, so merge the new table into the original.
Austin Schuha4fc60f2020-11-01 23:06:47 -0800485 *result.first =
486 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(c));
Austin Schuhcb108412019-10-13 16:09:54 -0700487 }
488 }
489 }
490
491 // Now repeat this for the application list.
Austin Schuh40485ed2019-10-26 21:51:44 -0700492 absl::btree_set<FlatbufferDetachedBuffer<Application>> applications;
Austin Schuhcb108412019-10-13 16:09:54 -0700493 if (config.message().has_applications()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700494 auto_merge_config.mutable_message()->clear_applications();
Austin Schuhcb108412019-10-13 16:09:54 -0700495 for (const Application *a : *config.message().applications()) {
496 if (!a->has_name()) {
497 continue;
498 }
499
Austin Schuha4fc60f2020-11-01 23:06:47 -0800500 auto result = applications.insert(RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700501 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800502 *result.first =
503 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(a));
Austin Schuhcb108412019-10-13 16:09:54 -0700504 }
505 }
506 }
507
Austin Schuh217a9782019-12-21 23:02:50 -0800508 // Now repeat this for the node list.
509 absl::btree_set<FlatbufferDetachedBuffer<Node>> nodes;
510 if (config.message().has_nodes()) {
James Kuszmaul3c998592020-07-27 21:04:47 -0700511 auto_merge_config.mutable_message()->clear_nodes();
Austin Schuh217a9782019-12-21 23:02:50 -0800512 for (const Node *n : *config.message().nodes()) {
513 if (!n->has_name()) {
514 continue;
515 }
516
Austin Schuha4fc60f2020-11-01 23:06:47 -0800517 auto result = nodes.insert(RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800518 if (!result.second) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800519 *result.first =
520 MergeFlatBuffers(*result.first, RecursiveCopyFlatBuffer(n));
Austin Schuh217a9782019-12-21 23:02:50 -0800521 }
522 }
523 }
524
Austin Schuhcb108412019-10-13 16:09:54 -0700525 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800526 fbb.ForceDefaults(true);
Austin Schuhcb108412019-10-13 16:09:54 -0700527
528 // Start by building the vectors. They need to come before the final table.
Austin Schuh40485ed2019-10-26 21:51:44 -0700529 // Channels
530 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
531 channels_offset;
Austin Schuhcb108412019-10-13 16:09:54 -0700532 {
Austin Schuh40485ed2019-10-26 21:51:44 -0700533 ::std::vector<flatbuffers::Offset<Channel>> channel_offsets;
534 for (const FlatbufferDetachedBuffer<Channel> &c : channels) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800535 channel_offsets.emplace_back(
536 RecursiveCopyFlatBuffer<Channel>(&c.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700537 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700538 channels_offset = fbb.CreateVector(channel_offsets);
Austin Schuhcb108412019-10-13 16:09:54 -0700539 }
540
541 // Applications
542 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
543 applications_offset;
544 {
545 ::std::vector<flatbuffers::Offset<Application>> applications_offsets;
Austin Schuh40485ed2019-10-26 21:51:44 -0700546 for (const FlatbufferDetachedBuffer<Application> &a : applications) {
Austin Schuhcb108412019-10-13 16:09:54 -0700547 applications_offsets.emplace_back(
Austin Schuha4fc60f2020-11-01 23:06:47 -0800548 RecursiveCopyFlatBuffer<Application>(&a.message(), &fbb));
Austin Schuhcb108412019-10-13 16:09:54 -0700549 }
550 applications_offset = fbb.CreateVector(applications_offsets);
551 }
552
Austin Schuh217a9782019-12-21 23:02:50 -0800553 // Nodes
554 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
555 nodes_offset;
556 {
557 ::std::vector<flatbuffers::Offset<Node>> node_offsets;
558 for (const FlatbufferDetachedBuffer<Node> &n : nodes) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800559 node_offsets.emplace_back(
560 RecursiveCopyFlatBuffer<Node>(&n.message(), &fbb));
Austin Schuh217a9782019-12-21 23:02:50 -0800561 }
562 nodes_offset = fbb.CreateVector(node_offsets);
563 }
564
Austin Schuhcb108412019-10-13 16:09:54 -0700565 // And then build a Configuration with them all.
566 ConfigurationBuilder configuration_builder(fbb);
Austin Schuh40485ed2019-10-26 21:51:44 -0700567 configuration_builder.add_channels(channels_offset);
Austin Schuh217a9782019-12-21 23:02:50 -0800568 if (config.message().has_applications()) {
569 configuration_builder.add_applications(applications_offset);
570 }
571 if (config.message().has_nodes()) {
572 configuration_builder.add_nodes(nodes_offset);
573 }
Austin Schuhcb108412019-10-13 16:09:54 -0700574
575 fbb.Finish(configuration_builder.Finish());
Austin Schuh217a9782019-12-21 23:02:50 -0800576
James Kuszmaul3c998592020-07-27 21:04:47 -0700577 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
578 fbb.Release());
579
Austin Schuh217a9782019-12-21 23:02:50 -0800580 // Now, validate that if there is a node list, every channel has a source
581 // node.
James Kuszmaul3c998592020-07-27 21:04:47 -0700582 FlatbufferDetachedBuffer<Configuration> result =
583 MergeFlatBuffers(modified_config, auto_merge_config);
Austin Schuh217a9782019-12-21 23:02:50 -0800584
Austin Schuh15182322020-10-10 15:25:21 -0700585 ValidateConfiguration(result);
Austin Schuh217a9782019-12-21 23:02:50 -0800586
587 return result;
Austin Schuhcb108412019-10-13 16:09:54 -0700588}
589
Austin Schuh40485ed2019-10-26 21:51:44 -0700590FlatbufferDetachedBuffer<Configuration> ReadConfig(
James Kuszmaulc0c08da2020-05-10 18:56:07 -0700591 const std::string_view path,
Austin Schuhef38cd22021-07-21 15:24:23 -0700592 const std::vector<std::string_view> &extra_import_paths) {
Austin Schuhcb108412019-10-13 16:09:54 -0700593 // We only want to read a file once. So track the visited files in a set.
594 absl::btree_set<std::string> visited_paths;
Austin Schuh15182322020-10-10 15:25:21 -0700595 FlatbufferDetachedBuffer<Configuration> read_config =
Austin Schuhef38cd22021-07-21 15:24:23 -0700596 ReadConfig(path, &visited_paths, extra_import_paths);
Austin Schuh15182322020-10-10 15:25:21 -0700597
598 // If we only read one file, and it had a .bfbs extension, it has to be a
599 // fully formatted config. Do a quick verification and return it.
600 if (visited_paths.size() == 1 && EndsWith(*visited_paths.begin(), ".bfbs")) {
601 ValidateConfiguration(read_config);
602 return read_config;
603 }
604
605 return MergeConfiguration(read_config);
Austin Schuhcb108412019-10-13 16:09:54 -0700606}
607
Austin Schuh8d6cea82020-02-28 12:17:16 -0800608FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Brian Silverman24f5aa82020-06-23 16:21:28 -0700609 const Configuration *config, const Flatbuffer<Configuration> &addition) {
610 return MergeConfiguration(MergeFlatBuffers(config, &addition.message()));
611}
612
613FlatbufferDetachedBuffer<Configuration> MergeWithConfig(
Austin Schuh8d6cea82020-02-28 12:17:16 -0800614 const Configuration *config, std::string_view json) {
615 FlatbufferDetachedBuffer<Configuration> addition =
616 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
617
Brian Silverman24f5aa82020-06-23 16:21:28 -0700618 return MergeWithConfig(config, addition);
Austin Schuh8d6cea82020-02-28 12:17:16 -0800619}
620
James Kuszmaul3ae42262019-11-08 12:33:41 -0800621const Channel *GetChannel(const Configuration *config, std::string_view name,
622 std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800623 std::string_view application_name, const Node *node,
624 bool quiet) {
Brian Silverman9fcf2c72020-12-21 18:30:58 -0800625 if (!config->has_channels()) {
626 return nullptr;
627 }
628
Austin Schuhbca6cf02019-12-22 17:28:34 -0800629 const std::string_view original_name = name;
Austin Schuhf1fff282020-03-28 16:57:32 -0700630 std::string mutable_name;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700631 if (node != nullptr) {
632 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
633 << "\" } on " << aos::FlatbufferToJson(node);
634 } else {
635 VLOG(1) << "Looking up { \"name\": \"" << name << "\", \"type\": \"" << type
636 << "\" }";
637 }
Austin Schuhcb108412019-10-13 16:09:54 -0700638
639 // First handle application specific maps. Only do this if we have a matching
640 // application name, and it has maps.
Austin Schuhd2e2f6a2021-02-07 20:46:16 -0800641 {
642 const Application *application =
643 GetApplication(config, node, application_name);
644 if (application != nullptr && application->has_maps()) {
645 mutable_name = std::string(name);
646 HandleMaps(application->maps(), &mutable_name, type, node);
647 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700648 }
649 }
650
651 // Now do global maps.
Austin Schuh40485ed2019-10-26 21:51:44 -0700652 if (config->has_maps()) {
Austin Schuhf1fff282020-03-28 16:57:32 -0700653 mutable_name = std::string(name);
654 HandleMaps(config->maps(), &mutable_name, type, node);
655 name = std::string_view(mutable_name);
Austin Schuhcb108412019-10-13 16:09:54 -0700656 }
657
Austin Schuhbca6cf02019-12-22 17:28:34 -0800658 if (original_name != name) {
659 VLOG(1) << "Remapped to { \"name\": \"" << name << "\", \"type\": \""
660 << type << "\" }";
661 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700662
James Kuszmaul71a81932020-12-15 21:08:01 -0800663 // Then look for the channel (note that this relies on the channels being
664 // sorted in the config).
Austin Schuh40485ed2019-10-26 21:51:44 -0700665 auto channel_iterator =
Austin Schuhf1fff282020-03-28 16:57:32 -0700666 std::lower_bound(config->channels()->cbegin(), config->channels()->cend(),
Austin Schuh40485ed2019-10-26 21:51:44 -0700667 std::make_pair(name, type), CompareChannels);
Austin Schuhcb108412019-10-13 16:09:54 -0700668
669 // Make sure we actually found it, and it matches.
Austin Schuh40485ed2019-10-26 21:51:44 -0700670 if (channel_iterator != config->channels()->cend() &&
671 EqualsChannels(*channel_iterator, std::make_pair(name, type))) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800672 if (VLOG_IS_ON(2)) {
673 VLOG(2) << "Found: " << FlatbufferToJson(*channel_iterator);
674 } else if (VLOG_IS_ON(1)) {
675 VLOG(1) << "Found: " << CleanedChannelToString(*channel_iterator);
676 }
Austin Schuh40485ed2019-10-26 21:51:44 -0700677 return *channel_iterator;
Austin Schuhcb108412019-10-13 16:09:54 -0700678 } else {
679 VLOG(1) << "No match for { \"name\": \"" << name << "\", \"type\": \""
680 << type << "\" }";
Austin Schuh0de30f32020-12-06 12:44:28 -0800681 if (original_name != name && !quiet) {
Austin Schuh4b42b252020-10-19 11:35:20 -0700682 LOG(WARNING) << "Remapped from {\"name\": \"" << original_name
683 << "\", \"type\": \"" << type << "\"}, to {\"name\": \""
684 << name << "\", \"type\": \"" << type
685 << "\"}, but no channel by that name exists.";
686 }
Austin Schuhcb108412019-10-13 16:09:54 -0700687 return nullptr;
688 }
689}
690
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800691size_t ChannelIndex(const Configuration *configuration,
692 const Channel *channel) {
693 CHECK(configuration->channels() != nullptr) << ": No channels";
694
695 auto c = std::find(configuration->channels()->begin(),
696 configuration->channels()->end(), channel);
697 CHECK(c != configuration->channels()->end())
698 << ": Channel pointer not found in configuration()->channels()";
699
700 return std::distance(configuration->channels()->begin(), c);
701}
702
Austin Schuhbca6cf02019-12-22 17:28:34 -0800703std::string CleanedChannelToString(const Channel *channel) {
704 FlatbufferDetachedBuffer<Channel> cleaned_channel = CopyFlatBuffer(channel);
705 cleaned_channel.mutable_message()->clear_schema();
706 return FlatbufferToJson(cleaned_channel);
707}
708
Austin Schuha81454b2020-05-12 19:58:36 -0700709std::string StrippedChannelToString(const Channel *channel) {
710 return absl::StrCat("{ \"name\": \"", channel->name()->string_view(),
711 "\", \"type\": \"", channel->type()->string_view(),
712 "\" }");
713}
714
Alex Perrycb7da4b2019-08-28 19:35:56 -0700715FlatbufferDetachedBuffer<Configuration> MergeConfiguration(
716 const Flatbuffer<Configuration> &config,
Austin Schuh0de30f32020-12-06 12:44:28 -0800717 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700718 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800719 fbb.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700720
Austin Schuh68d98592020-11-01 23:22:57 -0800721 // Cache for holding already inserted schemas.
722 std::map<std::string_view, flatbuffers::Offset<reflection::Schema>>
723 schema_cache;
724
725 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
726 << ": Merging logic needs to be updated when the number of channel "
727 "fields changes.";
James Kuszmaul3c998592020-07-27 21:04:47 -0700728
Alex Perrycb7da4b2019-08-28 19:35:56 -0700729 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
730 channels_offset;
731 if (config.message().has_channels()) {
732 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
733 for (const Channel *c : *config.message().channels()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734 // Search for a schema with a matching type.
Austin Schuh0de30f32020-12-06 12:44:28 -0800735 const aos::FlatbufferVector<reflection::Schema> *found_schema = nullptr;
736 for (const aos::FlatbufferVector<reflection::Schema> &schema : schemas) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700737 if (schema.message().root_table() != nullptr) {
738 if (schema.message().root_table()->name()->string_view() ==
739 c->type()->string_view()) {
740 found_schema = &schema;
741 }
742 }
743 }
744
745 CHECK(found_schema != nullptr)
746 << ": Failed to find schema for " << FlatbufferToJson(c);
747
Austin Schuh68d98592020-11-01 23:22:57 -0800748 // Now copy the message manually.
749 auto cached_schema = schema_cache.find(c->type()->string_view());
750 flatbuffers::Offset<reflection::Schema> schema_offset;
751 if (cached_schema != schema_cache.end()) {
752 schema_offset = cached_schema->second;
753 } else {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800754 schema_offset = RecursiveCopyFlatBuffer<reflection::Schema>(
755 &found_schema->message(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800756 schema_cache.emplace(c->type()->string_view(), schema_offset);
757 }
758
759 flatbuffers::Offset<flatbuffers::String> name_offset =
760 fbb.CreateSharedString(c->name()->str());
761 flatbuffers::Offset<flatbuffers::String> type_offset =
762 fbb.CreateSharedString(c->type()->str());
763 flatbuffers::Offset<flatbuffers::String> source_node_offset =
Austin Schuha4fc60f2020-11-01 23:06:47 -0800764 c->has_source_node() ? fbb.CreateSharedString(c->source_node()->str())
765 : 0;
Austin Schuh68d98592020-11-01 23:22:57 -0800766
767 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
768 destination_nodes_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800769 aos::RecursiveCopyVectorTable(c->destination_nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800770
771 flatbuffers::Offset<
772 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
773 logger_nodes_offset =
774 aos::CopyVectorSharedString(c->logger_nodes(), &fbb);
775
776 Channel::Builder channel_builder(fbb);
777 channel_builder.add_name(name_offset);
778 channel_builder.add_type(type_offset);
779 if (c->has_frequency()) {
780 channel_builder.add_frequency(c->frequency());
781 }
782 if (c->has_max_size()) {
783 channel_builder.add_max_size(c->max_size());
784 }
785 if (c->has_num_senders()) {
786 channel_builder.add_num_senders(c->num_senders());
787 }
788 if (c->has_num_watchers()) {
789 channel_builder.add_num_watchers(c->num_watchers());
790 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700791 channel_builder.add_schema(schema_offset);
Austin Schuh68d98592020-11-01 23:22:57 -0800792 if (!source_node_offset.IsNull()) {
793 channel_builder.add_source_node(source_node_offset);
794 }
795 if (!destination_nodes_offset.IsNull()) {
796 channel_builder.add_destination_nodes(destination_nodes_offset);
797 }
798 if (c->has_logger()) {
799 channel_builder.add_logger(c->logger());
800 }
801 if (!logger_nodes_offset.IsNull()) {
802 channel_builder.add_logger_nodes(logger_nodes_offset);
803 }
804 if (c->has_read_method()) {
805 channel_builder.add_read_method(c->read_method());
806 }
807 if (c->has_num_readers()) {
808 channel_builder.add_num_readers(c->num_readers());
809 }
810 channel_offsets.emplace_back(channel_builder.Finish());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700811 }
812 channels_offset = fbb.CreateVector(channel_offsets);
813 }
814
Austin Schuh68d98592020-11-01 23:22:57 -0800815 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800816 maps_offset =
817 aos::RecursiveCopyVectorTable(config.message().maps(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800818
819 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
Austin Schuh5c255aa2020-11-05 18:32:46 -0800820 nodes_offset =
821 aos::RecursiveCopyVectorTable(config.message().nodes(), &fbb);
Austin Schuh68d98592020-11-01 23:22:57 -0800822
823 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
824 applications_offset =
Austin Schuh5c255aa2020-11-05 18:32:46 -0800825 aos::RecursiveCopyVectorTable(config.message().applications(), &fbb);
Austin Schuh217a9782019-12-21 23:02:50 -0800826
827 // Now insert everything else in unmodified.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700828 ConfigurationBuilder configuration_builder(fbb);
829 if (config.message().has_channels()) {
830 configuration_builder.add_channels(channels_offset);
831 }
Austin Schuh68d98592020-11-01 23:22:57 -0800832 if (!maps_offset.IsNull()) {
833 configuration_builder.add_maps(maps_offset);
834 }
835 if (!nodes_offset.IsNull()) {
836 configuration_builder.add_nodes(nodes_offset);
837 }
838 if (!applications_offset.IsNull()) {
839 configuration_builder.add_applications(applications_offset);
840 }
841
842 if (config.message().has_channel_storage_duration()) {
843 configuration_builder.add_channel_storage_duration(
844 config.message().channel_storage_duration());
845 }
846
847 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
848 << ": Merging logic needs to be updated when the number of configuration "
849 "fields changes.";
850
Alex Perrycb7da4b2019-08-28 19:35:56 -0700851 fbb.Finish(configuration_builder.Finish());
James Kuszmaul3c998592020-07-27 21:04:47 -0700852 aos::FlatbufferDetachedBuffer<aos::Configuration> modified_config(
853 fbb.Release());
854
Austin Schuh68d98592020-11-01 23:22:57 -0800855 return modified_config;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700856}
857
Austin Schuh217a9782019-12-21 23:02:50 -0800858const Node *GetNodeFromHostname(const Configuration *config,
859 std::string_view hostname) {
860 for (const Node *node : *config->nodes()) {
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800861 if (node->has_hostname() && node->hostname()->string_view() == hostname) {
Austin Schuh217a9782019-12-21 23:02:50 -0800862 return node;
863 }
Brian Silvermanaa2633f2020-02-17 21:04:14 -0800864 if (node->has_hostnames()) {
865 for (const auto &candidate : *node->hostnames()) {
866 if (candidate->string_view() == hostname) {
867 return node;
868 }
869 }
870 }
Austin Schuh217a9782019-12-21 23:02:50 -0800871 }
872 return nullptr;
873}
Austin Schuhac0771c2020-01-07 18:36:30 -0800874
Austin Schuh217a9782019-12-21 23:02:50 -0800875const Node *GetMyNode(const Configuration *config) {
876 const std::string hostname = (FLAGS_override_hostname.size() > 0)
877 ? FLAGS_override_hostname
878 : network::GetHostname();
879 const Node *node = GetNodeFromHostname(config, hostname);
880 if (node != nullptr) return node;
881
882 LOG(FATAL) << "Unknown node for host: " << hostname
883 << ". Consider using --override_hostname if hostname detection "
884 "is wrong.";
885 return nullptr;
886}
887
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800888const Node *GetNode(const Configuration *config, const Node *node) {
889 if (!MultiNode(config)) {
890 CHECK(node == nullptr) << ": Provided a node in a single node world.";
891 return nullptr;
892 } else {
893 CHECK(node != nullptr);
894 CHECK(node->has_name());
895 return GetNode(config, node->name()->string_view());
896 }
897}
898
Austin Schuh217a9782019-12-21 23:02:50 -0800899const Node *GetNode(const Configuration *config, std::string_view name) {
Austin Schuhfd960622020-01-01 13:22:55 -0800900 CHECK(config->has_nodes())
901 << ": Asking for a node from a single node configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800902 for (const Node *node : *config->nodes()) {
Austin Schuhfd960622020-01-01 13:22:55 -0800903 CHECK(node->has_name()) << ": Malformed node " << FlatbufferToJson(node);
Austin Schuh217a9782019-12-21 23:02:50 -0800904 if (node->name()->string_view() == name) {
905 return node;
906 }
907 }
908 return nullptr;
909}
910
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800911const Node *GetNode(const Configuration *config, size_t node_index) {
912 if (!MultiNode(config)) {
913 CHECK_EQ(node_index, 0u) << ": Invalid node in a single node world.";
914 return nullptr;
915 } else {
916 CHECK_LT(node_index, config->nodes()->size());
917 return config->nodes()->Get(node_index);
918 }
919}
920
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800921const Node *GetNodeOrDie(const Configuration *config, const Node *node) {
922 if (!MultiNode(config)) {
923 CHECK(node == nullptr) << ": Provided a node in a single node world.";
924 return nullptr;
925 } else {
926 const Node *config_node = GetNode(config, node);
927 if (config_node == nullptr) {
928 LOG(FATAL) << "Couldn't find node matching " << FlatbufferToJson(node);
929 }
930 return config_node;
931 }
932}
933
Austin Schuh8bd96322020-02-13 21:18:22 -0800934namespace {
935int GetNodeIndexFromConfig(const Configuration *config, const Node *node) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800936 int node_index = 0;
937 for (const Node *iterated_node : *config->nodes()) {
938 if (iterated_node == node) {
939 return node_index;
940 }
941 ++node_index;
942 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800943 return -1;
944}
945} // namespace
946
Austin Schuha9df9ad2021-06-16 14:49:39 -0700947aos::FlatbufferDetachedBuffer<aos::Configuration> AddSchema(
948 std::string_view json,
949 const std::vector<aos::FlatbufferVector<reflection::Schema>> &schemas) {
950 FlatbufferDetachedBuffer<Configuration> addition =
951 JsonToFlatbuffer(json, Configuration::MiniReflectTypeTable());
952 return MergeConfiguration(addition, schemas);
953}
954
Austin Schuh8bd96322020-02-13 21:18:22 -0800955int GetNodeIndex(const Configuration *config, const Node *node) {
956 if (!MultiNode(config)) {
957 return 0;
958 }
959
960 {
961 int node_index = GetNodeIndexFromConfig(config, node);
962 if (node_index != -1) {
963 return node_index;
964 }
965 }
966
967 const Node *result = GetNode(config, node);
968 CHECK(result != nullptr);
969
970 {
Austin Schuh04408fc2020-02-16 21:48:54 -0800971 int node_index = GetNodeIndexFromConfig(config, result);
Austin Schuh8bd96322020-02-13 21:18:22 -0800972 if (node_index != -1) {
973 return node_index;
974 }
975 }
976
977 LOG(FATAL) << "Node " << FlatbufferToJson(node)
978 << " not found in the configuration.";
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800979}
980
Austin Schuh04408fc2020-02-16 21:48:54 -0800981int GetNodeIndex(const Configuration *config, std::string_view name) {
982 if (!MultiNode(config)) {
983 return 0;
984 }
985
986 {
987 int node_index = 0;
988 for (const Node *iterated_node : *config->nodes()) {
989 if (iterated_node->name()->string_view() == name) {
990 return node_index;
991 }
992 ++node_index;
993 }
994 }
995 LOG(FATAL) << "Node " << name << " not found in the configuration.";
996}
997
Austin Schuh681a2472020-12-31 23:55:40 -0800998size_t NodesCount(const Configuration *config) {
999 if (!MultiNode(config)) {
1000 return 1u;
1001 }
1002
1003 return config->nodes()->size();
1004}
1005
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001006std::vector<const Node *> GetNodes(const Configuration *config) {
1007 std::vector<const Node *> nodes;
Austin Schuh8bd96322020-02-13 21:18:22 -08001008 if (MultiNode(config)) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -08001009 for (const Node *node : *config->nodes()) {
1010 nodes.emplace_back(node);
1011 }
1012 } else {
1013 nodes.emplace_back(nullptr);
1014 }
1015 return nodes;
1016}
1017
Austin Schuh65465332020-11-05 17:36:53 -08001018std::vector<const Node *> GetNodesWithTag(const Configuration *config,
1019 std::string_view tag) {
1020 std::vector<const Node *> nodes;
1021 if (!MultiNode(config)) {
1022 nodes.emplace_back(nullptr);
1023 } else {
1024 for (const Node *node : *config->nodes()) {
1025 if (!node->has_tags()) {
1026 continue;
1027 }
1028 bool did_found_tag = false;
1029 for (const flatbuffers::String *found_tag : *node->tags()) {
1030 if (found_tag->string_view() == tag) {
1031 did_found_tag = true;
1032 break;
1033 }
1034 }
1035 if (did_found_tag) {
1036 nodes.emplace_back(node);
1037 }
1038 }
1039 }
1040 return nodes;
1041}
1042
Austin Schuhac0771c2020-01-07 18:36:30 -08001043bool MultiNode(const Configuration *config) { return config->has_nodes(); }
1044
Austin Schuh217a9782019-12-21 23:02:50 -08001045bool ChannelIsSendableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001046 if (node == nullptr) {
1047 return true;
1048 }
Austin Schuh3c5dae52020-10-06 18:55:18 -07001049 CHECK(channel->has_source_node()) << FlatbufferToJson(channel);
1050 CHECK(node->has_name()) << FlatbufferToJson(node);
Austin Schuh196a4452020-03-15 23:12:03 -07001051 return (CHECK_NOTNULL(channel)->source_node()->string_view() ==
1052 node->name()->string_view());
Austin Schuh217a9782019-12-21 23:02:50 -08001053}
1054
1055bool ChannelIsReadableOnNode(const Channel *channel, const Node *node) {
Austin Schuhca4828c2019-12-28 14:21:35 -08001056 if (node == nullptr) {
1057 return true;
1058 }
1059
Austin Schuh217a9782019-12-21 23:02:50 -08001060 if (channel->source_node()->string_view() == node->name()->string_view()) {
1061 return true;
1062 }
1063
1064 if (!channel->has_destination_nodes()) {
1065 return false;
1066 }
1067
Austin Schuh719946b2019-12-28 14:51:01 -08001068 for (const Connection *connection : *channel->destination_nodes()) {
1069 CHECK(connection->has_name());
1070 if (connection->name()->string_view() == node->name()->string_view()) {
Austin Schuh217a9782019-12-21 23:02:50 -08001071 return true;
1072 }
1073 }
1074
1075 return false;
1076}
1077
Austin Schuh719946b2019-12-28 14:51:01 -08001078bool ChannelMessageIsLoggedOnNode(const Channel *channel, const Node *node) {
Austin Schuh48e94502021-06-18 18:35:53 -07001079 if (node == nullptr) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001080 // Single node world. If there is a local logger, then we want to use
1081 // it.
Austin Schuh48e94502021-06-18 18:35:53 -07001082 if (channel->logger() == LoggerConfig::LOCAL_LOGGER) {
1083 return true;
1084 } else if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1085 return false;
1086 }
1087 LOG(FATAL) << "Unsupported logging configuration in a single node world: "
1088 << CleanedChannelToString(channel);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001089 }
1090 return ChannelMessageIsLoggedOnNode(
1091 channel, CHECK_NOTNULL(node)->name()->string_view());
1092}
1093
1094bool ChannelMessageIsLoggedOnNode(const Channel *channel,
1095 std::string_view node_name) {
Austin Schuhf1fff282020-03-28 16:57:32 -07001096 switch (channel->logger()) {
Austin Schuh719946b2019-12-28 14:51:01 -08001097 case LoggerConfig::LOCAL_LOGGER:
Austin Schuh2bb80e02021-03-20 21:46:17 -07001098 return channel->source_node()->string_view() == node_name;
Austin Schuh719946b2019-12-28 14:51:01 -08001099 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001100 CHECK(channel->has_logger_nodes());
1101 CHECK_GT(channel->logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001102
Austin Schuh2bb80e02021-03-20 21:46:17 -07001103 if (channel->source_node()->string_view() == node_name) {
Austin Schuh719946b2019-12-28 14:51:01 -08001104 return true;
1105 }
Austin Schuhda40e472020-03-28 15:15:29 -07001106
1107 [[fallthrough]];
1108 case LoggerConfig::REMOTE_LOGGER:
1109 CHECK(channel->has_logger_nodes());
1110 CHECK_GT(channel->logger_nodes()->size(), 0u);
1111 for (const flatbuffers::String *logger_node : *channel->logger_nodes()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001112 if (logger_node->string_view() == node_name) {
Austin Schuhda40e472020-03-28 15:15:29 -07001113 return true;
1114 }
Austin Schuh719946b2019-12-28 14:51:01 -08001115 }
1116
1117 return false;
1118 case LoggerConfig::NOT_LOGGED:
1119 return false;
1120 }
1121
1122 LOG(FATAL) << "Unknown logger config " << static_cast<int>(channel->logger());
1123}
1124
1125const Connection *ConnectionToNode(const Channel *channel, const Node *node) {
1126 if (!channel->has_destination_nodes()) {
1127 return nullptr;
1128 }
1129 for (const Connection *connection : *channel->destination_nodes()) {
1130 if (connection->name()->string_view() == node->name()->string_view()) {
1131 return connection;
1132 }
1133 }
1134 return nullptr;
1135}
1136
1137bool ConnectionDeliveryTimeIsLoggedOnNode(const Channel *channel,
1138 const Node *node,
1139 const Node *logger_node) {
1140 const Connection *connection = ConnectionToNode(channel, node);
1141 if (connection == nullptr) {
1142 return false;
1143 }
1144 return ConnectionDeliveryTimeIsLoggedOnNode(connection, logger_node);
1145}
1146
1147bool ConnectionDeliveryTimeIsLoggedOnNode(const Connection *connection,
1148 const Node *node) {
1149 switch (connection->timestamp_logger()) {
1150 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
Austin Schuhda40e472020-03-28 15:15:29 -07001151 CHECK(connection->has_timestamp_logger_nodes());
1152 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
Austin Schuh719946b2019-12-28 14:51:01 -08001153 if (connection->name()->string_view() == node->name()->string_view()) {
1154 return true;
1155 }
1156
Austin Schuhda40e472020-03-28 15:15:29 -07001157 [[fallthrough]];
1158 case LoggerConfig::REMOTE_LOGGER:
1159 CHECK(connection->has_timestamp_logger_nodes());
1160 CHECK_GT(connection->timestamp_logger_nodes()->size(), 0u);
1161 for (const flatbuffers::String *timestamp_logger_node :
1162 *connection->timestamp_logger_nodes()) {
1163 if (timestamp_logger_node->string_view() ==
1164 node->name()->string_view()) {
1165 return true;
1166 }
Austin Schuh719946b2019-12-28 14:51:01 -08001167 }
1168
1169 return false;
1170 case LoggerConfig::LOCAL_LOGGER:
1171 return connection->name()->string_view() == node->name()->string_view();
Austin Schuh719946b2019-12-28 14:51:01 -08001172 case LoggerConfig::NOT_LOGGED:
1173 return false;
1174 }
1175
1176 LOG(FATAL) << "Unknown logger config "
1177 << static_cast<int>(connection->timestamp_logger());
1178}
1179
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001180std::vector<std::string_view> SourceNodeNames(const Configuration *config,
1181 const Node *my_node) {
1182 std::set<std::string_view> result_set;
1183
1184 for (const Channel *channel : *config->channels()) {
1185 if (channel->has_destination_nodes()) {
1186 for (const Connection *connection : *channel->destination_nodes()) {
1187 if (connection->name()->string_view() ==
1188 my_node->name()->string_view()) {
1189 result_set.insert(channel->source_node()->string_view());
1190 }
1191 }
1192 }
1193 }
1194
1195 std::vector<std::string_view> result;
1196 for (const std::string_view source : result_set) {
1197 VLOG(1) << "Found a source node of " << source;
1198 result.emplace_back(source);
1199 }
1200 return result;
1201}
1202
1203std::vector<std::string_view> DestinationNodeNames(const Configuration *config,
1204 const Node *my_node) {
1205 std::vector<std::string_view> result;
1206
1207 for (const Channel *channel : *config->channels()) {
1208 if (channel->has_source_node() && channel->source_node()->string_view() ==
1209 my_node->name()->string_view()) {
1210 if (!channel->has_destination_nodes()) continue;
1211
1212 if (channel->source_node()->string_view() !=
1213 my_node->name()->string_view()) {
1214 continue;
1215 }
1216
1217 for (const Connection *connection : *channel->destination_nodes()) {
1218 if (std::find(result.begin(), result.end(),
1219 connection->name()->string_view()) == result.end()) {
1220 result.emplace_back(connection->name()->string_view());
1221 }
1222 }
1223 }
1224 }
1225
1226 for (const std::string_view destination : result) {
1227 VLOG(1) << "Found a destination node of " << destination;
1228 }
1229 return result;
1230}
1231
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001232std::vector<const Node *> TimestampNodes(const Configuration *config,
1233 const Node *my_node) {
1234 if (!configuration::MultiNode(config)) {
1235 CHECK(my_node == nullptr);
1236 return std::vector<const Node *>{};
1237 }
1238
1239 std::set<const Node *> timestamp_logger_nodes;
1240 for (const Channel *channel : *config->channels()) {
1241 if (!configuration::ChannelIsSendableOnNode(channel, my_node)) {
1242 continue;
1243 }
1244 if (!channel->has_destination_nodes()) {
1245 continue;
1246 }
1247 for (const Connection *connection : *channel->destination_nodes()) {
1248 const Node *other_node =
1249 configuration::GetNode(config, connection->name()->string_view());
1250
1251 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
1252 my_node)) {
1253 VLOG(1) << "Timestamps are logged from "
1254 << FlatbufferToJson(other_node);
1255 timestamp_logger_nodes.insert(other_node);
1256 }
1257 }
1258 }
1259
1260 std::vector<const Node *> result;
1261 for (const Node *node : timestamp_logger_nodes) {
1262 result.emplace_back(node);
1263 }
1264 return result;
1265}
1266
Austin Schuhd2e2f6a2021-02-07 20:46:16 -08001267const Application *GetApplication(const Configuration *config,
1268 const Node *my_node,
1269 std::string_view application_name) {
1270 if (config->has_applications()) {
1271 auto application_iterator = std::lower_bound(
1272 config->applications()->cbegin(), config->applications()->cend(),
1273 application_name, CompareApplications);
1274 if (application_iterator != config->applications()->cend() &&
1275 EqualsApplications(*application_iterator, application_name)) {
1276 if (MultiNode(config)) {
1277 // Ok, we need
1278 CHECK(application_iterator->has_nodes());
1279 CHECK(my_node != nullptr);
1280 for (const flatbuffers::String *str : *application_iterator->nodes()) {
1281 if (str->string_view() == my_node->name()->string_view()) {
1282 return *application_iterator;
1283 }
1284 }
1285 } else {
1286 return *application_iterator;
1287 }
1288 }
1289 }
1290 return nullptr;
1291}
1292
Austin Schuhfc7b6a02021-07-12 21:19:07 -07001293std::vector<size_t> SourceNodeIndex(const Configuration *config) {
1294 CHECK(config->has_channels());
1295 std::vector<size_t> result;
1296 result.resize(config->channels()->size(), 0u);
1297 if (MultiNode(config)) {
1298 for (size_t i = 0; i < config->channels()->size(); ++i) {
1299 result[i] = GetNodeIndex(
1300 config, config->channels()->Get(i)->source_node()->string_view());
1301 }
1302 }
1303 return result;
1304}
1305
Brian Silverman66f079a2013-08-26 16:24:30 -07001306} // namespace configuration
1307} // namespace aos