blob: f59fc2366642cdf4432bd66c00d3411cff17d055 [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"
Austin Schuh094d09b2020-11-20 23:26:52 -080011#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070013#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/util/phased_loop.h"
15
16namespace aos {
17
Brian Silverman661eb8d2020-08-12 19:41:01 -070018class SimulatedEventLoop;
19class SimulatedFetcher;
20class SimulatedChannel;
21
22namespace {
23
Austin Schuhcc6070c2020-10-10 20:25:56 -070024class ScopedMarkRealtimeRestorer {
25 public:
26 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
27 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
28
29 private:
30 const bool rt_;
31 const bool prior_;
32};
33
Alex Perrycb7da4b2019-08-28 19:35:56 -070034// Container for both a message, and the context for it for simulation. This
35// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070036struct SimulatedMessage final {
37 SimulatedMessage(const SimulatedMessage &) = delete;
38 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
39
40 // Creates a SimulatedMessage with size bytes of storage.
41 // This is a shared_ptr so we don't have to implement refcounting or copying.
42 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
43
Alex Perrycb7da4b2019-08-28 19:35:56 -070044 // Context for the data.
45 Context context;
46
Brian Silverman661eb8d2020-08-12 19:41:01 -070047 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070048
Alex Perrycb7da4b2019-08-28 19:35:56 -070049 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080050 char *data(size_t buffer_size) {
51 return RoundChannelData(&actual_data[0], buffer_size);
52 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070053
Brian Silvermana1652f32020-01-29 20:41:44 -080054 // Then the data, including padding on the end so we can align the buffer we
55 // actually return from data().
56 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070057
58 private:
59 SimulatedMessage(SimulatedChannel *channel_in);
60 ~SimulatedMessage();
61
62 static void DestroyAndFree(SimulatedMessage *p) {
63 p->~SimulatedMessage();
64 free(p);
65 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070066};
67
Brian Silverman661eb8d2020-08-12 19:41:01 -070068} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080069
Brian Silverman661eb8d2020-08-12 19:41:01 -070070// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
71// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080072class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080073 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080074 SimulatedWatcher(
75 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
76 const Channel *channel,
77 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080078
Austin Schuh7d87b672019-12-01 20:23:49 -080079 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080080
Austin Schuh8fb315a2020-11-19 22:33:58 -080081 bool has_run() const;
82
Austin Schuh39788ff2019-12-01 18:22:57 -080083 void Startup(EventLoop * /*event_loop*/) override {}
84
Austin Schuh7d87b672019-12-01 20:23:49 -080085 void Schedule(std::shared_ptr<SimulatedMessage> message);
86
87 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080088
89 void SetSimulatedChannel(SimulatedChannel *channel) {
90 simulated_channel_ = channel;
91 }
92
93 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080094 void DoSchedule(monotonic_clock::time_point event_time);
95
96 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
97
Brian Silverman4f4e0612020-08-12 19:54:41 -070098 SimulatedEventLoop *const simulated_event_loop_;
99 const Channel *const channel_;
100 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800101 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800102 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 SimulatedChannel *simulated_channel_ = nullptr;
104};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105
106class SimulatedChannel {
107 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800108 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800110 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700111 channel_storage_duration_(channel_storage_duration),
112 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
113 available_buffer_indices_.reserve(number_buffers());
114 for (int i = 0; i < number_buffers(); ++i) {
115 available_buffer_indices_.push_back(i);
116 }
117 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118
Brian Silverman661eb8d2020-08-12 19:41:01 -0700119 ~SimulatedChannel() {
120 latest_message_.reset();
121 CHECK_EQ(static_cast<size_t>(number_buffers()),
122 available_buffer_indices_.size());
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800123 CHECK_EQ(0u, fetchers_.size())
124 << configuration::StrippedChannelToString(channel());
125 CHECK_EQ(0u, watchers_.size())
126 << configuration::StrippedChannelToString(channel());
127 CHECK_EQ(0, sender_count_)
128 << configuration::StrippedChannelToString(channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700129 }
130
131 // The number of messages we pretend to have in the queue.
132 int queue_size() const {
133 return channel()->frequency() *
134 std::chrono::duration_cast<std::chrono::duration<double>>(
135 channel_storage_duration_)
136 .count();
137 }
138
139 // The number of extra buffers (beyond the queue) we pretend to have.
140 int number_scratch_buffers() const {
141 // We need to start creating messages before we know how many
142 // senders+readers we'll have, so we need to just pick something which is
143 // always big enough.
144 return 50;
145 }
146
147 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
148
149 int GetBufferIndex() {
150 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
151 const int result = available_buffer_indices_.back();
152 available_buffer_indices_.pop_back();
153 return result;
154 }
155
156 void FreeBufferIndex(int i) {
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800157 // This extra checking has a large performance hit with msan, so just skip
158 // it.
159#if !__has_feature(memory_sanitizer)
Brian Silverman661eb8d2020-08-12 19:41:01 -0700160 DCHECK(std::find(available_buffer_indices_.begin(),
161 available_buffer_indices_.end(),
162 i) == available_buffer_indices_.end())
163 << ": Buffer is not in use: " << i;
Brian Silvermanf3e6df22021-01-19 15:02:21 -0800164#endif
Brian Silverman661eb8d2020-08-12 19:41:01 -0700165 available_buffer_indices_.push_back(i);
166 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700167
168 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800169 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700170
171 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800172 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173
174 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800175 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800176
Austin Schuh7d87b672019-12-01 20:23:49 -0800177 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800178 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
179 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180
Austin Schuhad154822019-12-27 15:45:13 -0800181 // Sends the message to all the connected receivers and fetchers. Returns the
182 // sent queue index.
183 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184
185 // Unregisters a fetcher.
186 void UnregisterFetcher(SimulatedFetcher *fetcher);
187
188 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
189
Austin Schuh39788ff2019-12-01 18:22:57 -0800190 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800192 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800193 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700194 }
195
Austin Schuh39788ff2019-12-01 18:22:57 -0800196 const Channel *channel() const { return channel_; }
197
Austin Schuhe516ab02020-05-06 21:37:04 -0700198 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700199 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700200 if (sender_count_ >= channel()->num_senders()) {
201 LOG(FATAL) << "Failed to create sender on "
202 << configuration::CleanedChannelToString(channel())
203 << ", too many senders.";
204 }
205 ++sender_count_;
206 }
Brian Silverman77162972020-08-12 19:52:40 -0700207
Austin Schuhe516ab02020-05-06 21:37:04 -0700208 void CountSenderDestroyed() {
209 --sender_count_;
210 CHECK_GE(sender_count_, 0);
211 }
212
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213 private:
Brian Silverman77162972020-08-12 19:52:40 -0700214 void CheckBufferCount() {
215 int reader_count = 0;
216 if (channel()->read_method() == ReadMethod::PIN) {
217 reader_count = watchers_.size() + fetchers_.size();
218 }
219 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
220 }
221
222 void CheckReaderCount() {
223 if (channel()->read_method() != ReadMethod::PIN) {
224 return;
225 }
226 CheckBufferCount();
227 const int reader_count = watchers_.size() + fetchers_.size();
228 if (reader_count >= channel()->num_readers()) {
229 LOG(FATAL) << "Failed to create reader on "
230 << configuration::CleanedChannelToString(channel())
231 << ", too many readers.";
232 }
233 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700234
235 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700236 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
238 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800239 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240
241 // List of all fetchers.
242 ::std::vector<SimulatedFetcher *> fetchers_;
243 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700244
245 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700246
247 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700248
249 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700250};
251
252namespace {
253
Brian Silverman661eb8d2020-08-12 19:41:01 -0700254std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
255 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800256 // The allocations in here are due to infrastructure and don't count in the no
257 // mallocs in RT code.
258 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700259 const size_t size = channel->max_size();
260 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800261 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800264 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265
Brian Silverman661eb8d2020-08-12 19:41:01 -0700266 return std::shared_ptr<SimulatedMessage>(message,
267 &SimulatedMessage::DestroyAndFree);
268}
269
270SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
271 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700272 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700273}
274
275SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700276 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277}
278
279class SimulatedSender : public RawSender {
280 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800281 SimulatedSender(SimulatedChannel *simulated_channel,
282 SimulatedEventLoop *event_loop);
283 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284
285 void *data() override {
286 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700287 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800289 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290 }
291
292 size_t size() override { return simulated_channel_->max_size(); }
293
Austin Schuhad154822019-12-27 15:45:13 -0800294 bool DoSend(size_t length,
295 aos::monotonic_clock::time_point monotonic_remote_time,
296 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800297 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298
Austin Schuhad154822019-12-27 15:45:13 -0800299 bool DoSend(const void *msg, size_t size,
300 aos::monotonic_clock::time_point monotonic_remote_time,
301 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800302 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303
Brian Silverman4f4e0612020-08-12 19:54:41 -0700304 int buffer_index() override {
305 // First, ensure message_ is allocated.
306 data();
307 return message_->context.buffer_index;
308 }
309
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310 private:
311 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800312 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313
314 std::shared_ptr<SimulatedMessage> message_;
315};
316} // namespace
317
318class SimulatedFetcher : public RawFetcher {
319 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800320 explicit SimulatedFetcher(EventLoop *event_loop,
321 SimulatedChannel *simulated_channel)
322 : RawFetcher(event_loop, simulated_channel->channel()),
323 simulated_channel_(simulated_channel) {}
324 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325
Austin Schuh39788ff2019-12-01 18:22:57 -0800326 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800327 // The allocations in here are due to infrastructure and don't count in the
328 // no mallocs in RT code.
329 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800330 if (msgs_.size() == 0) {
331 return std::make_pair(false, monotonic_clock::min_time);
332 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700333
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700334 CHECK(!fell_behind_) << ": Got behind on "
335 << configuration::StrippedChannelToString(
336 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700337
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338 SetMsg(msgs_.front());
339 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800340 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700341 }
342
Austin Schuh39788ff2019-12-01 18:22:57 -0800343 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800344 // The allocations in here are due to infrastructure and don't count in the
345 // no mallocs in RT code.
346 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800348 // TODO(austin): Can we just do this logic unconditionally? It is a lot
349 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800350 if (!msg_ && simulated_channel_->latest_message()) {
351 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800352 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800354 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355 }
356 }
357
358 // We've had a message enqueued, so we don't need to go looking for the
359 // latest message from before we started.
360 SetMsg(msgs_.back());
361 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700362 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800363 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 }
365
366 private:
367 friend class SimulatedChannel;
368
369 // Updates the state inside RawFetcher to point to the data in msg_.
370 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
371 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700372 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700373 if (channel()->read_method() != ReadMethod::PIN) {
374 context_.buffer_index = -1;
375 }
Austin Schuhad154822019-12-27 15:45:13 -0800376 if (context_.remote_queue_index == 0xffffffffu) {
377 context_.remote_queue_index = context_.queue_index;
378 }
379 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
380 context_.monotonic_remote_time = context_.monotonic_event_time;
381 }
382 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
383 context_.realtime_remote_time = context_.realtime_event_time;
384 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385 }
386
387 // Internal method for Simulation to add a message to the buffer.
388 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
389 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700390 if (fell_behind_ ||
391 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
392 fell_behind_ = true;
393 // Might as well empty out all the intermediate messages now.
394 while (msgs_.size() > 1) {
395 msgs_.pop_front();
396 }
397 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700398 }
399
Austin Schuhac0771c2020-01-07 18:36:30 -0800400 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 std::shared_ptr<SimulatedMessage> msg_;
402
403 // Messages queued up but not in use.
404 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700405
406 // Whether we're currently "behind", which means a FetchNext call will fail.
407 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408};
409
410class SimulatedTimerHandler : public TimerHandler {
411 public:
412 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800413 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800414 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800415 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416
417 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800418 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800420 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700421
Austin Schuh7d87b672019-12-01 20:23:49 -0800422 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800425 SimulatedEventLoop *simulated_event_loop_;
426 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700427 EventScheduler *scheduler_;
428 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800429
Alex Perrycb7da4b2019-08-28 19:35:56 -0700430 monotonic_clock::time_point base_;
431 monotonic_clock::duration repeat_offset_;
432};
433
434class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
435 public:
436 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800437 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438 ::std::function<void(int)> fn,
439 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800440 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800441 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
Austin Schuh7d87b672019-12-01 20:23:49 -0800443 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444
Austin Schuh7d87b672019-12-01 20:23:49 -0800445 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
447 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800448 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800449 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450
Austin Schuh39788ff2019-12-01 18:22:57 -0800451 EventScheduler *scheduler_;
452 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700453};
454
455class SimulatedEventLoop : public EventLoop {
456 public:
457 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700458 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
460 *channels,
461 const Configuration *configuration,
462 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800463 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800464 const Node *node, pid_t tid)
Austin Schuh20ac95d2020-12-05 17:24:19 -0800465 : EventLoop(CHECK_NOTNULL(configuration),
466 node_event_loop_factory->boot_uuid()),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800468 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800470 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800471 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800472 tid_(tid) {
473 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
474 if (!has_setup_) {
475 Setup();
476 has_setup_ = true;
477 }
478 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800479 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800480 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 }
482 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800483 // Trigger any remaining senders or fetchers to be cleared before destroying
484 // the event loop so the book keeping matches.
485 timing_report_sender_.reset();
486
487 // Force everything with a registered fd with epoll to be destroyed now.
488 timers_.clear();
489 phased_loops_.clear();
490 watchers_.clear();
491
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
493 ++it) {
494 if (it->first == this) {
495 raw_event_loops_->erase(it);
496 break;
497 }
498 }
499 }
500
Austin Schuh8fb315a2020-11-19 22:33:58 -0800501 bool has_run() const { return has_run_; }
502
Austin Schuh7d87b672019-12-01 20:23:49 -0800503 std::chrono::nanoseconds send_delay() const { return send_delay_; }
504 void set_send_delay(std::chrono::nanoseconds send_delay) {
505 send_delay_ = send_delay;
506 }
507
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800509 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510 }
511
512 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800513 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514 }
515
516 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
517
518 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
519
520 void MakeRawWatcher(
521 const Channel *channel,
522 ::std::function<void(const Context &context, const void *message)>
523 watcher) override;
524
525 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800526 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800527 return NewTimer(::std::unique_ptr<TimerHandler>(
528 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529 }
530
531 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
532 const monotonic_clock::duration interval,
533 const monotonic_clock::duration offset =
534 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800535 return NewPhasedLoop(
536 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
537 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 }
539
540 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800541 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700542 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
543 ScopedMarkRealtimeRestorer rt(priority() > 0);
544 on_run();
545 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 }
547
Austin Schuh217a9782019-12-21 23:02:50 -0800548 const Node *node() const override { return node_; }
549
James Kuszmaul3ae42262019-11-08 12:33:41 -0800550 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700551 name_ = std::string(name);
552 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800553 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554
555 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
556
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800559 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 }
561
Austin Schuh39788ff2019-12-01 18:22:57 -0800562 int priority() const override { return priority_; }
563
Brian Silverman6a54ff32020-04-28 16:41:39 -0700564 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
565 CHECK(!is_running()) << ": Cannot set affinity while running.";
566 }
567
Tyler Chatow67ddb032020-01-12 14:30:04 -0800568 void Setup() {
569 MaybeScheduleTimingReports();
570 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800571 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700572 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800573 }
574 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800575
Brian Silverman4f4e0612020-08-12 19:54:41 -0700576 int NumberBuffers(const Channel *channel) override;
577
Alex Perrycb7da4b2019-08-28 19:35:56 -0700578 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800579 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800580 friend class SimulatedPhasedLoopHandler;
581 friend class SimulatedWatcher;
582
583 void HandleEvent() {
584 while (true) {
585 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
586 break;
587 }
588
589 EventLoopEvent *event = PopEvent();
590 event->HandleEvent();
591 }
592 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800593
Austin Schuh39788ff2019-12-01 18:22:57 -0800594 pid_t GetTid() override { return tid_; }
595
Alex Perrycb7da4b2019-08-28 19:35:56 -0700596 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800597 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
599 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
600 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601
602 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800603
604 int priority_ = 0;
605
606 bool has_setup_ = false;
607
Austin Schuh7d87b672019-12-01 20:23:49 -0800608 std::chrono::nanoseconds send_delay_;
609
Austin Schuh217a9782019-12-21 23:02:50 -0800610 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800611 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800612
613 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700614 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800615
616 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617};
618
Austin Schuh7d87b672019-12-01 20:23:49 -0800619void SimulatedEventLoopFactory::set_send_delay(
620 std::chrono::nanoseconds send_delay) {
621 send_delay_ = send_delay;
622 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
623 raw_event_loops_) {
624 reinterpret_cast<SimulatedEventLoop *>(loop.first)
625 ->set_send_delay(send_delay_);
626 }
627}
628
Alex Perrycb7da4b2019-08-28 19:35:56 -0700629void SimulatedEventLoop::MakeRawWatcher(
630 const Channel *channel,
631 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800632 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800633
Austin Schuh8bd96322020-02-13 21:18:22 -0800634 std::unique_ptr<SimulatedWatcher> shm_watcher(
635 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800636
637 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
638 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800639
640 // Order of operations gets kinda wonky if we let people make watchers after
641 // running once. If someone has a valid use case, we can reconsider.
642 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643}
644
645std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
646 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800647 TakeSender(channel);
648
Alex Perrycb7da4b2019-08-28 19:35:56 -0700649 return GetSimulatedChannel(channel)->MakeRawSender(this);
650}
651
652std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
653 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800654 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800655
Austin Schuhca4828c2019-12-28 14:21:35 -0800656 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
657 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
658 << "\", \"type\": \"" << channel->type()->string_view()
659 << "\" } is not able to be fetched on this node. Check your "
660 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800661 }
662
Austin Schuh39788ff2019-12-01 18:22:57 -0800663 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700664}
665
666SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
667 const Channel *channel) {
668 auto it = channels_->find(SimpleChannel(channel));
669 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800670 it =
671 channels_
672 ->emplace(
673 SimpleChannel(channel),
674 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
675 channel, std::chrono::nanoseconds(
676 configuration()->channel_storage_duration()))))
677 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700678 }
679 return it->second.get();
680}
681
Brian Silverman4f4e0612020-08-12 19:54:41 -0700682int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
683 return GetSimulatedChannel(channel)->number_buffers();
684}
685
Austin Schuh7d87b672019-12-01 20:23:49 -0800686SimulatedWatcher::SimulatedWatcher(
687 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800688 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 std::function<void(const Context &context, const void *message)> fn)
690 : WatcherState(simulated_event_loop, channel, std::move(fn)),
691 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700692 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800693 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700694 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800695 token_(scheduler_->InvalidToken()) {}
696
697SimulatedWatcher::~SimulatedWatcher() {
698 simulated_event_loop_->RemoveEvent(&event_);
699 if (token_ != scheduler_->InvalidToken()) {
700 scheduler_->Deschedule(token_);
701 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700702 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800703}
704
Austin Schuh8fb315a2020-11-19 22:33:58 -0800705bool SimulatedWatcher::has_run() const {
706 return simulated_event_loop_->has_run();
707}
708
Austin Schuh7d87b672019-12-01 20:23:49 -0800709void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800710 monotonic_clock::time_point event_time =
711 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800712
713 // Messages are queued in order. If we are the first, add ourselves.
714 // Otherwise, don't.
715 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800716 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800717 simulated_event_loop_->AddEvent(&event_);
718
719 DoSchedule(event_time);
720 }
721
722 msgs_.emplace_back(message);
723}
724
725void SimulatedWatcher::HandleEvent() {
726 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
727
728 const monotonic_clock::time_point monotonic_now =
729 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800730 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700731 if (simulated_event_loop_->log_impl_) {
732 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800733 }
Austin Schuhad154822019-12-27 15:45:13 -0800734 Context context = msgs_.front()->context;
735
Brian Silverman4f4e0612020-08-12 19:54:41 -0700736 if (channel_->read_method() != ReadMethod::PIN) {
737 context.buffer_index = -1;
738 }
Austin Schuhad154822019-12-27 15:45:13 -0800739 if (context.remote_queue_index == 0xffffffffu) {
740 context.remote_queue_index = context.queue_index;
741 }
742 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
743 context.monotonic_remote_time = context.monotonic_event_time;
744 }
745 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
746 context.realtime_remote_time = context.realtime_event_time;
747 }
748
Austin Schuhcc6070c2020-10-10 20:25:56 -0700749 {
750 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
751 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
752 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800753
754 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700755 if (token_ != scheduler_->InvalidToken()) {
756 scheduler_->Deschedule(token_);
757 token_ = scheduler_->InvalidToken();
758 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800759 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800760 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800761 simulated_event_loop_->AddEvent(&event_);
762
763 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800764 }
765}
766
767void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700768 CHECK(token_ == scheduler_->InvalidToken())
769 << ": May not schedule multiple times";
770 token_ = scheduler_->Schedule(
771 event_time + simulated_event_loop_->send_delay(), [this]() {
772 DCHECK(token_ != scheduler_->InvalidToken());
773 token_ = scheduler_->InvalidToken();
774 simulated_event_loop_->HandleEvent();
775 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800776}
777
778void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700779 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800780 watcher->SetSimulatedChannel(this);
781 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700782}
783
784::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800785 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
787}
788
Austin Schuh39788ff2019-12-01 18:22:57 -0800789::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
790 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700791 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800792 ::std::unique_ptr<SimulatedFetcher> fetcher(
793 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700794 fetchers_.push_back(fetcher.get());
795 return ::std::move(fetcher);
796}
797
Austin Schuhad154822019-12-27 15:45:13 -0800798uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
799 const uint32_t queue_index = next_queue_index_.index();
800 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800801 message->context.data = message->data(channel()->max_size()) +
802 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700803 next_queue_index_ = next_queue_index_.Increment();
804
805 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800806 for (SimulatedWatcher *watcher : watchers_) {
807 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800808 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700809 }
810 }
811 for (auto &fetcher : fetchers_) {
812 fetcher->Enqueue(message);
813 }
Austin Schuhad154822019-12-27 15:45:13 -0800814
815 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700816}
817
818void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
819 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
820}
821
Austin Schuh8fb315a2020-11-19 22:33:58 -0800822SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
823 SimulatedEventLoop *event_loop)
824 : RawSender(event_loop, simulated_channel->channel()),
825 simulated_channel_(simulated_channel),
826 event_loop_(event_loop) {
827 simulated_channel_->CountSenderCreated();
828}
829
830SimulatedSender::~SimulatedSender() {
831 simulated_channel_->CountSenderDestroyed();
832}
833
834bool SimulatedSender::DoSend(
835 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
836 aos::realtime_clock::time_point realtime_remote_time,
837 uint32_t remote_queue_index) {
838 // The allocations in here are due to infrastructure and don't count in the
839 // no mallocs in RT code.
840 ScopedNotRealtime nrt;
841 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
842 message_->context.monotonic_event_time = event_loop_->monotonic_now();
843 message_->context.monotonic_remote_time = monotonic_remote_time;
844 message_->context.remote_queue_index = remote_queue_index;
845 message_->context.realtime_event_time = event_loop_->realtime_now();
846 message_->context.realtime_remote_time = realtime_remote_time;
847 CHECK_LE(length, message_->context.size);
848 message_->context.size = length;
849
850 // TODO(austin): Track sending too fast.
851 sent_queue_index_ = simulated_channel_->Send(message_);
852 monotonic_sent_time_ = event_loop_->monotonic_now();
853 realtime_sent_time_ = event_loop_->realtime_now();
854
855 // Drop the reference to the message so that we allocate a new message for
856 // next time. Otherwise we will continue to reuse the same memory for all
857 // messages and corrupt it.
858 message_.reset();
859 return true;
860}
861
862bool SimulatedSender::DoSend(
863 const void *msg, size_t size,
864 aos::monotonic_clock::time_point monotonic_remote_time,
865 aos::realtime_clock::time_point realtime_remote_time,
866 uint32_t remote_queue_index) {
Austin Schuh102667e2020-12-11 20:13:28 -0800867 CHECK_LE(size, this->size())
868 << ": Attempting to send too big a message on "
869 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800870
871 // This is wasteful, but since flatbuffers fill from the back end of the
872 // queue, we need it to be full sized.
873 message_ = SimulatedMessage::Make(simulated_channel_);
874
875 // Now fill in the message. size is already populated above, and
876 // queue_index will be populated in simulated_channel_. Put this at the
877 // back of the data segment.
878 memcpy(message_->data(simulated_channel_->max_size()) +
879 simulated_channel_->max_size() - size,
880 msg, size);
881
882 return DoSend(size, monotonic_remote_time, realtime_remote_time,
883 remote_queue_index);
884}
885
Austin Schuh39788ff2019-12-01 18:22:57 -0800886SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800887 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
888 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800889 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800890 simulated_event_loop_(simulated_event_loop),
891 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800892 scheduler_(scheduler),
893 token_(scheduler_->InvalidToken()) {}
894
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800895void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
896 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800897 // The allocations in here are due to infrastructure and don't count in the no
898 // mallocs in RT code.
899 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800900 Disable();
901 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800902 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800903 base_ = base;
904 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700905 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
906 DCHECK(token_ != scheduler_->InvalidToken());
907 token_ = scheduler_->InvalidToken();
908 simulated_event_loop_->HandleEvent();
909 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800910 event_.set_event_time(base_);
911 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800912}
913
914void SimulatedTimerHandler::HandleEvent() {
915 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800916 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800917 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700918 if (simulated_event_loop_->log_impl_) {
919 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800920 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700921 if (token_ != scheduler_->InvalidToken()) {
922 scheduler_->Deschedule(token_);
923 token_ = scheduler_->InvalidToken();
924 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800925 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
926 // Reschedule.
927 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700928 token_ = scheduler_->Schedule(base_, [this]() {
929 DCHECK(token_ != scheduler_->InvalidToken());
930 token_ = scheduler_->InvalidToken();
931 simulated_event_loop_->HandleEvent();
932 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800933 event_.set_event_time(base_);
934 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800935 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800936
Austin Schuhcc6070c2020-10-10 20:25:56 -0700937 {
938 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
939 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
940 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800941}
942
Austin Schuh7d87b672019-12-01 20:23:49 -0800943void SimulatedTimerHandler::Disable() {
944 simulated_event_loop_->RemoveEvent(&event_);
945 if (token_ != scheduler_->InvalidToken()) {
946 scheduler_->Deschedule(token_);
947 token_ = scheduler_->InvalidToken();
948 }
949}
950
Austin Schuh39788ff2019-12-01 18:22:57 -0800951SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800952 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
953 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800954 const monotonic_clock::duration offset)
955 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
956 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800957 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800958 scheduler_(scheduler),
959 token_(scheduler_->InvalidToken()) {}
960
Austin Schuh7d87b672019-12-01 20:23:49 -0800961SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
962 if (token_ != scheduler_->InvalidToken()) {
963 scheduler_->Deschedule(token_);
964 token_ = scheduler_->InvalidToken();
965 }
966 simulated_event_loop_->RemoveEvent(&event_);
967}
968
969void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800970 monotonic_clock::time_point monotonic_now =
971 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800972 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700973 if (simulated_event_loop_->log_impl_) {
974 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800975 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700976
977 {
978 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
979 Call([monotonic_now]() { return monotonic_now; },
980 [this](monotonic_clock::time_point sleep_time) {
981 Schedule(sleep_time);
982 });
983 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800984}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800985
Austin Schuh7d87b672019-12-01 20:23:49 -0800986void SimulatedPhasedLoopHandler::Schedule(
987 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800988 // The allocations in here are due to infrastructure and don't count in the no
989 // mallocs in RT code.
990 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700991 if (token_ != scheduler_->InvalidToken()) {
992 scheduler_->Deschedule(token_);
993 token_ = scheduler_->InvalidToken();
994 }
995 token_ = scheduler_->Schedule(sleep_time, [this]() {
996 DCHECK(token_ != scheduler_->InvalidToken());
997 token_ = scheduler_->InvalidToken();
998 simulated_event_loop_->HandleEvent();
999 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001000 event_.set_event_time(sleep_time);
1001 simulated_event_loop_->AddEvent(&event_);
1002}
1003
Austin Schuhac0771c2020-01-07 18:36:30 -08001004NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -08001005 EventSchedulerScheduler *scheduler_scheduler,
1006 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -08001007 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
1008 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -08001009 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
1010 scheduler_scheduler->AddEventScheduler(&scheduler_);
1011}
Austin Schuhac0771c2020-01-07 18:36:30 -08001012
Alex Perrycb7da4b2019-08-28 19:35:56 -07001013SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1014 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001015 : configuration_(CHECK_NOTNULL(configuration)),
1016 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001017 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001018 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001019 node_factories_.emplace_back(new NodeEventLoopFactory(
1020 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001021 }
Austin Schuh898f4972020-01-11 17:21:25 -08001022
1023 if (configuration::MultiNode(configuration)) {
1024 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1025 }
Austin Schuh15649d62019-12-28 16:36:38 -08001026}
1027
Alex Perrycb7da4b2019-08-28 19:35:56 -07001028SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1029
Austin Schuhac0771c2020-01-07 18:36:30 -08001030NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1031 const Node *node) {
1032 auto result = std::find_if(
1033 node_factories_.begin(), node_factories_.end(),
1034 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1035 return node_factory->node() == node;
1036 });
1037
1038 CHECK(result != node_factories_.end())
1039 << ": Failed to find node " << FlatbufferToJson(node);
1040
1041 return result->get();
1042}
1043
Austin Schuh87dd3832021-01-01 23:07:31 -08001044void SimulatedEventLoopFactory::SetTimeConverter(
1045 TimeConverter *time_converter) {
1046 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1047 factory->SetTimeConverter(time_converter);
1048 }
1049}
1050
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001051::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001052 std::string_view name, const Node *node) {
1053 if (node == nullptr) {
1054 CHECK(!configuration::MultiNode(configuration()))
1055 << ": Can't make a single node event loop in a multi-node world.";
1056 } else {
1057 CHECK(configuration::MultiNode(configuration()))
1058 << ": Can't make a multi-node event loop in a single-node world.";
1059 }
1060 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1061}
1062
1063::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001064 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001065 CHECK(!scheduler_.is_running())
1066 << ": Can't create an event loop while running";
1067
Austin Schuh39788ff2019-12-01 18:22:57 -08001068 pid_t tid = tid_;
1069 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001070 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001071 &scheduler_, this, &channels_, factory_->configuration(),
1072 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001073 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001074 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001075 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001076}
1077
Austin Schuhc0b0f722020-12-12 18:36:06 -08001078void NodeEventLoopFactory::Disconnect(const Node *other) {
1079 factory_->bridge_->Disconnect(node_, other);
1080}
1081void NodeEventLoopFactory::Connect(const Node *other) {
1082 factory_->bridge_->Connect(node_, other);
1083}
1084
Alex Perrycb7da4b2019-08-28 19:35:56 -07001085void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1086 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1087 raw_event_loops_) {
1088 event_loop.second(true);
1089 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001090 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001091 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1092 raw_event_loops_) {
1093 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001094 }
1095}
1096
1097void SimulatedEventLoopFactory::Run() {
1098 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1099 raw_event_loops_) {
1100 event_loop.second(true);
1101 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001102 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001103 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1104 raw_event_loops_) {
1105 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001106 }
1107}
1108
Austin Schuh87dd3832021-01-01 23:07:31 -08001109void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001110
Austin Schuh6f3babe2020-01-26 20:34:50 -08001111void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001112 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001113 bridge_->DisableForwarding(channel);
1114}
1115
Austin Schuh4c3b9702020-08-30 11:34:55 -07001116void SimulatedEventLoopFactory::DisableStatistics() {
1117 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1118 bridge_->DisableStatistics();
1119}
1120
Alex Perrycb7da4b2019-08-28 19:35:56 -07001121} // namespace aos