blob: bc15643f8b6cf2bca898b11c5f0b6221c0f964ae [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/simulated_event_loop.h"
2
3#include <algorithm>
4#include <deque>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08005#include <string_view>
Brian Silverman661eb8d2020-08-12 19:41:01 -07006#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
8#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -07009#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080010#include "aos/events/simulated_network_bridge.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070012#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/util/phased_loop.h"
14
15namespace aos {
16
Brian Silverman661eb8d2020-08-12 19:41:01 -070017class SimulatedEventLoop;
18class SimulatedFetcher;
19class SimulatedChannel;
20
21namespace {
22
Austin Schuhcc6070c2020-10-10 20:25:56 -070023class ScopedMarkRealtimeRestorer {
24 public:
25 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
26 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
27
28 private:
29 const bool rt_;
30 const bool prior_;
31};
32
Alex Perrycb7da4b2019-08-28 19:35:56 -070033// Container for both a message, and the context for it for simulation. This
34// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070035struct SimulatedMessage final {
36 SimulatedMessage(const SimulatedMessage &) = delete;
37 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
38
39 // Creates a SimulatedMessage with size bytes of storage.
40 // This is a shared_ptr so we don't have to implement refcounting or copying.
41 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
42
Alex Perrycb7da4b2019-08-28 19:35:56 -070043 // Context for the data.
44 Context context;
45
Brian Silverman661eb8d2020-08-12 19:41:01 -070046 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070047
Alex Perrycb7da4b2019-08-28 19:35:56 -070048 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080049 char *data(size_t buffer_size) {
50 return RoundChannelData(&actual_data[0], buffer_size);
51 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070052
Brian Silvermana1652f32020-01-29 20:41:44 -080053 // Then the data, including padding on the end so we can align the buffer we
54 // actually return from data().
55 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070056
57 private:
58 SimulatedMessage(SimulatedChannel *channel_in);
59 ~SimulatedMessage();
60
61 static void DestroyAndFree(SimulatedMessage *p) {
62 p->~SimulatedMessage();
63 free(p);
64 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070065};
66
Brian Silverman661eb8d2020-08-12 19:41:01 -070067} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080068
Brian Silverman661eb8d2020-08-12 19:41:01 -070069// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
70// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080071class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080072 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080073 SimulatedWatcher(
74 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
75 const Channel *channel,
76 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080077
Austin Schuh7d87b672019-12-01 20:23:49 -080078 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080079
80 void Startup(EventLoop * /*event_loop*/) override {}
81
Austin Schuh7d87b672019-12-01 20:23:49 -080082 void Schedule(std::shared_ptr<SimulatedMessage> message);
83
84 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080085
86 void SetSimulatedChannel(SimulatedChannel *channel) {
87 simulated_channel_ = channel;
88 }
89
90 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080091 void DoSchedule(monotonic_clock::time_point event_time);
92
93 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
94
Brian Silverman4f4e0612020-08-12 19:54:41 -070095 SimulatedEventLoop *const simulated_event_loop_;
96 const Channel *const channel_;
97 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -080098 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -080099 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 SimulatedChannel *simulated_channel_ = nullptr;
101};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102
103class SimulatedChannel {
104 public:
Brian Silverman661eb8d2020-08-12 19:41:01 -0700105 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler,
106 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800107 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108 scheduler_(scheduler),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109 channel_storage_duration_(channel_storage_duration),
110 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
111 available_buffer_indices_.reserve(number_buffers());
112 for (int i = 0; i < number_buffers(); ++i) {
113 available_buffer_indices_.push_back(i);
114 }
115 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116
Brian Silverman661eb8d2020-08-12 19:41:01 -0700117 ~SimulatedChannel() {
118 latest_message_.reset();
119 CHECK_EQ(static_cast<size_t>(number_buffers()),
120 available_buffer_indices_.size());
121 CHECK_EQ(0u, fetchers_.size());
122 CHECK_EQ(0u, watchers_.size());
123 CHECK_EQ(0, sender_count_);
124 }
125
126 // The number of messages we pretend to have in the queue.
127 int queue_size() const {
128 return channel()->frequency() *
129 std::chrono::duration_cast<std::chrono::duration<double>>(
130 channel_storage_duration_)
131 .count();
132 }
133
134 // The number of extra buffers (beyond the queue) we pretend to have.
135 int number_scratch_buffers() const {
136 // We need to start creating messages before we know how many
137 // senders+readers we'll have, so we need to just pick something which is
138 // always big enough.
139 return 50;
140 }
141
142 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
143
144 int GetBufferIndex() {
145 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
146 const int result = available_buffer_indices_.back();
147 available_buffer_indices_.pop_back();
148 return result;
149 }
150
151 void FreeBufferIndex(int i) {
152 DCHECK(std::find(available_buffer_indices_.begin(),
153 available_buffer_indices_.end(),
154 i) == available_buffer_indices_.end())
155 << ": Buffer is not in use: " << i;
156 available_buffer_indices_.push_back(i);
157 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700158
159 // Makes a connected raw sender which calls Send below.
160 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
161
162 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800163 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164
165 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800166 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800167
Austin Schuh7d87b672019-12-01 20:23:49 -0800168 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800169 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
170 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
Austin Schuhad154822019-12-27 15:45:13 -0800172 // Sends the message to all the connected receivers and fetchers. Returns the
173 // sent queue index.
174 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
176 // Unregisters a fetcher.
177 void UnregisterFetcher(SimulatedFetcher *fetcher);
178
179 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
180
Austin Schuh39788ff2019-12-01 18:22:57 -0800181 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800183 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800184 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185 }
186
Austin Schuh39788ff2019-12-01 18:22:57 -0800187 const Channel *channel() const { return channel_; }
188
Austin Schuhe516ab02020-05-06 21:37:04 -0700189 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700190 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700191 if (sender_count_ >= channel()->num_senders()) {
192 LOG(FATAL) << "Failed to create sender on "
193 << configuration::CleanedChannelToString(channel())
194 << ", too many senders.";
195 }
196 ++sender_count_;
197 }
Brian Silverman77162972020-08-12 19:52:40 -0700198
Austin Schuhe516ab02020-05-06 21:37:04 -0700199 void CountSenderDestroyed() {
200 --sender_count_;
201 CHECK_GE(sender_count_, 0);
202 }
203
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204 private:
Brian Silverman77162972020-08-12 19:52:40 -0700205 void CheckBufferCount() {
206 int reader_count = 0;
207 if (channel()->read_method() == ReadMethod::PIN) {
208 reader_count = watchers_.size() + fetchers_.size();
209 }
210 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
211 }
212
213 void CheckReaderCount() {
214 if (channel()->read_method() != ReadMethod::PIN) {
215 return;
216 }
217 CheckBufferCount();
218 const int reader_count = watchers_.size() + fetchers_.size();
219 if (reader_count >= channel()->num_readers()) {
220 LOG(FATAL) << "Failed to create reader on "
221 << configuration::CleanedChannelToString(channel())
222 << ", too many readers.";
223 }
224 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700225
226 const Channel *const channel_;
227 EventScheduler *const scheduler_;
228 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
230 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800231 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232
233 // List of all fetchers.
234 ::std::vector<SimulatedFetcher *> fetchers_;
235 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700236
237 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700238
239 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700240
241 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242};
243
244namespace {
245
Brian Silverman661eb8d2020-08-12 19:41:01 -0700246std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
247 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800248 // The allocations in here are due to infrastructure and don't count in the no
249 // mallocs in RT code.
250 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700251 const size_t size = channel->max_size();
252 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800253 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700254 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800256 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700257
Brian Silverman661eb8d2020-08-12 19:41:01 -0700258 return std::shared_ptr<SimulatedMessage>(message,
259 &SimulatedMessage::DestroyAndFree);
260}
261
262SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
263 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700264 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700265}
266
267SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700268 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700269}
270
271class SimulatedSender : public RawSender {
272 public:
273 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800274 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800275 simulated_channel_(simulated_channel),
Austin Schuhe516ab02020-05-06 21:37:04 -0700276 event_loop_(event_loop) {
277 simulated_channel_->CountSenderCreated();
278 }
279 ~SimulatedSender() { simulated_channel_->CountSenderDestroyed(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280
281 void *data() override {
282 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700283 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800285 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286 }
287
288 size_t size() override { return simulated_channel_->max_size(); }
289
Austin Schuhad154822019-12-27 15:45:13 -0800290 bool DoSend(size_t length,
291 aos::monotonic_clock::time_point monotonic_remote_time,
292 aos::realtime_clock::time_point realtime_remote_time,
293 uint32_t remote_queue_index) override {
Austin Schuh62288252020-11-18 23:26:04 -0800294 // The allocations in here are due to infrastructure and don't count in the
295 // no mallocs in RT code.
296 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800298 message_->context.monotonic_event_time = event_loop_->monotonic_now();
299 message_->context.monotonic_remote_time = monotonic_remote_time;
300 message_->context.remote_queue_index = remote_queue_index;
301 message_->context.realtime_event_time = event_loop_->realtime_now();
302 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 CHECK_LE(length, message_->context.size);
304 message_->context.size = length;
305
306 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800307 sent_queue_index_ = simulated_channel_->Send(message_);
308 monotonic_sent_time_ = event_loop_->monotonic_now();
309 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310
311 // Drop the reference to the message so that we allocate a new message for
312 // next time. Otherwise we will continue to reuse the same memory for all
313 // messages and corrupt it.
314 message_.reset();
315 return true;
316 }
317
Austin Schuhad154822019-12-27 15:45:13 -0800318 bool DoSend(const void *msg, size_t size,
319 aos::monotonic_clock::time_point monotonic_remote_time,
320 aos::realtime_clock::time_point realtime_remote_time,
321 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
323
324 // This is wasteful, but since flatbuffers fill from the back end of the
325 // queue, we need it to be full sized.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700326 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327
328 // Now fill in the message. size is already populated above, and
Austin Schuhac0771c2020-01-07 18:36:30 -0800329 // queue_index will be populated in simulated_channel_. Put this at the
330 // back of the data segment.
Brian Silvermana1652f32020-01-29 20:41:44 -0800331 memcpy(message_->data(simulated_channel_->max_size()) +
332 simulated_channel_->max_size() - size,
333 msg, size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334
Austin Schuhac0771c2020-01-07 18:36:30 -0800335 return DoSend(size, monotonic_remote_time, realtime_remote_time,
336 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337 }
338
Brian Silverman4f4e0612020-08-12 19:54:41 -0700339 int buffer_index() override {
340 // First, ensure message_ is allocated.
341 data();
342 return message_->context.buffer_index;
343 }
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 private:
346 SimulatedChannel *simulated_channel_;
347 EventLoop *event_loop_;
348
349 std::shared_ptr<SimulatedMessage> message_;
350};
351} // namespace
352
353class SimulatedFetcher : public RawFetcher {
354 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800355 explicit SimulatedFetcher(EventLoop *event_loop,
356 SimulatedChannel *simulated_channel)
357 : RawFetcher(event_loop, simulated_channel->channel()),
358 simulated_channel_(simulated_channel) {}
359 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360
Austin Schuh39788ff2019-12-01 18:22:57 -0800361 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800362 // The allocations in here are due to infrastructure and don't count in the
363 // no mallocs in RT code.
364 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800365 if (msgs_.size() == 0) {
366 return std::make_pair(false, monotonic_clock::min_time);
367 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700369 CHECK(!fell_behind_) << ": Got behind on "
370 << configuration::StrippedChannelToString(
371 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700372
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373 SetMsg(msgs_.front());
374 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800375 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 }
377
Austin Schuh39788ff2019-12-01 18:22:57 -0800378 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800379 // The allocations in here are due to infrastructure and don't count in the
380 // no mallocs in RT code.
381 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800383 // TODO(austin): Can we just do this logic unconditionally? It is a lot
384 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800385 if (!msg_ && simulated_channel_->latest_message()) {
386 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800387 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800389 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 }
391 }
392
393 // We've had a message enqueued, so we don't need to go looking for the
394 // latest message from before we started.
395 SetMsg(msgs_.back());
396 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700397 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800398 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 }
400
401 private:
402 friend class SimulatedChannel;
403
404 // Updates the state inside RawFetcher to point to the data in msg_.
405 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
406 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700408 if (channel()->read_method() != ReadMethod::PIN) {
409 context_.buffer_index = -1;
410 }
Austin Schuhad154822019-12-27 15:45:13 -0800411 if (context_.remote_queue_index == 0xffffffffu) {
412 context_.remote_queue_index = context_.queue_index;
413 }
414 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
415 context_.monotonic_remote_time = context_.monotonic_event_time;
416 }
417 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
418 context_.realtime_remote_time = context_.realtime_event_time;
419 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 }
421
422 // Internal method for Simulation to add a message to the buffer.
423 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
424 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700425 if (fell_behind_ ||
426 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
427 fell_behind_ = true;
428 // Might as well empty out all the intermediate messages now.
429 while (msgs_.size() > 1) {
430 msgs_.pop_front();
431 }
432 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433 }
434
Austin Schuhac0771c2020-01-07 18:36:30 -0800435 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436 std::shared_ptr<SimulatedMessage> msg_;
437
438 // Messages queued up but not in use.
439 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700440
441 // Whether we're currently "behind", which means a FetchNext call will fail.
442 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443};
444
445class SimulatedTimerHandler : public TimerHandler {
446 public:
447 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800448 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800450 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451
452 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800453 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800455 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456
Austin Schuh7d87b672019-12-01 20:23:49 -0800457 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800460 SimulatedEventLoop *simulated_event_loop_;
461 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700462 EventScheduler *scheduler_;
463 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800464
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465 monotonic_clock::time_point base_;
466 monotonic_clock::duration repeat_offset_;
467};
468
469class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
470 public:
471 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800472 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700473 ::std::function<void(int)> fn,
474 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800475 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800476 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477
Austin Schuh7d87b672019-12-01 20:23:49 -0800478 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479
Austin Schuh7d87b672019-12-01 20:23:49 -0800480 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481
482 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800483 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800484 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485
Austin Schuh39788ff2019-12-01 18:22:57 -0800486 EventScheduler *scheduler_;
487 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488};
489
490class SimulatedEventLoop : public EventLoop {
491 public:
492 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700493 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
495 *channels,
496 const Configuration *configuration,
497 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800498 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800499 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800500 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800502 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800504 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800505 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800506 tid_(tid) {
507 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
508 if (!has_setup_) {
509 Setup();
510 has_setup_ = true;
511 }
512 set_is_running(value);
513 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514 }
515 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800516 // Trigger any remaining senders or fetchers to be cleared before destroying
517 // the event loop so the book keeping matches.
518 timing_report_sender_.reset();
519
520 // Force everything with a registered fd with epoll to be destroyed now.
521 timers_.clear();
522 phased_loops_.clear();
523 watchers_.clear();
524
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
526 ++it) {
527 if (it->first == this) {
528 raw_event_loops_->erase(it);
529 break;
530 }
531 }
532 }
533
Austin Schuh7d87b672019-12-01 20:23:49 -0800534 std::chrono::nanoseconds send_delay() const { return send_delay_; }
535 void set_send_delay(std::chrono::nanoseconds send_delay) {
536 send_delay_ = send_delay;
537 }
538
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800540 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 }
542
543 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800544 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 }
546
547 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
548
549 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
550
551 void MakeRawWatcher(
552 const Channel *channel,
553 ::std::function<void(const Context &context, const void *message)>
554 watcher) override;
555
556 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800558 return NewTimer(::std::unique_ptr<TimerHandler>(
559 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 }
561
562 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
563 const monotonic_clock::duration interval,
564 const monotonic_clock::duration offset =
565 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800566 return NewPhasedLoop(
567 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
568 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 }
570
571 void OnRun(::std::function<void()> on_run) override {
Austin Schuhcc6070c2020-10-10 20:25:56 -0700572 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
573 ScopedMarkRealtimeRestorer rt(priority() > 0);
574 on_run();
575 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 }
577
Austin Schuh217a9782019-12-21 23:02:50 -0800578 const Node *node() const override { return node_; }
579
James Kuszmaul3ae42262019-11-08 12:33:41 -0800580 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700581 name_ = std::string(name);
582 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800583 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700584
585 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
586
Austin Schuh39788ff2019-12-01 18:22:57 -0800587 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800589 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 }
591
Austin Schuh39788ff2019-12-01 18:22:57 -0800592 int priority() const override { return priority_; }
593
Brian Silverman6a54ff32020-04-28 16:41:39 -0700594 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
595 CHECK(!is_running()) << ": Cannot set affinity while running.";
596 }
597
Tyler Chatow67ddb032020-01-12 14:30:04 -0800598 void Setup() {
599 MaybeScheduleTimingReports();
600 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800601 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700602 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800603 }
604 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800605
Brian Silverman4f4e0612020-08-12 19:54:41 -0700606 int NumberBuffers(const Channel *channel) override;
607
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800609 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800610 friend class SimulatedPhasedLoopHandler;
611 friend class SimulatedWatcher;
612
613 void HandleEvent() {
614 while (true) {
615 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
616 break;
617 }
618
619 EventLoopEvent *event = PopEvent();
620 event->HandleEvent();
621 }
622 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800623
Austin Schuh39788ff2019-12-01 18:22:57 -0800624 pid_t GetTid() override { return tid_; }
625
Alex Perrycb7da4b2019-08-28 19:35:56 -0700626 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800627 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
629 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
630 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631
632 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800633
634 int priority_ = 0;
635
636 bool has_setup_ = false;
637
Austin Schuh7d87b672019-12-01 20:23:49 -0800638 std::chrono::nanoseconds send_delay_;
639
Austin Schuh217a9782019-12-21 23:02:50 -0800640 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800641 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800642
643 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700644 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645};
646
Austin Schuh7d87b672019-12-01 20:23:49 -0800647void SimulatedEventLoopFactory::set_send_delay(
648 std::chrono::nanoseconds send_delay) {
649 send_delay_ = send_delay;
650 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
651 raw_event_loops_) {
652 reinterpret_cast<SimulatedEventLoop *>(loop.first)
653 ->set_send_delay(send_delay_);
654 }
655}
656
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657void SimulatedEventLoop::MakeRawWatcher(
658 const Channel *channel,
659 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800660 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800661
Austin Schuh8bd96322020-02-13 21:18:22 -0800662 std::unique_ptr<SimulatedWatcher> shm_watcher(
663 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800664
665 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
666 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667}
668
669std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
670 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800671 TakeSender(channel);
672
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673 return GetSimulatedChannel(channel)->MakeRawSender(this);
674}
675
676std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
677 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800678 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800679
Austin Schuhca4828c2019-12-28 14:21:35 -0800680 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
681 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
682 << "\", \"type\": \"" << channel->type()->string_view()
683 << "\" } is not able to be fetched on this node. Check your "
684 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800685 }
686
Austin Schuh39788ff2019-12-01 18:22:57 -0800687 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688}
689
690SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
691 const Channel *channel) {
692 auto it = channels_->find(SimpleChannel(channel));
693 if (it == channels_->end()) {
694 it = channels_
695 ->emplace(SimpleChannel(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700696 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
697 channel, scheduler_,
698 std::chrono::nanoseconds(
699 configuration()->channel_storage_duration()))))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700700 .first;
701 }
702 return it->second.get();
703}
704
Brian Silverman4f4e0612020-08-12 19:54:41 -0700705int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
706 return GetSimulatedChannel(channel)->number_buffers();
707}
708
Austin Schuh7d87b672019-12-01 20:23:49 -0800709SimulatedWatcher::SimulatedWatcher(
710 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800711 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800712 std::function<void(const Context &context, const void *message)> fn)
713 : WatcherState(simulated_event_loop, channel, std::move(fn)),
714 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700715 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800716 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700717 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800718 token_(scheduler_->InvalidToken()) {}
719
720SimulatedWatcher::~SimulatedWatcher() {
721 simulated_event_loop_->RemoveEvent(&event_);
722 if (token_ != scheduler_->InvalidToken()) {
723 scheduler_->Deschedule(token_);
724 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700725 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800726}
727
728void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800729 monotonic_clock::time_point event_time =
730 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800731
732 // Messages are queued in order. If we are the first, add ourselves.
733 // Otherwise, don't.
734 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800735 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800736 simulated_event_loop_->AddEvent(&event_);
737
738 DoSchedule(event_time);
739 }
740
741 msgs_.emplace_back(message);
742}
743
744void SimulatedWatcher::HandleEvent() {
745 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
746
747 const monotonic_clock::time_point monotonic_now =
748 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800749 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700750 if (simulated_event_loop_->log_impl_) {
751 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800752 }
Austin Schuhad154822019-12-27 15:45:13 -0800753 Context context = msgs_.front()->context;
754
Brian Silverman4f4e0612020-08-12 19:54:41 -0700755 if (channel_->read_method() != ReadMethod::PIN) {
756 context.buffer_index = -1;
757 }
Austin Schuhad154822019-12-27 15:45:13 -0800758 if (context.remote_queue_index == 0xffffffffu) {
759 context.remote_queue_index = context.queue_index;
760 }
761 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
762 context.monotonic_remote_time = context.monotonic_event_time;
763 }
764 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
765 context.realtime_remote_time = context.realtime_event_time;
766 }
767
Austin Schuhcc6070c2020-10-10 20:25:56 -0700768 {
769 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
770 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
771 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800772
773 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700774 if (token_ != scheduler_->InvalidToken()) {
775 scheduler_->Deschedule(token_);
776 token_ = scheduler_->InvalidToken();
777 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800778 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800779 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800780 simulated_event_loop_->AddEvent(&event_);
781
782 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800783 }
784}
785
786void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700787 CHECK(token_ == scheduler_->InvalidToken())
788 << ": May not schedule multiple times";
789 token_ = scheduler_->Schedule(
790 event_time + simulated_event_loop_->send_delay(), [this]() {
791 DCHECK(token_ != scheduler_->InvalidToken());
792 token_ = scheduler_->InvalidToken();
793 simulated_event_loop_->HandleEvent();
794 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800795}
796
797void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700798 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800799 watcher->SetSimulatedChannel(this);
800 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700801}
802
803::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
804 EventLoop *event_loop) {
805 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
806}
807
Austin Schuh39788ff2019-12-01 18:22:57 -0800808::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
809 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700810 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800811 ::std::unique_ptr<SimulatedFetcher> fetcher(
812 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700813 fetchers_.push_back(fetcher.get());
814 return ::std::move(fetcher);
815}
816
Austin Schuhad154822019-12-27 15:45:13 -0800817uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
818 const uint32_t queue_index = next_queue_index_.index();
819 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800820 message->context.data = message->data(channel()->max_size()) +
821 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700822 next_queue_index_ = next_queue_index_.Increment();
823
824 latest_message_ = message;
825 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800826 for (SimulatedWatcher *watcher : watchers_) {
827 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700828 }
829 }
830 for (auto &fetcher : fetchers_) {
831 fetcher->Enqueue(message);
832 }
Austin Schuhad154822019-12-27 15:45:13 -0800833
834 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700835}
836
837void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
838 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
839}
840
Austin Schuh39788ff2019-12-01 18:22:57 -0800841SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800842 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
843 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800844 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800845 simulated_event_loop_(simulated_event_loop),
846 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800847 scheduler_(scheduler),
848 token_(scheduler_->InvalidToken()) {}
849
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800850void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
851 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800852 // The allocations in here are due to infrastructure and don't count in the no
853 // mallocs in RT code.
854 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800855 Disable();
856 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800857 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800858 base_ = base;
859 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700860 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
861 DCHECK(token_ != scheduler_->InvalidToken());
862 token_ = scheduler_->InvalidToken();
863 simulated_event_loop_->HandleEvent();
864 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800865 event_.set_event_time(base_);
866 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800867}
868
869void SimulatedTimerHandler::HandleEvent() {
870 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800871 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800872 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700873 if (simulated_event_loop_->log_impl_) {
874 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800875 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700876 if (token_ != scheduler_->InvalidToken()) {
877 scheduler_->Deschedule(token_);
878 token_ = scheduler_->InvalidToken();
879 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800880 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
881 // Reschedule.
882 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700883 token_ = scheduler_->Schedule(base_, [this]() {
884 DCHECK(token_ != scheduler_->InvalidToken());
885 token_ = scheduler_->InvalidToken();
886 simulated_event_loop_->HandleEvent();
887 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800888 event_.set_event_time(base_);
889 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800890 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800891
Austin Schuhcc6070c2020-10-10 20:25:56 -0700892 {
893 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
894 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
895 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800896}
897
Austin Schuh7d87b672019-12-01 20:23:49 -0800898void SimulatedTimerHandler::Disable() {
899 simulated_event_loop_->RemoveEvent(&event_);
900 if (token_ != scheduler_->InvalidToken()) {
901 scheduler_->Deschedule(token_);
902 token_ = scheduler_->InvalidToken();
903 }
904}
905
Austin Schuh39788ff2019-12-01 18:22:57 -0800906SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800907 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
908 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800909 const monotonic_clock::duration offset)
910 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
911 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800912 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800913 scheduler_(scheduler),
914 token_(scheduler_->InvalidToken()) {}
915
Austin Schuh7d87b672019-12-01 20:23:49 -0800916SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
917 if (token_ != scheduler_->InvalidToken()) {
918 scheduler_->Deschedule(token_);
919 token_ = scheduler_->InvalidToken();
920 }
921 simulated_event_loop_->RemoveEvent(&event_);
922}
923
924void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800925 monotonic_clock::time_point monotonic_now =
926 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800927 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700928 if (simulated_event_loop_->log_impl_) {
929 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800930 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700931
932 {
933 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
934 Call([monotonic_now]() { return monotonic_now; },
935 [this](monotonic_clock::time_point sleep_time) {
936 Schedule(sleep_time);
937 });
938 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800939}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800940
Austin Schuh7d87b672019-12-01 20:23:49 -0800941void SimulatedPhasedLoopHandler::Schedule(
942 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800943 // The allocations in here are due to infrastructure and don't count in the no
944 // mallocs in RT code.
945 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700946 if (token_ != scheduler_->InvalidToken()) {
947 scheduler_->Deschedule(token_);
948 token_ = scheduler_->InvalidToken();
949 }
950 token_ = scheduler_->Schedule(sleep_time, [this]() {
951 DCHECK(token_ != scheduler_->InvalidToken());
952 token_ = scheduler_->InvalidToken();
953 simulated_event_loop_->HandleEvent();
954 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800955 event_.set_event_time(sleep_time);
956 simulated_event_loop_->AddEvent(&event_);
957}
958
Austin Schuhac0771c2020-01-07 18:36:30 -0800959NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800960 EventSchedulerScheduler *scheduler_scheduler,
961 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800962 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
963 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800964 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
965 scheduler_scheduler->AddEventScheduler(&scheduler_);
966}
Austin Schuhac0771c2020-01-07 18:36:30 -0800967
Alex Perrycb7da4b2019-08-28 19:35:56 -0700968SimulatedEventLoopFactory::SimulatedEventLoopFactory(
969 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800970 : configuration_(CHECK_NOTNULL(configuration)),
971 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800972 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800973 node_factories_.emplace_back(new NodeEventLoopFactory(
974 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800975 }
Austin Schuh898f4972020-01-11 17:21:25 -0800976
977 if (configuration::MultiNode(configuration)) {
978 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
979 }
Austin Schuh15649d62019-12-28 16:36:38 -0800980}
981
Alex Perrycb7da4b2019-08-28 19:35:56 -0700982SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
983
Austin Schuhac0771c2020-01-07 18:36:30 -0800984NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
985 const Node *node) {
986 auto result = std::find_if(
987 node_factories_.begin(), node_factories_.end(),
988 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
989 return node_factory->node() == node;
990 });
991
992 CHECK(result != node_factories_.end())
993 << ": Failed to find node " << FlatbufferToJson(node);
994
995 return result->get();
996}
997
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800998::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800999 std::string_view name, const Node *node) {
1000 if (node == nullptr) {
1001 CHECK(!configuration::MultiNode(configuration()))
1002 << ": Can't make a single node event loop in a multi-node world.";
1003 } else {
1004 CHECK(configuration::MultiNode(configuration()))
1005 << ": Can't make a multi-node event loop in a single-node world.";
1006 }
1007 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1008}
1009
1010::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001011 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001012 CHECK(!scheduler_.is_running())
1013 << ": Can't create an event loop while running";
1014
Austin Schuh39788ff2019-12-01 18:22:57 -08001015 pid_t tid = tid_;
1016 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001017 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001018 &scheduler_, this, &channels_, factory_->configuration(),
1019 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001020 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001021 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001022 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001023}
1024
1025void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1026 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1027 raw_event_loops_) {
1028 event_loop.second(true);
1029 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001030 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001031 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1032 raw_event_loops_) {
1033 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001034 }
1035}
1036
1037void SimulatedEventLoopFactory::Run() {
1038 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1039 raw_event_loops_) {
1040 event_loop.second(true);
1041 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001042 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001043 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1044 raw_event_loops_) {
1045 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001046 }
1047}
1048
Austin Schuh6f3babe2020-01-26 20:34:50 -08001049void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001050 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001051 bridge_->DisableForwarding(channel);
1052}
1053
Austin Schuh4c3b9702020-08-30 11:34:55 -07001054void SimulatedEventLoopFactory::DisableStatistics() {
1055 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1056 bridge_->DisableStatistics();
1057}
1058
Alex Perrycb7da4b2019-08-28 19:35:56 -07001059} // namespace aos