blob: 61888e7e5dabffbe92f03cbb6955d7e4373350f7 [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) {
157 DCHECK(std::find(available_buffer_indices_.begin(),
158 available_buffer_indices_.end(),
159 i) == available_buffer_indices_.end())
160 << ": Buffer is not in use: " << i;
161 available_buffer_indices_.push_back(i);
162 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163
164 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800165 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166
167 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800168 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700169
170 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800171 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800172
Austin Schuh7d87b672019-12-01 20:23:49 -0800173 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800174 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
175 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176
Austin Schuhad154822019-12-27 15:45:13 -0800177 // Sends the message to all the connected receivers and fetchers. Returns the
178 // sent queue index.
179 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180
181 // Unregisters a fetcher.
182 void UnregisterFetcher(SimulatedFetcher *fetcher);
183
184 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
185
Austin Schuh39788ff2019-12-01 18:22:57 -0800186 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700187
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800188 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800189 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700190 }
191
Austin Schuh39788ff2019-12-01 18:22:57 -0800192 const Channel *channel() const { return channel_; }
193
Austin Schuhe516ab02020-05-06 21:37:04 -0700194 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700195 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700196 if (sender_count_ >= channel()->num_senders()) {
197 LOG(FATAL) << "Failed to create sender on "
198 << configuration::CleanedChannelToString(channel())
199 << ", too many senders.";
200 }
201 ++sender_count_;
202 }
Brian Silverman77162972020-08-12 19:52:40 -0700203
Austin Schuhe516ab02020-05-06 21:37:04 -0700204 void CountSenderDestroyed() {
205 --sender_count_;
206 CHECK_GE(sender_count_, 0);
207 }
208
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209 private:
Brian Silverman77162972020-08-12 19:52:40 -0700210 void CheckBufferCount() {
211 int reader_count = 0;
212 if (channel()->read_method() == ReadMethod::PIN) {
213 reader_count = watchers_.size() + fetchers_.size();
214 }
215 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
216 }
217
218 void CheckReaderCount() {
219 if (channel()->read_method() != ReadMethod::PIN) {
220 return;
221 }
222 CheckBufferCount();
223 const int reader_count = watchers_.size() + fetchers_.size();
224 if (reader_count >= channel()->num_readers()) {
225 LOG(FATAL) << "Failed to create reader on "
226 << configuration::CleanedChannelToString(channel())
227 << ", too many readers.";
228 }
229 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700230
231 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700232 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700233
234 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800235 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700236
237 // List of all fetchers.
238 ::std::vector<SimulatedFetcher *> fetchers_;
239 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240
241 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700242
243 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700244
245 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700246};
247
248namespace {
249
Brian Silverman661eb8d2020-08-12 19:41:01 -0700250std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
251 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800252 // The allocations in here are due to infrastructure and don't count in the no
253 // mallocs in RT code.
254 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700255 const size_t size = channel->max_size();
256 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800257 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700258 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700259 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800260 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700261
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262 return std::shared_ptr<SimulatedMessage>(message,
263 &SimulatedMessage::DestroyAndFree);
264}
265
266SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
267 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700268 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700269}
270
271SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700272 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273}
274
275class SimulatedSender : public RawSender {
276 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800277 SimulatedSender(SimulatedChannel *simulated_channel,
278 SimulatedEventLoop *event_loop);
279 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280
281 void *data() override {
282 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700283 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800285 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286 }
287
288 size_t size() override { return simulated_channel_->max_size(); }
289
Austin Schuhad154822019-12-27 15:45:13 -0800290 bool DoSend(size_t length,
291 aos::monotonic_clock::time_point monotonic_remote_time,
292 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800293 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700294
Austin Schuhad154822019-12-27 15:45:13 -0800295 bool DoSend(const void *msg, size_t size,
296 aos::monotonic_clock::time_point monotonic_remote_time,
297 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800298 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299
Brian Silverman4f4e0612020-08-12 19:54:41 -0700300 int buffer_index() override {
301 // First, ensure message_ is allocated.
302 data();
303 return message_->context.buffer_index;
304 }
305
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306 private:
307 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800308 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309
310 std::shared_ptr<SimulatedMessage> message_;
311};
312} // namespace
313
314class SimulatedFetcher : public RawFetcher {
315 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800316 explicit SimulatedFetcher(EventLoop *event_loop,
317 SimulatedChannel *simulated_channel)
318 : RawFetcher(event_loop, simulated_channel->channel()),
319 simulated_channel_(simulated_channel) {}
320 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700321
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800323 // The allocations in here are due to infrastructure and don't count in the
324 // no mallocs in RT code.
325 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800326 if (msgs_.size() == 0) {
327 return std::make_pair(false, monotonic_clock::min_time);
328 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700329
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700330 CHECK(!fell_behind_) << ": Got behind on "
331 << configuration::StrippedChannelToString(
332 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700333
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334 SetMsg(msgs_.front());
335 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800336 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337 }
338
Austin Schuh39788ff2019-12-01 18:22:57 -0800339 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800340 // The allocations in here are due to infrastructure and don't count in the
341 // no mallocs in RT code.
342 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800344 // TODO(austin): Can we just do this logic unconditionally? It is a lot
345 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800346 if (!msg_ && simulated_channel_->latest_message()) {
347 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800348 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800350 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351 }
352 }
353
354 // We've had a message enqueued, so we don't need to go looking for the
355 // latest message from before we started.
356 SetMsg(msgs_.back());
357 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700358 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800359 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360 }
361
362 private:
363 friend class SimulatedChannel;
364
365 // Updates the state inside RawFetcher to point to the data in msg_.
366 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
367 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700369 if (channel()->read_method() != ReadMethod::PIN) {
370 context_.buffer_index = -1;
371 }
Austin Schuhad154822019-12-27 15:45:13 -0800372 if (context_.remote_queue_index == 0xffffffffu) {
373 context_.remote_queue_index = context_.queue_index;
374 }
375 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
376 context_.monotonic_remote_time = context_.monotonic_event_time;
377 }
378 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
379 context_.realtime_remote_time = context_.realtime_event_time;
380 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381 }
382
383 // Internal method for Simulation to add a message to the buffer.
384 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
385 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700386 if (fell_behind_ ||
387 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
388 fell_behind_ = true;
389 // Might as well empty out all the intermediate messages now.
390 while (msgs_.size() > 1) {
391 msgs_.pop_front();
392 }
393 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 }
395
Austin Schuhac0771c2020-01-07 18:36:30 -0800396 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 std::shared_ptr<SimulatedMessage> msg_;
398
399 // Messages queued up but not in use.
400 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700401
402 // Whether we're currently "behind", which means a FetchNext call will fail.
403 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404};
405
406class SimulatedTimerHandler : public TimerHandler {
407 public:
408 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800409 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800411 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412
413 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800414 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800416 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417
Austin Schuh7d87b672019-12-01 20:23:49 -0800418 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800421 SimulatedEventLoop *simulated_event_loop_;
422 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423 EventScheduler *scheduler_;
424 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800425
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426 monotonic_clock::time_point base_;
427 monotonic_clock::duration repeat_offset_;
428};
429
430class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
431 public:
432 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800433 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 ::std::function<void(int)> fn,
435 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800436 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800437 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438
Austin Schuh7d87b672019-12-01 20:23:49 -0800439 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440
Austin Schuh7d87b672019-12-01 20:23:49 -0800441 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
443 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800444 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800445 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
Austin Schuh39788ff2019-12-01 18:22:57 -0800447 EventScheduler *scheduler_;
448 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449};
450
451class SimulatedEventLoop : public EventLoop {
452 public:
453 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700454 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
456 *channels,
457 const Configuration *configuration,
458 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800459 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800460 const Node *node, pid_t tid)
Austin Schuh20ac95d2020-12-05 17:24:19 -0800461 : EventLoop(CHECK_NOTNULL(configuration),
462 node_event_loop_factory->boot_uuid()),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800464 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800466 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800467 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800468 tid_(tid) {
469 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
470 if (!has_setup_) {
471 Setup();
472 has_setup_ = true;
473 }
474 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800475 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800476 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477 }
478 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800479 // Trigger any remaining senders or fetchers to be cleared before destroying
480 // the event loop so the book keeping matches.
481 timing_report_sender_.reset();
482
483 // Force everything with a registered fd with epoll to be destroyed now.
484 timers_.clear();
485 phased_loops_.clear();
486 watchers_.clear();
487
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
489 ++it) {
490 if (it->first == this) {
491 raw_event_loops_->erase(it);
492 break;
493 }
494 }
495 }
496
Austin Schuh8fb315a2020-11-19 22:33:58 -0800497 bool has_run() const { return has_run_; }
498
Austin Schuh7d87b672019-12-01 20:23:49 -0800499 std::chrono::nanoseconds send_delay() const { return send_delay_; }
500 void set_send_delay(std::chrono::nanoseconds send_delay) {
501 send_delay_ = send_delay;
502 }
503
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800505 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506 }
507
508 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800509 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510 }
511
512 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
513
514 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
515
516 void MakeRawWatcher(
517 const Channel *channel,
518 ::std::function<void(const Context &context, const void *message)>
519 watcher) override;
520
521 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800522 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800523 return NewTimer(::std::unique_ptr<TimerHandler>(
524 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 }
526
527 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
528 const monotonic_clock::duration interval,
529 const monotonic_clock::duration offset =
530 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800531 return NewPhasedLoop(
532 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
533 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534 }
535
536 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800537 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700538 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
539 ScopedMarkRealtimeRestorer rt(priority() > 0);
540 on_run();
541 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 }
543
Austin Schuh217a9782019-12-21 23:02:50 -0800544 const Node *node() const override { return node_; }
545
James Kuszmaul3ae42262019-11-08 12:33:41 -0800546 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547 name_ = std::string(name);
548 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800549 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550
551 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
552
Austin Schuh39788ff2019-12-01 18:22:57 -0800553 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800555 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556 }
557
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 int priority() const override { return priority_; }
559
Brian Silverman6a54ff32020-04-28 16:41:39 -0700560 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
561 CHECK(!is_running()) << ": Cannot set affinity while running.";
562 }
563
Tyler Chatow67ddb032020-01-12 14:30:04 -0800564 void Setup() {
565 MaybeScheduleTimingReports();
566 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800567 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700568 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800569 }
570 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800571
Brian Silverman4f4e0612020-08-12 19:54:41 -0700572 int NumberBuffers(const Channel *channel) override;
573
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800575 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800576 friend class SimulatedPhasedLoopHandler;
577 friend class SimulatedWatcher;
578
579 void HandleEvent() {
580 while (true) {
581 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
582 break;
583 }
584
585 EventLoopEvent *event = PopEvent();
586 event->HandleEvent();
587 }
588 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800589
Austin Schuh39788ff2019-12-01 18:22:57 -0800590 pid_t GetTid() override { return tid_; }
591
Alex Perrycb7da4b2019-08-28 19:35:56 -0700592 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800593 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
595 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
596 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700597
598 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800599
600 int priority_ = 0;
601
602 bool has_setup_ = false;
603
Austin Schuh7d87b672019-12-01 20:23:49 -0800604 std::chrono::nanoseconds send_delay_;
605
Austin Schuh217a9782019-12-21 23:02:50 -0800606 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800607 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800608
609 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700610 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800611
612 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700613};
614
Austin Schuh7d87b672019-12-01 20:23:49 -0800615void SimulatedEventLoopFactory::set_send_delay(
616 std::chrono::nanoseconds send_delay) {
617 send_delay_ = send_delay;
618 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
619 raw_event_loops_) {
620 reinterpret_cast<SimulatedEventLoop *>(loop.first)
621 ->set_send_delay(send_delay_);
622 }
623}
624
Alex Perrycb7da4b2019-08-28 19:35:56 -0700625void SimulatedEventLoop::MakeRawWatcher(
626 const Channel *channel,
627 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800628 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800629
Austin Schuh8bd96322020-02-13 21:18:22 -0800630 std::unique_ptr<SimulatedWatcher> shm_watcher(
631 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800632
633 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
634 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800635
636 // Order of operations gets kinda wonky if we let people make watchers after
637 // running once. If someone has a valid use case, we can reconsider.
638 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700639}
640
641std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
642 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800643 TakeSender(channel);
644
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645 return GetSimulatedChannel(channel)->MakeRawSender(this);
646}
647
648std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
649 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800650 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800651
Austin Schuhca4828c2019-12-28 14:21:35 -0800652 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
653 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
654 << "\", \"type\": \"" << channel->type()->string_view()
655 << "\" } is not able to be fetched on this node. Check your "
656 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800657 }
658
Austin Schuh39788ff2019-12-01 18:22:57 -0800659 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660}
661
662SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
663 const Channel *channel) {
664 auto it = channels_->find(SimpleChannel(channel));
665 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800666 it =
667 channels_
668 ->emplace(
669 SimpleChannel(channel),
670 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
671 channel, std::chrono::nanoseconds(
672 configuration()->channel_storage_duration()))))
673 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700674 }
675 return it->second.get();
676}
677
Brian Silverman4f4e0612020-08-12 19:54:41 -0700678int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
679 return GetSimulatedChannel(channel)->number_buffers();
680}
681
Austin Schuh7d87b672019-12-01 20:23:49 -0800682SimulatedWatcher::SimulatedWatcher(
683 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800684 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800685 std::function<void(const Context &context, const void *message)> fn)
686 : WatcherState(simulated_event_loop, channel, std::move(fn)),
687 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700688 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700690 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800691 token_(scheduler_->InvalidToken()) {}
692
693SimulatedWatcher::~SimulatedWatcher() {
694 simulated_event_loop_->RemoveEvent(&event_);
695 if (token_ != scheduler_->InvalidToken()) {
696 scheduler_->Deschedule(token_);
697 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700698 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800699}
700
Austin Schuh8fb315a2020-11-19 22:33:58 -0800701bool SimulatedWatcher::has_run() const {
702 return simulated_event_loop_->has_run();
703}
704
Austin Schuh7d87b672019-12-01 20:23:49 -0800705void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800706 monotonic_clock::time_point event_time =
707 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800708
709 // Messages are queued in order. If we are the first, add ourselves.
710 // Otherwise, don't.
711 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800712 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800713 simulated_event_loop_->AddEvent(&event_);
714
715 DoSchedule(event_time);
716 }
717
718 msgs_.emplace_back(message);
719}
720
721void SimulatedWatcher::HandleEvent() {
722 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
723
724 const monotonic_clock::time_point monotonic_now =
725 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800726 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700727 if (simulated_event_loop_->log_impl_) {
728 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800729 }
Austin Schuhad154822019-12-27 15:45:13 -0800730 Context context = msgs_.front()->context;
731
Brian Silverman4f4e0612020-08-12 19:54:41 -0700732 if (channel_->read_method() != ReadMethod::PIN) {
733 context.buffer_index = -1;
734 }
Austin Schuhad154822019-12-27 15:45:13 -0800735 if (context.remote_queue_index == 0xffffffffu) {
736 context.remote_queue_index = context.queue_index;
737 }
738 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
739 context.monotonic_remote_time = context.monotonic_event_time;
740 }
741 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
742 context.realtime_remote_time = context.realtime_event_time;
743 }
744
Austin Schuhcc6070c2020-10-10 20:25:56 -0700745 {
746 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
747 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
748 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800749
750 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700751 if (token_ != scheduler_->InvalidToken()) {
752 scheduler_->Deschedule(token_);
753 token_ = scheduler_->InvalidToken();
754 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800755 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800756 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800757 simulated_event_loop_->AddEvent(&event_);
758
759 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800760 }
761}
762
763void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700764 CHECK(token_ == scheduler_->InvalidToken())
765 << ": May not schedule multiple times";
766 token_ = scheduler_->Schedule(
767 event_time + simulated_event_loop_->send_delay(), [this]() {
768 DCHECK(token_ != scheduler_->InvalidToken());
769 token_ = scheduler_->InvalidToken();
770 simulated_event_loop_->HandleEvent();
771 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800772}
773
774void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700775 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800776 watcher->SetSimulatedChannel(this);
777 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700778}
779
780::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800781 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700782 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
783}
784
Austin Schuh39788ff2019-12-01 18:22:57 -0800785::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
786 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700787 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800788 ::std::unique_ptr<SimulatedFetcher> fetcher(
789 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700790 fetchers_.push_back(fetcher.get());
791 return ::std::move(fetcher);
792}
793
Austin Schuhad154822019-12-27 15:45:13 -0800794uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
795 const uint32_t queue_index = next_queue_index_.index();
796 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800797 message->context.data = message->data(channel()->max_size()) +
798 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700799 next_queue_index_ = next_queue_index_.Increment();
800
801 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800802 for (SimulatedWatcher *watcher : watchers_) {
803 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800804 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700805 }
806 }
807 for (auto &fetcher : fetchers_) {
808 fetcher->Enqueue(message);
809 }
Austin Schuhad154822019-12-27 15:45:13 -0800810
811 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700812}
813
814void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
815 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
816}
817
Austin Schuh8fb315a2020-11-19 22:33:58 -0800818SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
819 SimulatedEventLoop *event_loop)
820 : RawSender(event_loop, simulated_channel->channel()),
821 simulated_channel_(simulated_channel),
822 event_loop_(event_loop) {
823 simulated_channel_->CountSenderCreated();
824}
825
826SimulatedSender::~SimulatedSender() {
827 simulated_channel_->CountSenderDestroyed();
828}
829
830bool SimulatedSender::DoSend(
831 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
832 aos::realtime_clock::time_point realtime_remote_time,
833 uint32_t remote_queue_index) {
834 // The allocations in here are due to infrastructure and don't count in the
835 // no mallocs in RT code.
836 ScopedNotRealtime nrt;
837 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
838 message_->context.monotonic_event_time = event_loop_->monotonic_now();
839 message_->context.monotonic_remote_time = monotonic_remote_time;
840 message_->context.remote_queue_index = remote_queue_index;
841 message_->context.realtime_event_time = event_loop_->realtime_now();
842 message_->context.realtime_remote_time = realtime_remote_time;
843 CHECK_LE(length, message_->context.size);
844 message_->context.size = length;
845
846 // TODO(austin): Track sending too fast.
847 sent_queue_index_ = simulated_channel_->Send(message_);
848 monotonic_sent_time_ = event_loop_->monotonic_now();
849 realtime_sent_time_ = event_loop_->realtime_now();
850
851 // Drop the reference to the message so that we allocate a new message for
852 // next time. Otherwise we will continue to reuse the same memory for all
853 // messages and corrupt it.
854 message_.reset();
855 return true;
856}
857
858bool SimulatedSender::DoSend(
859 const void *msg, size_t size,
860 aos::monotonic_clock::time_point monotonic_remote_time,
861 aos::realtime_clock::time_point realtime_remote_time,
862 uint32_t remote_queue_index) {
Austin Schuh102667e2020-12-11 20:13:28 -0800863 CHECK_LE(size, this->size())
864 << ": Attempting to send too big a message on "
865 << configuration::CleanedChannelToString(simulated_channel_->channel());
Austin Schuh8fb315a2020-11-19 22:33:58 -0800866
867 // This is wasteful, but since flatbuffers fill from the back end of the
868 // queue, we need it to be full sized.
869 message_ = SimulatedMessage::Make(simulated_channel_);
870
871 // Now fill in the message. size is already populated above, and
872 // queue_index will be populated in simulated_channel_. Put this at the
873 // back of the data segment.
874 memcpy(message_->data(simulated_channel_->max_size()) +
875 simulated_channel_->max_size() - size,
876 msg, size);
877
878 return DoSend(size, monotonic_remote_time, realtime_remote_time,
879 remote_queue_index);
880}
881
Austin Schuh39788ff2019-12-01 18:22:57 -0800882SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800883 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
884 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800885 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800886 simulated_event_loop_(simulated_event_loop),
887 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800888 scheduler_(scheduler),
889 token_(scheduler_->InvalidToken()) {}
890
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800891void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
892 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800893 // The allocations in here are due to infrastructure and don't count in the no
894 // mallocs in RT code.
895 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800896 Disable();
897 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800898 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800899 base_ = base;
900 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700901 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
902 DCHECK(token_ != scheduler_->InvalidToken());
903 token_ = scheduler_->InvalidToken();
904 simulated_event_loop_->HandleEvent();
905 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800906 event_.set_event_time(base_);
907 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800908}
909
910void SimulatedTimerHandler::HandleEvent() {
911 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800912 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800913 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700914 if (simulated_event_loop_->log_impl_) {
915 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800916 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700917 if (token_ != scheduler_->InvalidToken()) {
918 scheduler_->Deschedule(token_);
919 token_ = scheduler_->InvalidToken();
920 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800921 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
922 // Reschedule.
923 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700924 token_ = scheduler_->Schedule(base_, [this]() {
925 DCHECK(token_ != scheduler_->InvalidToken());
926 token_ = scheduler_->InvalidToken();
927 simulated_event_loop_->HandleEvent();
928 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800929 event_.set_event_time(base_);
930 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800931 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800932
Austin Schuhcc6070c2020-10-10 20:25:56 -0700933 {
934 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
935 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
936 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800937}
938
Austin Schuh7d87b672019-12-01 20:23:49 -0800939void SimulatedTimerHandler::Disable() {
940 simulated_event_loop_->RemoveEvent(&event_);
941 if (token_ != scheduler_->InvalidToken()) {
942 scheduler_->Deschedule(token_);
943 token_ = scheduler_->InvalidToken();
944 }
945}
946
Austin Schuh39788ff2019-12-01 18:22:57 -0800947SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800948 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
949 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800950 const monotonic_clock::duration offset)
951 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
952 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800953 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800954 scheduler_(scheduler),
955 token_(scheduler_->InvalidToken()) {}
956
Austin Schuh7d87b672019-12-01 20:23:49 -0800957SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
958 if (token_ != scheduler_->InvalidToken()) {
959 scheduler_->Deschedule(token_);
960 token_ = scheduler_->InvalidToken();
961 }
962 simulated_event_loop_->RemoveEvent(&event_);
963}
964
965void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800966 monotonic_clock::time_point monotonic_now =
967 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800968 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700969 if (simulated_event_loop_->log_impl_) {
970 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800971 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700972
973 {
974 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
975 Call([monotonic_now]() { return monotonic_now; },
976 [this](monotonic_clock::time_point sleep_time) {
977 Schedule(sleep_time);
978 });
979 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800980}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800981
Austin Schuh7d87b672019-12-01 20:23:49 -0800982void SimulatedPhasedLoopHandler::Schedule(
983 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800984 // The allocations in here are due to infrastructure and don't count in the no
985 // mallocs in RT code.
986 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700987 if (token_ != scheduler_->InvalidToken()) {
988 scheduler_->Deschedule(token_);
989 token_ = scheduler_->InvalidToken();
990 }
991 token_ = scheduler_->Schedule(sleep_time, [this]() {
992 DCHECK(token_ != scheduler_->InvalidToken());
993 token_ = scheduler_->InvalidToken();
994 simulated_event_loop_->HandleEvent();
995 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800996 event_.set_event_time(sleep_time);
997 simulated_event_loop_->AddEvent(&event_);
998}
999
Austin Schuhac0771c2020-01-07 18:36:30 -08001000NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -08001001 EventSchedulerScheduler *scheduler_scheduler,
1002 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -08001003 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
1004 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -08001005 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
1006 scheduler_scheduler->AddEventScheduler(&scheduler_);
1007}
Austin Schuhac0771c2020-01-07 18:36:30 -08001008
Alex Perrycb7da4b2019-08-28 19:35:56 -07001009SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1010 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001011 : configuration_(CHECK_NOTNULL(configuration)),
1012 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001013 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001014 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001015 node_factories_.emplace_back(new NodeEventLoopFactory(
1016 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001017 }
Austin Schuh898f4972020-01-11 17:21:25 -08001018
1019 if (configuration::MultiNode(configuration)) {
1020 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1021 }
Austin Schuh15649d62019-12-28 16:36:38 -08001022}
1023
Alex Perrycb7da4b2019-08-28 19:35:56 -07001024SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1025
Austin Schuhac0771c2020-01-07 18:36:30 -08001026NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1027 const Node *node) {
1028 auto result = std::find_if(
1029 node_factories_.begin(), node_factories_.end(),
1030 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1031 return node_factory->node() == node;
1032 });
1033
1034 CHECK(result != node_factories_.end())
1035 << ": Failed to find node " << FlatbufferToJson(node);
1036
1037 return result->get();
1038}
1039
Austin Schuh87dd3832021-01-01 23:07:31 -08001040void SimulatedEventLoopFactory::SetTimeConverter(
1041 TimeConverter *time_converter) {
1042 for (std::unique_ptr<NodeEventLoopFactory> &factory : node_factories_) {
1043 factory->SetTimeConverter(time_converter);
1044 }
1045}
1046
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001047::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001048 std::string_view name, const Node *node) {
1049 if (node == nullptr) {
1050 CHECK(!configuration::MultiNode(configuration()))
1051 << ": Can't make a single node event loop in a multi-node world.";
1052 } else {
1053 CHECK(configuration::MultiNode(configuration()))
1054 << ": Can't make a multi-node event loop in a single-node world.";
1055 }
1056 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1057}
1058
1059::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001060 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001061 CHECK(!scheduler_.is_running())
1062 << ": Can't create an event loop while running";
1063
Austin Schuh39788ff2019-12-01 18:22:57 -08001064 pid_t tid = tid_;
1065 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001066 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001067 &scheduler_, this, &channels_, factory_->configuration(),
1068 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001069 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001070 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001071 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001072}
1073
Austin Schuhc0b0f722020-12-12 18:36:06 -08001074void NodeEventLoopFactory::Disconnect(const Node *other) {
1075 factory_->bridge_->Disconnect(node_, other);
1076}
1077void NodeEventLoopFactory::Connect(const Node *other) {
1078 factory_->bridge_->Connect(node_, other);
1079}
1080
Alex Perrycb7da4b2019-08-28 19:35:56 -07001081void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1082 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1083 raw_event_loops_) {
1084 event_loop.second(true);
1085 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001086 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001087 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1088 raw_event_loops_) {
1089 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001090 }
1091}
1092
1093void SimulatedEventLoopFactory::Run() {
1094 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1095 raw_event_loops_) {
1096 event_loop.second(true);
1097 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001098 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001099 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1100 raw_event_loops_) {
1101 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001102 }
1103}
1104
Austin Schuh87dd3832021-01-01 23:07:31 -08001105void SimulatedEventLoopFactory::Exit() { scheduler_scheduler_.Exit(); }
Austin Schuh8fb315a2020-11-19 22:33:58 -08001106
Austin Schuh6f3babe2020-01-26 20:34:50 -08001107void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001108 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001109 bridge_->DisableForwarding(channel);
1110}
1111
Austin Schuh4c3b9702020-08-30 11:34:55 -07001112void SimulatedEventLoopFactory::DisableStatistics() {
1113 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1114 bridge_->DisableStatistics();
1115}
1116
Alex Perrycb7da4b2019-08-28 19:35:56 -07001117} // namespace aos