blob: b38829e142335df6e02f656443726a1d6ff83fee [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 Schuh83c7f702021-01-19 22:36:29 -0800465 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800467 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800469 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800470 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800471 tid_(tid) {
472 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
473 if (!has_setup_) {
474 Setup();
475 has_setup_ = true;
476 }
477 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800478 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800479 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 }
481 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800482 // Trigger any remaining senders or fetchers to be cleared before destroying
483 // the event loop so the book keeping matches.
484 timing_report_sender_.reset();
485
486 // Force everything with a registered fd with epoll to be destroyed now.
487 timers_.clear();
488 phased_loops_.clear();
489 watchers_.clear();
490
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
492 ++it) {
493 if (it->first == this) {
494 raw_event_loops_->erase(it);
495 break;
496 }
497 }
498 }
499
Austin Schuh8fb315a2020-11-19 22:33:58 -0800500 bool has_run() const { return has_run_; }
501
Austin Schuh7d87b672019-12-01 20:23:49 -0800502 std::chrono::nanoseconds send_delay() const { return send_delay_; }
503 void set_send_delay(std::chrono::nanoseconds send_delay) {
504 send_delay_ = send_delay;
505 }
506
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800508 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 }
510
511 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800512 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513 }
514
515 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
516
517 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
518
519 void MakeRawWatcher(
520 const Channel *channel,
521 ::std::function<void(const Context &context, const void *message)>
522 watcher) override;
523
524 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800525 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800526 return NewTimer(::std::unique_ptr<TimerHandler>(
527 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528 }
529
530 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
531 const monotonic_clock::duration interval,
532 const monotonic_clock::duration offset =
533 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800534 return NewPhasedLoop(
535 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
536 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 }
538
539 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800540 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700541 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
542 ScopedMarkRealtimeRestorer rt(priority() > 0);
543 on_run();
544 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 }
546
Austin Schuh217a9782019-12-21 23:02:50 -0800547 const Node *node() const override { return node_; }
548
James Kuszmaul3ae42262019-11-08 12:33:41 -0800549 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 name_ = std::string(name);
551 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800552 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553
554 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
555
Austin Schuh39788ff2019-12-01 18:22:57 -0800556 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559 }
560
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 int priority() const override { return priority_; }
562
Brian Silverman6a54ff32020-04-28 16:41:39 -0700563 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
564 CHECK(!is_running()) << ": Cannot set affinity while running.";
565 }
566
Tyler Chatow67ddb032020-01-12 14:30:04 -0800567 void Setup() {
568 MaybeScheduleTimingReports();
569 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800570 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700571 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800572 }
573 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800574
Brian Silverman4f4e0612020-08-12 19:54:41 -0700575 int NumberBuffers(const Channel *channel) override;
576
Austin Schuh83c7f702021-01-19 22:36:29 -0800577 const UUID &boot_uuid() const override {
578 return node_event_loop_factory_->boot_uuid();
579 }
580
Alex Perrycb7da4b2019-08-28 19:35:56 -0700581 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800582 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800583 friend class SimulatedPhasedLoopHandler;
584 friend class SimulatedWatcher;
585
586 void HandleEvent() {
587 while (true) {
588 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
589 break;
590 }
591
592 EventLoopEvent *event = PopEvent();
593 event->HandleEvent();
594 }
595 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597 pid_t GetTid() override { return tid_; }
598
Alex Perrycb7da4b2019-08-28 19:35:56 -0700599 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800600 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
602 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
603 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604
605 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800606
607 int priority_ = 0;
608
609 bool has_setup_ = false;
610
Austin Schuh7d87b672019-12-01 20:23:49 -0800611 std::chrono::nanoseconds send_delay_;
612
Austin Schuh217a9782019-12-21 23:02:50 -0800613 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800614 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800615
616 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700617 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800618
619 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620};
621
Austin Schuh7d87b672019-12-01 20:23:49 -0800622void SimulatedEventLoopFactory::set_send_delay(
623 std::chrono::nanoseconds send_delay) {
624 send_delay_ = send_delay;
625 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
626 raw_event_loops_) {
627 reinterpret_cast<SimulatedEventLoop *>(loop.first)
628 ->set_send_delay(send_delay_);
629 }
630}
631
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632void SimulatedEventLoop::MakeRawWatcher(
633 const Channel *channel,
634 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800635 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800636
Austin Schuh8bd96322020-02-13 21:18:22 -0800637 std::unique_ptr<SimulatedWatcher> shm_watcher(
638 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800639
640 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
641 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800642
643 // Order of operations gets kinda wonky if we let people make watchers after
644 // running once. If someone has a valid use case, we can reconsider.
645 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700646}
647
648std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
649 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800650 TakeSender(channel);
651
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652 return GetSimulatedChannel(channel)->MakeRawSender(this);
653}
654
655std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
656 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800657 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800658
Austin Schuhca4828c2019-12-28 14:21:35 -0800659 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
660 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
661 << "\", \"type\": \"" << channel->type()->string_view()
662 << "\" } is not able to be fetched on this node. Check your "
663 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800664 }
665
Austin Schuh39788ff2019-12-01 18:22:57 -0800666 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667}
668
669SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
670 const Channel *channel) {
671 auto it = channels_->find(SimpleChannel(channel));
672 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800673 it =
674 channels_
675 ->emplace(
676 SimpleChannel(channel),
677 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
678 channel, std::chrono::nanoseconds(
679 configuration()->channel_storage_duration()))))
680 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681 }
682 return it->second.get();
683}
684
Brian Silverman4f4e0612020-08-12 19:54:41 -0700685int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
686 return GetSimulatedChannel(channel)->number_buffers();
687}
688
Austin Schuh7d87b672019-12-01 20:23:49 -0800689SimulatedWatcher::SimulatedWatcher(
690 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800691 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800692 std::function<void(const Context &context, const void *message)> fn)
693 : WatcherState(simulated_event_loop, channel, std::move(fn)),
694 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700695 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800696 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700697 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800698 token_(scheduler_->InvalidToken()) {}
699
700SimulatedWatcher::~SimulatedWatcher() {
701 simulated_event_loop_->RemoveEvent(&event_);
702 if (token_ != scheduler_->InvalidToken()) {
703 scheduler_->Deschedule(token_);
704 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700705 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800706}
707
Austin Schuh8fb315a2020-11-19 22:33:58 -0800708bool SimulatedWatcher::has_run() const {
709 return simulated_event_loop_->has_run();
710}
711
Austin Schuh7d87b672019-12-01 20:23:49 -0800712void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800713 monotonic_clock::time_point event_time =
714 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800715
716 // Messages are queued in order. If we are the first, add ourselves.
717 // Otherwise, don't.
718 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800719 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800720 simulated_event_loop_->AddEvent(&event_);
721
722 DoSchedule(event_time);
723 }
724
725 msgs_.emplace_back(message);
726}
727
728void SimulatedWatcher::HandleEvent() {
729 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
730
731 const monotonic_clock::time_point monotonic_now =
732 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800733 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700734 if (simulated_event_loop_->log_impl_) {
735 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800736 }
Austin Schuhad154822019-12-27 15:45:13 -0800737 Context context = msgs_.front()->context;
738
Brian Silverman4f4e0612020-08-12 19:54:41 -0700739 if (channel_->read_method() != ReadMethod::PIN) {
740 context.buffer_index = -1;
741 }
Austin Schuhad154822019-12-27 15:45:13 -0800742 if (context.remote_queue_index == 0xffffffffu) {
743 context.remote_queue_index = context.queue_index;
744 }
745 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
746 context.monotonic_remote_time = context.monotonic_event_time;
747 }
748 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
749 context.realtime_remote_time = context.realtime_event_time;
750 }
751
Austin Schuhcc6070c2020-10-10 20:25:56 -0700752 {
753 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
754 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
755 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800756
757 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700758 if (token_ != scheduler_->InvalidToken()) {
759 scheduler_->Deschedule(token_);
760 token_ = scheduler_->InvalidToken();
761 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800762 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800763 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800764 simulated_event_loop_->AddEvent(&event_);
765
766 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800767 }
768}
769
770void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700771 CHECK(token_ == scheduler_->InvalidToken())
772 << ": May not schedule multiple times";
773 token_ = scheduler_->Schedule(
774 event_time + simulated_event_loop_->send_delay(), [this]() {
775 DCHECK(token_ != scheduler_->InvalidToken());
776 token_ = scheduler_->InvalidToken();
777 simulated_event_loop_->HandleEvent();
778 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800779}
780
781void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700782 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800783 watcher->SetSimulatedChannel(this);
784 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785}
786
787::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800788 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700789 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
790}
791
Austin Schuh39788ff2019-12-01 18:22:57 -0800792::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
793 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700794 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800795 ::std::unique_ptr<SimulatedFetcher> fetcher(
796 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700797 fetchers_.push_back(fetcher.get());
798 return ::std::move(fetcher);
799}
800
Austin Schuhad154822019-12-27 15:45:13 -0800801uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
802 const uint32_t queue_index = next_queue_index_.index();
803 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800804 message->context.data = message->data(channel()->max_size()) +
805 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700806 next_queue_index_ = next_queue_index_.Increment();
807
808 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800809 for (SimulatedWatcher *watcher : watchers_) {
810 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800811 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700812 }
813 }
814 for (auto &fetcher : fetchers_) {
815 fetcher->Enqueue(message);
816 }
Austin Schuhad154822019-12-27 15:45:13 -0800817
818 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700819}
820
821void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
822 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
823}
824
Austin Schuh8fb315a2020-11-19 22:33:58 -0800825SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
826 SimulatedEventLoop *event_loop)
827 : RawSender(event_loop, simulated_channel->channel()),
828 simulated_channel_(simulated_channel),
829 event_loop_(event_loop) {
830 simulated_channel_->CountSenderCreated();
831}
832
833SimulatedSender::~SimulatedSender() {
834 simulated_channel_->CountSenderDestroyed();
835}
836
837bool SimulatedSender::DoSend(
838 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
839 aos::realtime_clock::time_point realtime_remote_time,
840 uint32_t remote_queue_index) {
841 // The allocations in here are due to infrastructure and don't count in the
842 // no mallocs in RT code.
843 ScopedNotRealtime nrt;
844 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
845 message_->context.monotonic_event_time = event_loop_->monotonic_now();
846 message_->context.monotonic_remote_time = monotonic_remote_time;
847 message_->context.remote_queue_index = remote_queue_index;
848 message_->context.realtime_event_time = event_loop_->realtime_now();
849 message_->context.realtime_remote_time = realtime_remote_time;
850 CHECK_LE(length, message_->context.size);
851 message_->context.size = length;
852
853 // TODO(austin): Track sending too fast.
854 sent_queue_index_ = simulated_channel_->Send(message_);
855 monotonic_sent_time_ = event_loop_->monotonic_now();
856 realtime_sent_time_ = event_loop_->realtime_now();
857
858 // Drop the reference to the message so that we allocate a new message for
859 // next time. Otherwise we will continue to reuse the same memory for all
860 // messages and corrupt it.
861 message_.reset();
862 return true;
863}
864
865bool SimulatedSender::DoSend(
866 const void *msg, size_t size,
867 aos::monotonic_clock::time_point monotonic_remote_time,
868 aos::realtime_clock::time_point realtime_remote_time,
869 uint32_t remote_queue_index) {
Austin Schuh102667e2020-12-11 20:13:28 -0800870 CHECK_LE(size, this->size())
871 << ": Attempting to send too big a message on "
872 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800873
874 // This is wasteful, but since flatbuffers fill from the back end of the
875 // queue, we need it to be full sized.
876 message_ = SimulatedMessage::Make(simulated_channel_);
877
878 // Now fill in the message. size is already populated above, and
879 // queue_index will be populated in simulated_channel_. Put this at the
880 // back of the data segment.
881 memcpy(message_->data(simulated_channel_->max_size()) +
882 simulated_channel_->max_size() - size,
883 msg, size);
884
885 return DoSend(size, monotonic_remote_time, realtime_remote_time,
886 remote_queue_index);
887}
888
Austin Schuh39788ff2019-12-01 18:22:57 -0800889SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800890 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
891 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800892 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800893 simulated_event_loop_(simulated_event_loop),
894 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800895 scheduler_(scheduler),
896 token_(scheduler_->InvalidToken()) {}
897
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800898void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
899 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800900 // The allocations in here are due to infrastructure and don't count in the no
901 // mallocs in RT code.
902 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800903 Disable();
904 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800905 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800906 base_ = base;
907 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700908 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
909 DCHECK(token_ != scheduler_->InvalidToken());
910 token_ = scheduler_->InvalidToken();
911 simulated_event_loop_->HandleEvent();
912 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800913 event_.set_event_time(base_);
914 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800915}
916
917void SimulatedTimerHandler::HandleEvent() {
918 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800919 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800920 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700921 if (simulated_event_loop_->log_impl_) {
922 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800923 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700924 if (token_ != scheduler_->InvalidToken()) {
925 scheduler_->Deschedule(token_);
926 token_ = scheduler_->InvalidToken();
927 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800928 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
929 // Reschedule.
930 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700931 token_ = scheduler_->Schedule(base_, [this]() {
932 DCHECK(token_ != scheduler_->InvalidToken());
933 token_ = scheduler_->InvalidToken();
934 simulated_event_loop_->HandleEvent();
935 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800936 event_.set_event_time(base_);
937 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800938 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800939
Austin Schuhcc6070c2020-10-10 20:25:56 -0700940 {
941 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
942 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
943 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800944}
945
Austin Schuh7d87b672019-12-01 20:23:49 -0800946void SimulatedTimerHandler::Disable() {
947 simulated_event_loop_->RemoveEvent(&event_);
948 if (token_ != scheduler_->InvalidToken()) {
949 scheduler_->Deschedule(token_);
950 token_ = scheduler_->InvalidToken();
951 }
952}
953
Austin Schuh39788ff2019-12-01 18:22:57 -0800954SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800955 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
956 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800957 const monotonic_clock::duration offset)
958 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
959 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800960 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800961 scheduler_(scheduler),
962 token_(scheduler_->InvalidToken()) {}
963
Austin Schuh7d87b672019-12-01 20:23:49 -0800964SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
965 if (token_ != scheduler_->InvalidToken()) {
966 scheduler_->Deschedule(token_);
967 token_ = scheduler_->InvalidToken();
968 }
969 simulated_event_loop_->RemoveEvent(&event_);
970}
971
972void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800973 monotonic_clock::time_point monotonic_now =
974 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800975 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700976 if (simulated_event_loop_->log_impl_) {
977 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800978 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700979
980 {
981 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
982 Call([monotonic_now]() { return monotonic_now; },
983 [this](monotonic_clock::time_point sleep_time) {
984 Schedule(sleep_time);
985 });
986 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800987}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800988
Austin Schuh7d87b672019-12-01 20:23:49 -0800989void SimulatedPhasedLoopHandler::Schedule(
990 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800991 // The allocations in here are due to infrastructure and don't count in the no
992 // mallocs in RT code.
993 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700994 if (token_ != scheduler_->InvalidToken()) {
995 scheduler_->Deschedule(token_);
996 token_ = scheduler_->InvalidToken();
997 }
998 token_ = scheduler_->Schedule(sleep_time, [this]() {
999 DCHECK(token_ != scheduler_->InvalidToken());
1000 token_ = scheduler_->InvalidToken();
1001 simulated_event_loop_->HandleEvent();
1002 });
Austin Schuh7d87b672019-12-01 20:23:49 -08001003 event_.set_event_time(sleep_time);
1004 simulated_event_loop_->AddEvent(&event_);
1005}
1006
Austin Schuhac0771c2020-01-07 18:36:30 -08001007NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -08001008 EventSchedulerScheduler *scheduler_scheduler,
1009 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -08001010 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
1011 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -08001012 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
1013 scheduler_scheduler->AddEventScheduler(&scheduler_);
1014}
Austin Schuhac0771c2020-01-07 18:36:30 -08001015
Alex Perrycb7da4b2019-08-28 19:35:56 -07001016SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1017 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001018 : configuration_(CHECK_NOTNULL(configuration)),
1019 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001020 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001021 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001022 node_factories_.emplace_back(new NodeEventLoopFactory(
1023 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001024 }
Austin Schuh898f4972020-01-11 17:21:25 -08001025
1026 if (configuration::MultiNode(configuration)) {
1027 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1028 }
Austin Schuh15649d62019-12-28 16:36:38 -08001029}
1030
Alex Perrycb7da4b2019-08-28 19:35:56 -07001031SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1032
Austin Schuhac0771c2020-01-07 18:36:30 -08001033NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1034 const Node *node) {
1035 auto result = std::find_if(
1036 node_factories_.begin(), node_factories_.end(),
1037 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1038 return node_factory->node() == node;
1039 });
1040
1041 CHECK(result != node_factories_.end())
1042 << ": Failed to find node " << FlatbufferToJson(node);
1043
1044 return result->get();
1045}
1046
Austin Schuh87dd3832021-01-01 23:07:31 -08001047void SimulatedEventLoopFactory::SetTimeConverter(
1048 TimeConverter *time_converter) {
1049 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1050 factory->SetTimeConverter(time_converter);
1051 }
1052}
1053
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001054::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001055 std::string_view name, const Node *node) {
1056 if (node == nullptr) {
1057 CHECK(!configuration::MultiNode(configuration()))
1058 << ": Can't make a single node event loop in a multi-node world.";
1059 } else {
1060 CHECK(configuration::MultiNode(configuration()))
1061 << ": Can't make a multi-node event loop in a single-node world.";
1062 }
1063 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1064}
1065
1066::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001067 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001068 CHECK(!scheduler_.is_running())
1069 << ": Can't create an event loop while running";
1070
Austin Schuh39788ff2019-12-01 18:22:57 -08001071 pid_t tid = tid_;
1072 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001073 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001074 &scheduler_, this, &channels_, factory_->configuration(),
1075 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001076 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001077 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001078 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001079}
1080
Austin Schuhc0b0f722020-12-12 18:36:06 -08001081void NodeEventLoopFactory::Disconnect(const Node *other) {
1082 factory_->bridge_->Disconnect(node_, other);
1083}
1084void NodeEventLoopFactory::Connect(const Node *other) {
1085 factory_->bridge_->Connect(node_, other);
1086}
1087
Alex Perrycb7da4b2019-08-28 19:35:56 -07001088void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1089 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1090 raw_event_loops_) {
1091 event_loop.second(true);
1092 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001093 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001094 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1095 raw_event_loops_) {
1096 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001097 }
1098}
1099
1100void SimulatedEventLoopFactory::Run() {
1101 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1102 raw_event_loops_) {
1103 event_loop.second(true);
1104 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001105 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001106 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1107 raw_event_loops_) {
1108 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001109 }
1110}
1111
Austin Schuh87dd3832021-01-01 23:07:31 -08001112void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001113
Austin Schuh6f3babe2020-01-26 20:34:50 -08001114void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001115 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001116 bridge_->DisableForwarding(channel);
1117}
1118
Austin Schuh4c3b9702020-08-30 11:34:55 -07001119void SimulatedEventLoopFactory::DisableStatistics() {
1120 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1121 bridge_->DisableStatistics();
1122}
1123
Austin Schuh2928ebe2021-02-07 22:10:27 -08001124void SimulatedEventLoopFactory::SkipTimingReport() {
1125 CHECK(bridge_) << ": Can't skip timing reports without a message bridge.";
1126 bridge_->SkipTimingReport();
1127}
1128
Alex Perrycb7da4b2019-08-28 19:35:56 -07001129} // namespace aos