blob: 108176e194fc9415cd6a0871d723de2d165c879f [file] [log] [blame]
Austin Schuh898f4972020-01-11 17:21:25 -08001#include "aos/events/simulated_network_bridge.h"
2
Austin Schuh0de30f32020-12-06 12:44:28 -08003#include "absl/strings/str_cat.h"
4#include "aos/configuration.h"
Austin Schuh898f4972020-01-11 17:21:25 -08005#include "aos/events/event_loop.h"
6#include "aos/events/simulated_event_loop.h"
Austin Schuh0de30f32020-12-06 12:44:28 -08007#include "aos/network/remote_message_generated.h"
Austin Schuh898f4972020-01-11 17:21:25 -08008
9namespace aos {
10namespace message_bridge {
11
12// This class delays messages forwarded between two factories.
13//
14// The basic design is that we need to use the distributed_clock to convert
15// monotonic times from the source to the destination node. We also use a
16// fetcher to manage the queue of data, and a timer to schedule the sends.
17class RawMessageDelayer {
18 public:
Austin Schuh58646e22021-08-23 23:51:46 -070019 RawMessageDelayer(const Channel *channel, const Connection *connection,
20 aos::NodeEventLoopFactory *fetch_node_factory,
Austin Schuh898f4972020-01-11 17:21:25 -080021 aos::NodeEventLoopFactory *send_node_factory,
Austin Schuh58646e22021-08-23 23:51:46 -070022 size_t destination_node_index, bool delivery_time_is_logged)
23 : channel_(channel),
24 connection_(connection),
25 fetch_node_factory_(fetch_node_factory),
Austin Schuh898f4972020-01-11 17:21:25 -080026 send_node_factory_(send_node_factory),
Austin Schuh20ac95d2020-12-05 17:24:19 -080027 destination_node_index_(destination_node_index),
Austin Schuh58646e22021-08-23 23:51:46 -070028 channel_index_(configuration::ChannelIndex(
29 fetch_node_factory_->configuration(), channel_)),
30 delivery_time_is_logged_(delivery_time_is_logged) {}
Austin Schuh898f4972020-01-11 17:21:25 -080031
Austin Schuh58646e22021-08-23 23:51:46 -070032 bool forwarding_disabled() const { return forwarding_disabled_; }
33 void set_forwarding_disabled(bool forwarding_disabled) {
34 forwarding_disabled_ = forwarding_disabled;
James Kuszmaul94ca5132022-07-19 09:11:08 -070035 if (!forwarding_disabled_) {
36 CHECK(timestamp_logger_ == nullptr);
37 CHECK(sender_ == nullptr);
38 }
Austin Schuh898f4972020-01-11 17:21:25 -080039 }
40
Austin Schuh58646e22021-08-23 23:51:46 -070041 void SetFetchEventLoop(aos::EventLoop *fetch_event_loop,
42 MessageBridgeServerStatus *server_status,
43 ChannelTimestampSender *timestamp_loggers) {
44 sent_ = false;
45 fetch_event_loop_ = fetch_event_loop;
46 if (fetch_event_loop_) {
47 fetcher_ = fetch_event_loop_->MakeRawFetcher(channel_);
48 } else {
49 fetcher_ = nullptr;
50 }
51
52 server_status_ = server_status;
53 if (server_status) {
54 server_connection_ =
55 server_status_->FindServerConnection(send_node_factory_->node());
56 }
James Kuszmaul94ca5132022-07-19 09:11:08 -070057 if (delivery_time_is_logged_ && timestamp_loggers != nullptr &&
58 !forwarding_disabled_) {
Austin Schuh58646e22021-08-23 23:51:46 -070059 timestamp_logger_ =
60 timestamp_loggers->SenderForChannel(channel_, connection_);
61 } else {
62 timestamp_logger_ = nullptr;
63 }
64
65 if (fetch_event_loop_) {
66 timestamp_timer_ =
67 fetch_event_loop_->AddTimer([this]() { SendTimestamp(); });
68 if (send_event_loop_) {
milind1f1dca32021-07-03 13:50:07 -070069 std::string timer_name =
70 absl::StrCat(send_event_loop_->node()->name()->string_view(), " ",
71 fetcher_->channel()->name()->string_view(), " ",
72 fetcher_->channel()->type()->string_view());
Austin Schuh58646e22021-08-23 23:51:46 -070073 if (timer_) {
74 timer_->set_name(timer_name);
75 }
76 timestamp_timer_->set_name(absl::StrCat(timer_name, " timestamps"));
77 }
78 } else {
79 timestamp_timer_ = nullptr;
80 }
81 }
82
83 void SetSendEventLoop(aos::EventLoop *send_event_loop,
84 MessageBridgeClientStatus *client_status) {
85 sent_ = false;
86 send_event_loop_ = send_event_loop;
James Kuszmaul94ca5132022-07-19 09:11:08 -070087 if (send_event_loop_ && !forwarding_disabled_) {
Austin Schuh58646e22021-08-23 23:51:46 -070088 sender_ = send_event_loop_->MakeRawSender(channel_);
89 } else {
90 sender_ = nullptr;
91 }
92
93 client_status_ = client_status;
94 if (client_status_) {
95 client_index_ = client_status_->FindClientIndex(
96 channel_->source_node()->string_view());
97 client_connection_ = client_status_->GetClientConnection(client_index_);
98 } else {
99 client_index_ = -1;
100 client_connection_ = nullptr;
101 }
102
103 if (send_event_loop_) {
104 timer_ = send_event_loop_->AddTimer([this]() { Send(); });
105 if (fetcher_) {
106 std::string timer_name =
107 absl::StrCat(send_event_loop_->node()->name()->string_view(), " ",
108 fetcher_->channel()->name()->string_view(), " ",
109 fetcher_->channel()->type()->string_view());
110 timer_->set_name(timer_name);
111 if (timestamp_timer_) {
112 timestamp_timer_->set_name(absl::StrCat(timer_name, " timestamps"));
113 }
114 }
115 } else {
116 timer_ = nullptr;
117 }
118 }
119
120 const Channel *channel() const { return channel_; }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800121
Austin Schuh4c570ea2020-11-19 23:13:24 -0800122 uint32_t time_to_live() {
Austin Schuh58646e22021-08-23 23:51:46 -0700123 return configuration::ConnectionToNode(channel_, send_node_factory_->node())
Austin Schuh4c570ea2020-11-19 23:13:24 -0800124 ->time_to_live();
125 }
126
Austin Schuh58646e22021-08-23 23:51:46 -0700127 void ScheduleReliable() {
128 if (forwarding_disabled()) return;
129
130 if (!fetcher_) {
131 return;
132 }
133 if (fetcher_->context().data == nullptr || sent_) {
134 sent_ = !fetcher_->Fetch();
135 }
136
137 FetchNext();
138 if (fetcher_->context().data == nullptr || sent_) {
139 return;
140 }
141 CHECK(!timer_scheduled_);
142
143 // Send at startup. It is the best we can do.
144 const monotonic_clock::time_point monotonic_delivered_time =
145 send_node_factory_->monotonic_now() +
146 send_node_factory_->network_delay();
147
148 CHECK_GE(monotonic_delivered_time, send_node_factory_->monotonic_now())
149 << ": Trying to deliver message in the past on channel "
150 << configuration::StrippedChannelToString(fetcher_->channel())
151 << " to node " << send_event_loop_->node()->name()->string_view()
152 << " sent from " << fetcher_->channel()->source_node()->string_view()
153 << " at " << fetch_node_factory_->monotonic_now();
154
155 if (timer_) {
156 server_connection_->mutate_sent_packets(
157 server_connection_->sent_packets() + 1);
158 timer_->Setup(monotonic_delivered_time);
159 timer_scheduled_ = true;
160 } else {
161 server_connection_->mutate_dropped_packets(
162 server_connection_->dropped_packets() + 1);
163 sent_ = true;
164 }
165 }
166
167 bool timer_scheduled_ = false;
168
Austin Schuh898f4972020-01-11 17:21:25 -0800169 // Kicks us to re-fetch and schedule the timer.
170 void Schedule() {
Austin Schuh58646e22021-08-23 23:51:46 -0700171 CHECK(!forwarding_disabled());
172 if (!fetcher_) {
173 return;
174 }
175 if (timer_scheduled_) {
176 return;
177 }
178 FetchNext();
179 if (fetcher_->context().data == nullptr || sent_) {
180 return;
181 }
182
183 // Compute the time to publish this message.
184 const monotonic_clock::time_point monotonic_delivered_time =
185 DeliveredTime(fetcher_->context());
186
187 CHECK_GE(monotonic_delivered_time, send_node_factory_->monotonic_now())
188 << ": Trying to deliver message in the past on channel "
189 << configuration::StrippedChannelToString(fetcher_->channel())
190 << " to node " << send_event_loop_->node()->name()->string_view()
191 << " sent from " << fetcher_->channel()->source_node()->string_view()
192 << " at " << fetch_node_factory_->monotonic_now();
193
194 if (timer_) {
195 server_connection_->mutate_sent_packets(
196 server_connection_->sent_packets() + 1);
197 timer_->Setup(monotonic_delivered_time);
198 timer_scheduled_ = true;
199 } else {
200 server_connection_->mutate_dropped_packets(
201 server_connection_->dropped_packets() + 1);
202 sent_ = true;
203 Schedule();
204 }
205 }
206
207 private:
208 void FetchNext() {
209 CHECK(server_connection_);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800210 // Keep pulling messages out of the fetcher until we find one in the future.
211 while (true) {
212 if (fetcher_->context().data == nullptr || sent_) {
213 sent_ = !fetcher_->FetchNext();
214 }
215 if (sent_) {
216 break;
217 }
Austin Schuhc0b0f722020-12-12 18:36:06 -0800218
219 if (server_connection_->state() != State::CONNECTED) {
220 sent_ = true;
221 server_connection_->mutate_dropped_packets(
222 server_connection_->dropped_packets() + 1);
223 continue;
224 }
225
Austin Schuh6aa77be2020-02-22 21:06:40 -0800226 if (fetcher_->context().monotonic_event_time +
Austin Schuh58646e22021-08-23 23:51:46 -0700227 send_node_factory_->network_delay() +
228 send_node_factory_->send_delay() >
229 fetch_node_factory_->monotonic_now() ||
230 time_to_live() == 0) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800231 break;
232 }
233
234 // TODO(austin): Not cool. We want to actually forward these. This means
235 // we need a more sophisticated concept of what is running.
Austin Schuh60e77942022-05-16 17:48:24 -0700236 // TODO(james): This fails if multiple messages are sent on the same
237 // channel within the same callback.
Austin Schuh6aa77be2020-02-22 21:06:40 -0800238 LOG(WARNING) << "Not forwarding message on "
239 << configuration::CleanedChannelToString(fetcher_->channel())
240 << " because we aren't running. Set at "
241 << fetcher_->context().monotonic_event_time << " now is "
242 << fetch_node_factory_->monotonic_now();
243 sent_ = true;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700244 server_connection_->mutate_dropped_packets(
245 server_connection_->dropped_packets() + 1);
Austin Schuh898f4972020-01-11 17:21:25 -0800246 }
Austin Schuh898f4972020-01-11 17:21:25 -0800247 }
248
Austin Schuh58646e22021-08-23 23:51:46 -0700249 // Actually sends the message, and reschedules.
Austin Schuh898f4972020-01-11 17:21:25 -0800250 void Send() {
Austin Schuh58646e22021-08-23 23:51:46 -0700251 timer_scheduled_ = false;
252 CHECK(sender_);
253 CHECK(client_status_);
Austin Schuhc0b0f722020-12-12 18:36:06 -0800254 if (server_connection_->state() != State::CONNECTED) {
255 sent_ = true;
256 Schedule();
257 return;
258 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700259 // Fill out the send times.
milind1f1dca32021-07-03 13:50:07 -0700260 sender_->CheckOk(sender_->Send(
261 fetcher_->context().data, fetcher_->context().size,
262 fetcher_->context().monotonic_event_time,
263 fetcher_->context().realtime_event_time,
264 fetcher_->context().queue_index, fetcher_->context().source_boot_uuid));
Austin Schuh898f4972020-01-11 17:21:25 -0800265
Austin Schuh4c3b9702020-08-30 11:34:55 -0700266 // And simulate message_bridge's offset recovery.
Austin Schuh367a7f42021-11-23 23:04:36 -0800267 client_status_->SampleFilter(
268 client_index_, fetcher_->context().monotonic_event_time,
269 sender_->monotonic_sent_time(), fetcher_->context().source_boot_uuid);
Austin Schuh4c3b9702020-08-30 11:34:55 -0700270
271 client_connection_->mutate_received_packets(
272 client_connection_->received_packets() + 1);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700273
274 if (timestamp_logger_) {
Austin Schuheeaa2022021-01-02 21:52:03 -0800275 flatbuffers::FlatBufferBuilder fbb;
Austin Schuh5e2bfb82021-03-13 22:46:55 -0800276 fbb.ForceDefaults(true);
Austin Schuh20ac95d2020-12-05 17:24:19 -0800277 // Reset the filter every time the UUID changes. There's probably a more
278 // clever way to do this, but that means a better concept of rebooting.
279 if (server_status_->BootUUID(destination_node_index_) !=
Austin Schuh5e2bfb82021-03-13 22:46:55 -0800280 send_node_factory_->boot_uuid()) {
Austin Schuh20ac95d2020-12-05 17:24:19 -0800281 server_status_->ResetFilter(destination_node_index_);
Austin Schuh5e2bfb82021-03-13 22:46:55 -0800282 server_status_->SetBootUUID(destination_node_index_,
283 send_node_factory_->boot_uuid());
Austin Schuh20ac95d2020-12-05 17:24:19 -0800284 }
285
Austin Schuhcdd90272021-03-15 12:46:16 -0700286 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
287 send_node_factory_->boot_uuid().PackVector(&fbb);
Austin Schuh20ac95d2020-12-05 17:24:19 -0800288
Austin Schuheeaa2022021-01-02 21:52:03 -0800289 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700290
291 message_header_builder.add_channel_index(channel_index_);
292
293 // Swap the remote and sent metrics. They are from the sender's
294 // perspective, not the receiver's perspective.
295 message_header_builder.add_monotonic_remote_time(
296 fetcher_->context().monotonic_event_time.time_since_epoch().count());
297 message_header_builder.add_realtime_remote_time(
298 fetcher_->context().realtime_event_time.time_since_epoch().count());
299 message_header_builder.add_remote_queue_index(
300 fetcher_->context().queue_index);
301
302 message_header_builder.add_monotonic_sent_time(
303 sender_->monotonic_sent_time().time_since_epoch().count());
304 message_header_builder.add_realtime_sent_time(
305 sender_->realtime_sent_time().time_since_epoch().count());
306 message_header_builder.add_queue_index(sender_->sent_queue_index());
Austin Schuh20ac95d2020-12-05 17:24:19 -0800307 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700308
Austin Schuheeaa2022021-01-02 21:52:03 -0800309 fbb.Finish(message_header_builder.Finish());
310
311 remote_timestamps_.emplace_back(
312 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
313 fetch_node_factory_->monotonic_now() +
314 send_node_factory_->network_delay());
315 ScheduleTimestamp();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700316 }
317
Austin Schuh898f4972020-01-11 17:21:25 -0800318 sent_ = true;
319 Schedule();
320 }
321
Austin Schuheeaa2022021-01-02 21:52:03 -0800322 // Schedules sending the next timestamp in remote_timestamps_ if there is one.
323 void ScheduleTimestamp() {
324 if (remote_timestamps_.empty()) {
325 timestamp_timer_->Disable();
326 return;
327 }
328
329 if (scheduled_time_ !=
330 remote_timestamps_.front().monotonic_timestamp_time) {
331 timestamp_timer_->Setup(
332 remote_timestamps_.front().monotonic_timestamp_time);
333 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
334 return;
335 } else {
336 scheduled_time_ = monotonic_clock::min_time;
337 }
338 }
339
340 // Sends the next timestamp in remote_timestamps_.
341 void SendTimestamp() {
342 CHECK(!remote_timestamps_.empty());
343
344 // Send out all timestamps at the currently scheduled time.
345 while (remote_timestamps_.front().monotonic_timestamp_time ==
346 scheduled_time_) {
347 if (server_connection_->state() == State::CONNECTED) {
milind1f1dca32021-07-03 13:50:07 -0700348 timestamp_logger_->CheckOk(timestamp_logger_->Send(
349 std::move(remote_timestamps_.front().remote_message)));
Austin Schuheeaa2022021-01-02 21:52:03 -0800350 }
351 remote_timestamps_.pop_front();
352 if (remote_timestamps_.empty()) {
353 break;
354 }
355 }
356
357 ScheduleTimestamp();
358 }
359
Austin Schuh898f4972020-01-11 17:21:25 -0800360 // Converts from time on the sending node to time on the receiving node.
361 monotonic_clock::time_point DeliveredTime(const Context &context) const {
362 const distributed_clock::time_point distributed_sent_time =
363 fetch_node_factory_->ToDistributedClock(context.monotonic_event_time);
364
Austin Schuh58646e22021-08-23 23:51:46 -0700365 const logger::BootTimestamp t = send_node_factory_->FromDistributedClock(
Austin Schuh2febf0d2020-09-21 22:24:30 -0700366 distributed_sent_time + send_node_factory_->network_delay() +
367 send_node_factory_->send_delay());
Austin Schuh58646e22021-08-23 23:51:46 -0700368 CHECK_EQ(t.boot, send_node_factory_->boot_count());
369 return t.time;
Austin Schuh898f4972020-01-11 17:21:25 -0800370 }
371
Austin Schuh58646e22021-08-23 23:51:46 -0700372 const Channel *channel_;
373 const Connection *connection_;
374
Austin Schuh898f4972020-01-11 17:21:25 -0800375 // Factories used for time conversion.
376 aos::NodeEventLoopFactory *fetch_node_factory_;
377 aos::NodeEventLoopFactory *send_node_factory_;
378
Austin Schuheeaa2022021-01-02 21:52:03 -0800379 // Event loop which fetching and sending timestamps are scheduled on.
Austin Schuh58646e22021-08-23 23:51:46 -0700380 aos::EventLoop *fetch_event_loop_ = nullptr;
Austin Schuh898f4972020-01-11 17:21:25 -0800381 // Event loop which sending is scheduled on.
Austin Schuh58646e22021-08-23 23:51:46 -0700382 aos::EventLoop *send_event_loop_ = nullptr;
Austin Schuh898f4972020-01-11 17:21:25 -0800383 // Timer used to send.
Austin Schuh58646e22021-08-23 23:51:46 -0700384 aos::TimerHandler *timer_ = nullptr;
Austin Schuheeaa2022021-01-02 21:52:03 -0800385 // Timer used to send timestamps out.
Austin Schuh58646e22021-08-23 23:51:46 -0700386 aos::TimerHandler *timestamp_timer_ = nullptr;
Austin Schuheeaa2022021-01-02 21:52:03 -0800387 // Time that the timer is scheduled for. Used to track if it needs to be
388 // rescheduled.
389 monotonic_clock::time_point scheduled_time_ = monotonic_clock::min_time;
390
Austin Schuh898f4972020-01-11 17:21:25 -0800391 // Fetcher used to receive messages.
392 std::unique_ptr<aos::RawFetcher> fetcher_;
393 // Sender to send them back out.
394 std::unique_ptr<aos::RawSender> sender_;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800395
Austin Schuh58646e22021-08-23 23:51:46 -0700396 MessageBridgeServerStatus *server_status_ = nullptr;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800397 const size_t destination_node_index_;
Austin Schuh898f4972020-01-11 17:21:25 -0800398 // True if we have sent the message in the fetcher.
399 bool sent_ = false;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700400
401 ServerConnection *server_connection_ = nullptr;
402 MessageBridgeClientStatus *client_status_ = nullptr;
Austin Schuh58646e22021-08-23 23:51:46 -0700403 int client_index_ = -1;
Austin Schuh4c3b9702020-08-30 11:34:55 -0700404 ClientConnection *client_connection_ = nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700405
406 size_t channel_index_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800407 aos::Sender<RemoteMessage> *timestamp_logger_ = nullptr;
Austin Schuheeaa2022021-01-02 21:52:03 -0800408
409 struct Timestamp {
410 Timestamp(FlatbufferDetachedBuffer<RemoteMessage> new_remote_message,
411 monotonic_clock::time_point new_monotonic_timestamp_time)
412 : remote_message(std::move(new_remote_message)),
413 monotonic_timestamp_time(new_monotonic_timestamp_time) {}
414 FlatbufferDetachedBuffer<RemoteMessage> remote_message;
415 monotonic_clock::time_point monotonic_timestamp_time;
416 };
417
418 std::deque<Timestamp> remote_timestamps_;
Austin Schuh58646e22021-08-23 23:51:46 -0700419
420 bool delivery_time_is_logged_;
421
422 bool forwarding_disabled_ = false;
Austin Schuh898f4972020-01-11 17:21:25 -0800423};
424
425SimulatedMessageBridge::SimulatedMessageBridge(
426 SimulatedEventLoopFactory *simulated_event_loop_factory) {
427 CHECK(
428 configuration::MultiNode(simulated_event_loop_factory->configuration()));
429
430 // Pre-build up event loops for every node. They are pretty cheap anyways.
431 for (const Node *node : simulated_event_loop_factory->nodes()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700432 NodeEventLoopFactory *node_factory =
433 simulated_event_loop_factory->GetNodeEventLoopFactory(node);
434 auto it = event_loop_map_.emplace(node, node_factory);
Austin Schuhcde938c2020-02-02 17:30:07 -0800435 CHECK(it.second);
436
Austin Schuh58646e22021-08-23 23:51:46 -0700437 node_factory->OnStartup(
438 [this, simulated_event_loop_factory, node_state = &it.first->second]() {
439 node_state->MakeEventLoop();
440 const size_t my_node_index = configuration::GetNodeIndex(
441 simulated_event_loop_factory->configuration(),
442 node_state->event_loop->node());
Austin Schuh4c3b9702020-08-30 11:34:55 -0700443
Austin Schuh58646e22021-08-23 23:51:46 -0700444 size_t node_index = 0;
445 for (ServerConnection *connection :
446 node_state->server_status->server_connection()) {
447 if (connection != nullptr) {
448 node_state->server_status->ResetFilter(node_index);
449 }
450 ++node_index;
451 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700452
Austin Schuh58646e22021-08-23 23:51:46 -0700453 for (const ClientConnection *client_connections :
454 *node_state->client_status->mutable_client_statistics()
455 ->connections()) {
456 const Node *client_node = configuration::GetNode(
457 simulated_event_loop_factory->configuration(),
458 client_connections->node()->name()->string_view());
Austin Schuh4c3b9702020-08-30 11:34:55 -0700459
Austin Schuh58646e22021-08-23 23:51:46 -0700460 auto client_event_loop = event_loop_map_.find(client_node);
461 client_event_loop->second.SetBootUUID(
462 my_node_index, node_state->event_loop->boot_uuid());
463 }
464 });
Austin Schuh4c3b9702020-08-30 11:34:55 -0700465
Austin Schuh58646e22021-08-23 23:51:46 -0700466 node_factory->OnShutdown([node_state = &it.first->second]() {
467 node_state->SetEventLoop(nullptr);
468 });
Austin Schuh20ac95d2020-12-05 17:24:19 -0800469 }
470
Austin Schuh898f4972020-01-11 17:21:25 -0800471 for (const Channel *channel :
472 *simulated_event_loop_factory->configuration()->channels()) {
473 if (!channel->has_destination_nodes()) {
474 continue;
475 }
476
477 // Find the sending node.
Austin Schuh58646e22021-08-23 23:51:46 -0700478 const Node *source_node =
Austin Schuh898f4972020-01-11 17:21:25 -0800479 configuration::GetNode(simulated_event_loop_factory->configuration(),
480 channel->source_node()->string_view());
Austin Schuh58646e22021-08-23 23:51:46 -0700481 auto source_event_loop = event_loop_map_.find(source_node);
Austin Schuh898f4972020-01-11 17:21:25 -0800482 CHECK(source_event_loop != event_loop_map_.end());
483
484 std::unique_ptr<DelayersVector> delayers =
485 std::make_unique<DelayersVector>();
486
487 // And then build up a RawMessageDelayer for each destination.
488 for (const Connection *connection : *channel->destination_nodes()) {
489 const Node *destination_node =
490 configuration::GetNode(simulated_event_loop_factory->configuration(),
491 connection->name()->string_view());
492 auto destination_event_loop = event_loop_map_.find(destination_node);
493 CHECK(destination_event_loop != event_loop_map_.end());
494
Austin Schuh2f8fd752020-09-01 22:38:28 -0700495 const size_t destination_node_index = configuration::GetNodeIndex(
496 simulated_event_loop_factory->configuration(), destination_node);
497
498 const bool delivery_time_is_logged =
Austin Schuh58646e22021-08-23 23:51:46 -0700499 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
500 source_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700501
Austin Schuh58646e22021-08-23 23:51:46 -0700502 delayers->v.emplace_back(std::make_unique<RawMessageDelayer>(
503 channel, connection,
504 simulated_event_loop_factory->GetNodeEventLoopFactory(source_node),
Austin Schuh898f4972020-01-11 17:21:25 -0800505 simulated_event_loop_factory->GetNodeEventLoopFactory(
506 destination_node),
Austin Schuh58646e22021-08-23 23:51:46 -0700507 destination_node_index, delivery_time_is_logged));
508
509 source_event_loop->second.AddSourceDelayer(delayers->v.back().get());
510 destination_event_loop->second.AddDestinationDelayer(
511 delayers->v.back().get());
Austin Schuh898f4972020-01-11 17:21:25 -0800512 }
513
Austin Schuh4c3b9702020-08-30 11:34:55 -0700514 const Channel *const timestamp_channel = configuration::GetChannel(
515 simulated_event_loop_factory->configuration(), "/aos",
Austin Schuh58646e22021-08-23 23:51:46 -0700516 Timestamp::GetFullyQualifiedName(), "message_bridge", source_node);
Austin Schuh4c3b9702020-08-30 11:34:55 -0700517
518 if (channel == timestamp_channel) {
Austin Schuh58646e22021-08-23 23:51:46 -0700519 source_event_loop->second.SetSendData(
Austin Schuh4c3b9702020-08-30 11:34:55 -0700520 [captured_delayers = delayers.get()](const Context &) {
521 for (std::unique_ptr<RawMessageDelayer> &delayer :
Austin Schuh58646e22021-08-23 23:51:46 -0700522 captured_delayers->v) {
Austin Schuh4c3b9702020-08-30 11:34:55 -0700523 delayer->Schedule();
524 }
525 });
526 } else {
Austin Schuh58646e22021-08-23 23:51:46 -0700527 source_event_loop->second.AddDelayerWatcher(channel, delayers.get());
Austin Schuh4c3b9702020-08-30 11:34:55 -0700528 }
Austin Schuh898f4972020-01-11 17:21:25 -0800529 delayers_list_.emplace_back(std::move(delayers));
530 }
531}
532
533SimulatedMessageBridge::~SimulatedMessageBridge() {}
534
Austin Schuh6f3babe2020-01-26 20:34:50 -0800535void SimulatedMessageBridge::DisableForwarding(const Channel *channel) {
Austin Schuh58646e22021-08-23 23:51:46 -0700536 for (std::unique_ptr<DelayersVector> &delayers : delayers_list_) {
537 if (delayers->v.size() > 0) {
538 if (delayers->v[0]->channel() == channel) {
539 delayers->disable_forwarding = true;
540 for (std::unique_ptr<RawMessageDelayer> &delayer : delayers->v) {
541 delayer->set_forwarding_disabled(true);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800542 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800543 }
544 }
545 }
546}
547
Austin Schuhc0b0f722020-12-12 18:36:06 -0800548void SimulatedMessageBridge::Disconnect(const Node *source,
549 const Node *destination) {
550 SetState(source, destination, message_bridge::State::DISCONNECTED);
551}
552
553void SimulatedMessageBridge::Connect(const Node *source,
554 const Node *destination) {
555 SetState(source, destination, message_bridge::State::CONNECTED);
556}
557void SimulatedMessageBridge::SetState(const Node *source,
558 const Node *destination,
559 message_bridge::State state) {
560 auto source_state = event_loop_map_.find(source);
561 CHECK(source_state != event_loop_map_.end());
Austin Schuh58646e22021-08-23 23:51:46 -0700562 source_state->second.SetServerState(destination, state);
Austin Schuhc0b0f722020-12-12 18:36:06 -0800563
564 auto destination_state = event_loop_map_.find(destination);
565 CHECK(destination_state != event_loop_map_.end());
Austin Schuh58646e22021-08-23 23:51:46 -0700566 destination_state->second.SetClientState(source, state);
Austin Schuhc0b0f722020-12-12 18:36:06 -0800567}
568
James Kuszmaul94ca5132022-07-19 09:11:08 -0700569void SimulatedMessageBridge::DisableStatistics(DestroySenders destroy_senders) {
Austin Schuh4c3b9702020-08-30 11:34:55 -0700570 for (std::pair<const Node *const, State> &state : event_loop_map_) {
James Kuszmaul94ca5132022-07-19 09:11:08 -0700571 state.second.DisableStatistics(destroy_senders);
Austin Schuh4c3b9702020-08-30 11:34:55 -0700572 }
573}
574
James Kuszmaul94ca5132022-07-19 09:11:08 -0700575void SimulatedMessageBridge::DisableStatistics(const Node *node,
576 DestroySenders destroy_senders) {
Austin Schuh48205e62021-11-12 14:13:18 -0800577 auto it = event_loop_map_.find(node);
578 CHECK(it != event_loop_map_.end());
James Kuszmaul94ca5132022-07-19 09:11:08 -0700579 it->second.DisableStatistics(destroy_senders);
Austin Schuh48205e62021-11-12 14:13:18 -0800580}
581
582void SimulatedMessageBridge::EnableStatistics() {
583 for (std::pair<const Node *const, State> &state : event_loop_map_) {
584 state.second.EnableStatistics();
585 }
586}
587
588void SimulatedMessageBridge::EnableStatistics(const Node *node) {
589 auto it = event_loop_map_.find(node);
590 CHECK(it != event_loop_map_.end());
591 it->second.EnableStatistics();
592}
593
Austin Schuh58646e22021-08-23 23:51:46 -0700594void SimulatedMessageBridge::State::SetEventLoop(
595 std::unique_ptr<aos::EventLoop> loop) {
596 if (!loop) {
597 timestamp_loggers = ChannelTimestampSender(nullptr);
598 server_status.reset();
599 client_status.reset();
600 for (RawMessageDelayer *source_delayer : source_delayers_) {
601 source_delayer->SetFetchEventLoop(nullptr, nullptr, nullptr);
602 }
603 for (RawMessageDelayer *destination_delayer : destination_delayers_) {
604 destination_delayer->SetSendEventLoop(nullptr, nullptr);
605 }
606 event_loop = std::move(loop);
607 return;
608 } else {
609 CHECK(!event_loop);
610 }
611 event_loop = std::move(loop);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700612
Austin Schuh58646e22021-08-23 23:51:46 -0700613 event_loop->SkipTimingReport();
614 event_loop->SkipAosLog();
615
616 for (std::pair<const Channel *, DelayersVector *> &watcher :
617 delayer_watchers_) {
618 // Don't register watchers if we know we aren't forwarding.
619 if (watcher.second->disable_forwarding) continue;
620 event_loop->MakeRawNoArgWatcher(
621 watcher.first, [captured_delayers = watcher.second](const Context &) {
622 // We might get told after registering, so don't forward at that point
623 // too.
624 for (std::unique_ptr<RawMessageDelayer> &delayer :
625 captured_delayers->v) {
626 delayer->Schedule();
627 }
628 });
629 }
630
631 timestamp_loggers = ChannelTimestampSender(event_loop.get());
632 server_status = std::make_unique<MessageBridgeServerStatus>(event_loop.get());
Austin Schuh48205e62021-11-12 14:13:18 -0800633 if (disable_statistics_) {
James Kuszmaul94ca5132022-07-19 09:11:08 -0700634 server_status->DisableStatistics(destroy_senders_ == DestroySenders::kYes);
Austin Schuh48205e62021-11-12 14:13:18 -0800635 }
Austin Schuh58646e22021-08-23 23:51:46 -0700636
637 {
638 size_t node_index = 0;
639 for (ServerConnection *connection : server_status->server_connection()) {
640 if (connection) {
641 if (boot_uuids_[node_index] != UUID::Zero()) {
Austin Schuh367a7f42021-11-23 23:04:36 -0800642 switch (server_state_[node_index]) {
643 case message_bridge::State::DISCONNECTED:
644 server_status->Disconnect(node_index);
645 break;
646 case message_bridge::State::CONNECTED:
647 server_status->Connect(node_index, event_loop->monotonic_now());
648 break;
649 }
Austin Schuh58646e22021-08-23 23:51:46 -0700650 } else {
Austin Schuh367a7f42021-11-23 23:04:36 -0800651 server_status->Disconnect(node_index);
Austin Schuh58646e22021-08-23 23:51:46 -0700652 }
653 }
654 ++node_index;
655 }
656 }
657
658 for (size_t i = 0; i < boot_uuids_.size(); ++i) {
659 if (boot_uuids_[i] != UUID::Zero()) {
660 server_status->SetBootUUID(i, boot_uuids_[i]);
661 }
662 }
Austin Schuh58646e22021-08-23 23:51:46 -0700663 if (fn_) {
664 server_status->set_send_data(fn_);
665 }
666 client_status = std::make_unique<MessageBridgeClientStatus>(event_loop.get());
667 if (disable_statistics_) {
James Kuszmaul94ca5132022-07-19 09:11:08 -0700668 client_status->DisableStatistics(destroy_senders_ == DestroySenders::kYes);
Austin Schuh58646e22021-08-23 23:51:46 -0700669 }
670
671 for (size_t i = 0;
672 i < client_status->mutable_client_statistics()->connections()->size();
673 ++i) {
674 ClientConnection *client_connection =
675 client_status->mutable_client_statistics()
676 ->mutable_connections()
677 ->GetMutableObject(i);
678 const Node *client_node = configuration::GetNode(
679 node_factory_->configuration(),
680 client_connection->node()->name()->string_view());
681 const size_t client_node_index = configuration::GetNodeIndex(
682 node_factory_->configuration(), client_node);
683 if (boot_uuids_[client_node_index] != UUID::Zero()) {
Austin Schuh367a7f42021-11-23 23:04:36 -0800684 if (client_connection->state() != client_state_[client_node_index]) {
685 switch (client_state_[client_node_index]) {
686 case message_bridge::State::DISCONNECTED:
687 client_status->Disconnect(i);
688 break;
689 case message_bridge::State::CONNECTED:
690 client_status->Connect(i);
691 break;
692 }
693 }
Austin Schuh58646e22021-08-23 23:51:46 -0700694 } else {
Austin Schuh367a7f42021-11-23 23:04:36 -0800695 client_status->Disconnect(i);
Austin Schuh58646e22021-08-23 23:51:46 -0700696 }
697 }
698
Austin Schuh2f8fd752020-09-01 22:38:28 -0700699 for (const Channel *channel : *event_loop->configuration()->channels()) {
700 CHECK(channel->has_source_node());
701
702 // Sent by us.
703 if (configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
704 channel->has_destination_nodes()) {
705 for (const Connection *connection : *channel->destination_nodes()) {
706 const bool delivery_time_is_logged =
707 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
708 connection, event_loop->node());
709
James Kuszmaul94ca5132022-07-19 09:11:08 -0700710 const RawMessageDelayer *delayer = nullptr;
711 for (const RawMessageDelayer *candidate : source_delayers_) {
712 if (candidate->channel() == channel) {
713 delayer = candidate;
714 }
715 }
716
Austin Schuh2f8fd752020-09-01 22:38:28 -0700717 // And the timestamps are then logged back by us again.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700718 if (!delivery_time_is_logged ||
719 CHECK_NOTNULL(delayer)->forwarding_disabled()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720 continue;
721 }
722
Austin Schuh89c9b812021-02-20 14:42:10 -0800723 timestamp_loggers.SenderForChannel(channel, connection);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700724 }
725 }
726 }
Austin Schuh58646e22021-08-23 23:51:46 -0700727
728 for (RawMessageDelayer *source_delayer : source_delayers_) {
729 source_delayer->SetFetchEventLoop(event_loop.get(), server_status.get(),
730 &timestamp_loggers);
731 }
732 for (RawMessageDelayer *destination_delayer : destination_delayers_) {
733 destination_delayer->SetSendEventLoop(event_loop.get(),
734 client_status.get());
735 }
736 event_loop->OnRun([this]() {
737 for (RawMessageDelayer *destination_delayer : destination_delayers_) {
738 if (destination_delayer->time_to_live() == 0) {
739 destination_delayer->ScheduleReliable();
740 }
741 }
742 });
Austin Schuh2f8fd752020-09-01 22:38:28 -0700743}
744
Austin Schuh898f4972020-01-11 17:21:25 -0800745} // namespace message_bridge
746} // namespace aos