blob: 4c28039ba2cc4ceb1a6577a1098cdaaef2f2853c [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());
123 CHECK_EQ(0u, fetchers_.size());
124 CHECK_EQ(0u, watchers_.size());
125 CHECK_EQ(0, sender_count_);
126 }
127
128 // The number of messages we pretend to have in the queue.
129 int queue_size() const {
130 return channel()->frequency() *
131 std::chrono::duration_cast<std::chrono::duration<double>>(
132 channel_storage_duration_)
133 .count();
134 }
135
136 // The number of extra buffers (beyond the queue) we pretend to have.
137 int number_scratch_buffers() const {
138 // We need to start creating messages before we know how many
139 // senders+readers we'll have, so we need to just pick something which is
140 // always big enough.
141 return 50;
142 }
143
144 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
145
146 int GetBufferIndex() {
147 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
148 const int result = available_buffer_indices_.back();
149 available_buffer_indices_.pop_back();
150 return result;
151 }
152
153 void FreeBufferIndex(int i) {
154 DCHECK(std::find(available_buffer_indices_.begin(),
155 available_buffer_indices_.end(),
156 i) == available_buffer_indices_.end())
157 << ": Buffer is not in use: " << i;
158 available_buffer_indices_.push_back(i);
159 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160
161 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800162 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163
164 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800165 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166
167 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800168 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800169
Austin Schuh7d87b672019-12-01 20:23:49 -0800170 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800171 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
172 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173
Austin Schuhad154822019-12-27 15:45:13 -0800174 // Sends the message to all the connected receivers and fetchers. Returns the
175 // sent queue index.
176 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700177
178 // Unregisters a fetcher.
179 void UnregisterFetcher(SimulatedFetcher *fetcher);
180
181 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
182
Austin Schuh39788ff2019-12-01 18:22:57 -0800183 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800185 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800186 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700187 }
188
Austin Schuh39788ff2019-12-01 18:22:57 -0800189 const Channel *channel() const { return channel_; }
190
Austin Schuhe516ab02020-05-06 21:37:04 -0700191 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700192 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700193 if (sender_count_ >= channel()->num_senders()) {
194 LOG(FATAL) << "Failed to create sender on "
195 << configuration::CleanedChannelToString(channel())
196 << ", too many senders.";
197 }
198 ++sender_count_;
199 }
Brian Silverman77162972020-08-12 19:52:40 -0700200
Austin Schuhe516ab02020-05-06 21:37:04 -0700201 void CountSenderDestroyed() {
202 --sender_count_;
203 CHECK_GE(sender_count_, 0);
204 }
205
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 private:
Brian Silverman77162972020-08-12 19:52:40 -0700207 void CheckBufferCount() {
208 int reader_count = 0;
209 if (channel()->read_method() == ReadMethod::PIN) {
210 reader_count = watchers_.size() + fetchers_.size();
211 }
212 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
213 }
214
215 void CheckReaderCount() {
216 if (channel()->read_method() != ReadMethod::PIN) {
217 return;
218 }
219 CheckBufferCount();
220 const int reader_count = watchers_.size() + fetchers_.size();
221 if (reader_count >= channel()->num_readers()) {
222 LOG(FATAL) << "Failed to create reader on "
223 << configuration::CleanedChannelToString(channel())
224 << ", too many readers.";
225 }
226 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700227
228 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700229 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230
231 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800232 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700233
234 // List of all fetchers.
235 ::std::vector<SimulatedFetcher *> fetchers_;
236 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237
238 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700239
240 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700241
242 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243};
244
245namespace {
246
Brian Silverman661eb8d2020-08-12 19:41:01 -0700247std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
248 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800249 // The allocations in here are due to infrastructure and don't count in the no
250 // mallocs in RT code.
251 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700252 const size_t size = channel->max_size();
253 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800254 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700255 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800257 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258
Brian Silverman661eb8d2020-08-12 19:41:01 -0700259 return std::shared_ptr<SimulatedMessage>(message,
260 &SimulatedMessage::DestroyAndFree);
261}
262
263SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
264 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700265 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700266}
267
268SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700269 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270}
271
272class SimulatedSender : public RawSender {
273 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800274 SimulatedSender(SimulatedChannel *simulated_channel,
275 SimulatedEventLoop *event_loop);
276 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277
278 void *data() override {
279 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700280 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800282 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283 }
284
285 size_t size() override { return simulated_channel_->max_size(); }
286
Austin Schuhad154822019-12-27 15:45:13 -0800287 bool DoSend(size_t length,
288 aos::monotonic_clock::time_point monotonic_remote_time,
289 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800290 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291
Austin Schuhad154822019-12-27 15:45:13 -0800292 bool DoSend(const void *msg, size_t size,
293 aos::monotonic_clock::time_point monotonic_remote_time,
294 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800295 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296
Brian Silverman4f4e0612020-08-12 19:54:41 -0700297 int buffer_index() override {
298 // First, ensure message_ is allocated.
299 data();
300 return message_->context.buffer_index;
301 }
302
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 private:
304 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800305 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306
307 std::shared_ptr<SimulatedMessage> message_;
308};
309} // namespace
310
311class SimulatedFetcher : public RawFetcher {
312 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800313 explicit SimulatedFetcher(EventLoop *event_loop,
314 SimulatedChannel *simulated_channel)
315 : RawFetcher(event_loop, simulated_channel->channel()),
316 simulated_channel_(simulated_channel) {}
317 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700318
Austin Schuh39788ff2019-12-01 18:22:57 -0800319 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800320 // The allocations in here are due to infrastructure and don't count in the
321 // no mallocs in RT code.
322 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800323 if (msgs_.size() == 0) {
324 return std::make_pair(false, monotonic_clock::min_time);
325 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700326
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700327 CHECK(!fell_behind_) << ": Got behind on "
328 << configuration::StrippedChannelToString(
329 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700330
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 SetMsg(msgs_.front());
332 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800333 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334 }
335
Austin Schuh39788ff2019-12-01 18:22:57 -0800336 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800337 // The allocations in here are due to infrastructure and don't count in the
338 // no mallocs in RT code.
339 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700340 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800341 // TODO(austin): Can we just do this logic unconditionally? It is a lot
342 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800343 if (!msg_ && simulated_channel_->latest_message()) {
344 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800345 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700346 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800347 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348 }
349 }
350
351 // We've had a message enqueued, so we don't need to go looking for the
352 // latest message from before we started.
353 SetMsg(msgs_.back());
354 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700355 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800356 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 }
358
359 private:
360 friend class SimulatedChannel;
361
362 // Updates the state inside RawFetcher to point to the data in msg_.
363 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
364 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700366 if (channel()->read_method() != ReadMethod::PIN) {
367 context_.buffer_index = -1;
368 }
Austin Schuhad154822019-12-27 15:45:13 -0800369 if (context_.remote_queue_index == 0xffffffffu) {
370 context_.remote_queue_index = context_.queue_index;
371 }
372 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
373 context_.monotonic_remote_time = context_.monotonic_event_time;
374 }
375 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
376 context_.realtime_remote_time = context_.realtime_event_time;
377 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378 }
379
380 // Internal method for Simulation to add a message to the buffer.
381 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
382 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700383 if (fell_behind_ ||
384 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
385 fell_behind_ = true;
386 // Might as well empty out all the intermediate messages now.
387 while (msgs_.size() > 1) {
388 msgs_.pop_front();
389 }
390 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 }
392
Austin Schuhac0771c2020-01-07 18:36:30 -0800393 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394 std::shared_ptr<SimulatedMessage> msg_;
395
396 // Messages queued up but not in use.
397 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700398
399 // Whether we're currently "behind", which means a FetchNext call will fail.
400 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401};
402
403class SimulatedTimerHandler : public TimerHandler {
404 public:
405 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800406 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800407 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800408 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409
410 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800411 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800413 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700414
Austin Schuh7d87b672019-12-01 20:23:49 -0800415 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800418 SimulatedEventLoop *simulated_event_loop_;
419 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 EventScheduler *scheduler_;
421 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800422
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423 monotonic_clock::time_point base_;
424 monotonic_clock::duration repeat_offset_;
425};
426
427class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
428 public:
429 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800430 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431 ::std::function<void(int)> fn,
432 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800433 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800434 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435
Austin Schuh7d87b672019-12-01 20:23:49 -0800436 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437
Austin Schuh7d87b672019-12-01 20:23:49 -0800438 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700439
440 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800441 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800442 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443
Austin Schuh39788ff2019-12-01 18:22:57 -0800444 EventScheduler *scheduler_;
445 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446};
447
448class SimulatedEventLoop : public EventLoop {
449 public:
450 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700451 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
453 *channels,
454 const Configuration *configuration,
455 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800456 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800457 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800458 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800460 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800462 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800463 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800464 tid_(tid) {
465 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
466 if (!has_setup_) {
467 Setup();
468 has_setup_ = true;
469 }
470 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800471 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800472 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700473 }
474 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800475 // Trigger any remaining senders or fetchers to be cleared before destroying
476 // the event loop so the book keeping matches.
477 timing_report_sender_.reset();
478
479 // Force everything with a registered fd with epoll to be destroyed now.
480 timers_.clear();
481 phased_loops_.clear();
482 watchers_.clear();
483
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
485 ++it) {
486 if (it->first == this) {
487 raw_event_loops_->erase(it);
488 break;
489 }
490 }
491 }
492
Austin Schuh8fb315a2020-11-19 22:33:58 -0800493 bool has_run() const { return has_run_; }
494
Austin Schuh7d87b672019-12-01 20:23:49 -0800495 std::chrono::nanoseconds send_delay() const { return send_delay_; }
496 void set_send_delay(std::chrono::nanoseconds send_delay) {
497 send_delay_ = send_delay;
498 }
499
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800501 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502 }
503
504 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800505 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506 }
507
508 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
509
510 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
511
512 void MakeRawWatcher(
513 const Channel *channel,
514 ::std::function<void(const Context &context, const void *message)>
515 watcher) override;
516
517 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800518 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800519 return NewTimer(::std::unique_ptr<TimerHandler>(
520 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700521 }
522
523 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
524 const monotonic_clock::duration interval,
525 const monotonic_clock::duration offset =
526 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800527 return NewPhasedLoop(
528 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
529 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530 }
531
532 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800533 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700534 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
535 ScopedMarkRealtimeRestorer rt(priority() > 0);
536 on_run();
537 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 }
539
Austin Schuh217a9782019-12-21 23:02:50 -0800540 const Node *node() const override { return node_; }
541
James Kuszmaul3ae42262019-11-08 12:33:41 -0800542 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543 name_ = std::string(name);
544 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800545 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546
547 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
548
Austin Schuh39788ff2019-12-01 18:22:57 -0800549 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800551 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 }
553
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 int priority() const override { return priority_; }
555
Brian Silverman6a54ff32020-04-28 16:41:39 -0700556 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
557 CHECK(!is_running()) << ": Cannot set affinity while running.";
558 }
559
Tyler Chatow67ddb032020-01-12 14:30:04 -0800560 void Setup() {
561 MaybeScheduleTimingReports();
562 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800563 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700564 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800565 }
566 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800567
Brian Silverman4f4e0612020-08-12 19:54:41 -0700568 int NumberBuffers(const Channel *channel) override;
569
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800571 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800572 friend class SimulatedPhasedLoopHandler;
573 friend class SimulatedWatcher;
574
575 void HandleEvent() {
576 while (true) {
577 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
578 break;
579 }
580
581 EventLoopEvent *event = PopEvent();
582 event->HandleEvent();
583 }
584 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800585
Austin Schuh39788ff2019-12-01 18:22:57 -0800586 pid_t GetTid() override { return tid_; }
587
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800589 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
591 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
592 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593
594 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800595
596 int priority_ = 0;
597
598 bool has_setup_ = false;
599
Austin Schuh7d87b672019-12-01 20:23:49 -0800600 std::chrono::nanoseconds send_delay_;
601
Austin Schuh217a9782019-12-21 23:02:50 -0800602 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800603 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800604
605 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700606 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800607
608 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700609};
610
Austin Schuh7d87b672019-12-01 20:23:49 -0800611void SimulatedEventLoopFactory::set_send_delay(
612 std::chrono::nanoseconds send_delay) {
613 send_delay_ = send_delay;
614 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
615 raw_event_loops_) {
616 reinterpret_cast<SimulatedEventLoop *>(loop.first)
617 ->set_send_delay(send_delay_);
618 }
619}
620
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621void SimulatedEventLoop::MakeRawWatcher(
622 const Channel *channel,
623 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800624 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800625
Austin Schuh8bd96322020-02-13 21:18:22 -0800626 std::unique_ptr<SimulatedWatcher> shm_watcher(
627 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800628
629 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
630 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800631
632 // Order of operations gets kinda wonky if we let people make watchers after
633 // running once. If someone has a valid use case, we can reconsider.
634 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635}
636
637std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
638 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800639 TakeSender(channel);
640
Alex Perrycb7da4b2019-08-28 19:35:56 -0700641 return GetSimulatedChannel(channel)->MakeRawSender(this);
642}
643
644std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
645 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800646 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800647
Austin Schuhca4828c2019-12-28 14:21:35 -0800648 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
649 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
650 << "\", \"type\": \"" << channel->type()->string_view()
651 << "\" } is not able to be fetched on this node. Check your "
652 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800653 }
654
Austin Schuh39788ff2019-12-01 18:22:57 -0800655 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656}
657
658SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
659 const Channel *channel) {
660 auto it = channels_->find(SimpleChannel(channel));
661 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800662 it =
663 channels_
664 ->emplace(
665 SimpleChannel(channel),
666 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
667 channel, std::chrono::nanoseconds(
668 configuration()->channel_storage_duration()))))
669 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700670 }
671 return it->second.get();
672}
673
Brian Silverman4f4e0612020-08-12 19:54:41 -0700674int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
675 return GetSimulatedChannel(channel)->number_buffers();
676}
677
Austin Schuh7d87b672019-12-01 20:23:49 -0800678SimulatedWatcher::SimulatedWatcher(
679 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800680 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800681 std::function<void(const Context &context, const void *message)> fn)
682 : WatcherState(simulated_event_loop, channel, std::move(fn)),
683 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700684 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800685 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700686 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800687 token_(scheduler_->InvalidToken()) {}
688
689SimulatedWatcher::~SimulatedWatcher() {
690 simulated_event_loop_->RemoveEvent(&event_);
691 if (token_ != scheduler_->InvalidToken()) {
692 scheduler_->Deschedule(token_);
693 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700694 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800695}
696
Austin Schuh8fb315a2020-11-19 22:33:58 -0800697bool SimulatedWatcher::has_run() const {
698 return simulated_event_loop_->has_run();
699}
700
Austin Schuh7d87b672019-12-01 20:23:49 -0800701void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800702 monotonic_clock::time_point event_time =
703 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800704
705 // Messages are queued in order. If we are the first, add ourselves.
706 // Otherwise, don't.
707 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800708 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800709 simulated_event_loop_->AddEvent(&event_);
710
711 DoSchedule(event_time);
712 }
713
714 msgs_.emplace_back(message);
715}
716
717void SimulatedWatcher::HandleEvent() {
718 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
719
720 const monotonic_clock::time_point monotonic_now =
721 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800722 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700723 if (simulated_event_loop_->log_impl_) {
724 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800725 }
Austin Schuhad154822019-12-27 15:45:13 -0800726 Context context = msgs_.front()->context;
727
Brian Silverman4f4e0612020-08-12 19:54:41 -0700728 if (channel_->read_method() != ReadMethod::PIN) {
729 context.buffer_index = -1;
730 }
Austin Schuhad154822019-12-27 15:45:13 -0800731 if (context.remote_queue_index == 0xffffffffu) {
732 context.remote_queue_index = context.queue_index;
733 }
734 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
735 context.monotonic_remote_time = context.monotonic_event_time;
736 }
737 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
738 context.realtime_remote_time = context.realtime_event_time;
739 }
740
Austin Schuhcc6070c2020-10-10 20:25:56 -0700741 {
742 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
743 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
744 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800745
746 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700747 if (token_ != scheduler_->InvalidToken()) {
748 scheduler_->Deschedule(token_);
749 token_ = scheduler_->InvalidToken();
750 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800751 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800752 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800753 simulated_event_loop_->AddEvent(&event_);
754
755 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800756 }
757}
758
759void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700760 CHECK(token_ == scheduler_->InvalidToken())
761 << ": May not schedule multiple times";
762 token_ = scheduler_->Schedule(
763 event_time + simulated_event_loop_->send_delay(), [this]() {
764 DCHECK(token_ != scheduler_->InvalidToken());
765 token_ = scheduler_->InvalidToken();
766 simulated_event_loop_->HandleEvent();
767 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800768}
769
770void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700771 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800772 watcher->SetSimulatedChannel(this);
773 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700774}
775
776::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800777 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700778 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
779}
780
Austin Schuh39788ff2019-12-01 18:22:57 -0800781::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
782 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700783 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800784 ::std::unique_ptr<SimulatedFetcher> fetcher(
785 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786 fetchers_.push_back(fetcher.get());
787 return ::std::move(fetcher);
788}
789
Austin Schuhad154822019-12-27 15:45:13 -0800790uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
791 const uint32_t queue_index = next_queue_index_.index();
792 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800793 message->context.data = message->data(channel()->max_size()) +
794 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700795 next_queue_index_ = next_queue_index_.Increment();
796
797 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800798 for (SimulatedWatcher *watcher : watchers_) {
799 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800800 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700801 }
802 }
803 for (auto &fetcher : fetchers_) {
804 fetcher->Enqueue(message);
805 }
Austin Schuhad154822019-12-27 15:45:13 -0800806
807 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808}
809
810void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
811 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
812}
813
Austin Schuh8fb315a2020-11-19 22:33:58 -0800814SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
815 SimulatedEventLoop *event_loop)
816 : RawSender(event_loop, simulated_channel->channel()),
817 simulated_channel_(simulated_channel),
818 event_loop_(event_loop) {
819 simulated_channel_->CountSenderCreated();
820}
821
822SimulatedSender::~SimulatedSender() {
823 simulated_channel_->CountSenderDestroyed();
824}
825
826bool SimulatedSender::DoSend(
827 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
828 aos::realtime_clock::time_point realtime_remote_time,
829 uint32_t remote_queue_index) {
830 // The allocations in here are due to infrastructure and don't count in the
831 // no mallocs in RT code.
832 ScopedNotRealtime nrt;
833 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
834 message_->context.monotonic_event_time = event_loop_->monotonic_now();
835 message_->context.monotonic_remote_time = monotonic_remote_time;
836 message_->context.remote_queue_index = remote_queue_index;
837 message_->context.realtime_event_time = event_loop_->realtime_now();
838 message_->context.realtime_remote_time = realtime_remote_time;
839 CHECK_LE(length, message_->context.size);
840 message_->context.size = length;
841
842 // TODO(austin): Track sending too fast.
843 sent_queue_index_ = simulated_channel_->Send(message_);
844 monotonic_sent_time_ = event_loop_->monotonic_now();
845 realtime_sent_time_ = event_loop_->realtime_now();
846
847 // Drop the reference to the message so that we allocate a new message for
848 // next time. Otherwise we will continue to reuse the same memory for all
849 // messages and corrupt it.
850 message_.reset();
851 return true;
852}
853
854bool SimulatedSender::DoSend(
855 const void *msg, size_t size,
856 aos::monotonic_clock::time_point monotonic_remote_time,
857 aos::realtime_clock::time_point realtime_remote_time,
858 uint32_t remote_queue_index) {
859 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
860
861 // This is wasteful, but since flatbuffers fill from the back end of the
862 // queue, we need it to be full sized.
863 message_ = SimulatedMessage::Make(simulated_channel_);
864
865 // Now fill in the message. size is already populated above, and
866 // queue_index will be populated in simulated_channel_. Put this at the
867 // back of the data segment.
868 memcpy(message_->data(simulated_channel_->max_size()) +
869 simulated_channel_->max_size() - size,
870 msg, size);
871
872 return DoSend(size, monotonic_remote_time, realtime_remote_time,
873 remote_queue_index);
874}
875
Austin Schuh39788ff2019-12-01 18:22:57 -0800876SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800877 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
878 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800879 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800880 simulated_event_loop_(simulated_event_loop),
881 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800882 scheduler_(scheduler),
883 token_(scheduler_->InvalidToken()) {}
884
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800885void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
886 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800887 // The allocations in here are due to infrastructure and don't count in the no
888 // mallocs in RT code.
889 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800890 Disable();
891 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800892 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800893 base_ = base;
894 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700895 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
896 DCHECK(token_ != scheduler_->InvalidToken());
897 token_ = scheduler_->InvalidToken();
898 simulated_event_loop_->HandleEvent();
899 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800900 event_.set_event_time(base_);
901 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800902}
903
904void SimulatedTimerHandler::HandleEvent() {
905 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800906 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800907 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700908 if (simulated_event_loop_->log_impl_) {
909 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800910 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700911 if (token_ != scheduler_->InvalidToken()) {
912 scheduler_->Deschedule(token_);
913 token_ = scheduler_->InvalidToken();
914 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800915 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
916 // Reschedule.
917 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700918 token_ = scheduler_->Schedule(base_, [this]() {
919 DCHECK(token_ != scheduler_->InvalidToken());
920 token_ = scheduler_->InvalidToken();
921 simulated_event_loop_->HandleEvent();
922 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800923 event_.set_event_time(base_);
924 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800925 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800926
Austin Schuhcc6070c2020-10-10 20:25:56 -0700927 {
928 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
929 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
930 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800931}
932
Austin Schuh7d87b672019-12-01 20:23:49 -0800933void SimulatedTimerHandler::Disable() {
934 simulated_event_loop_->RemoveEvent(&event_);
935 if (token_ != scheduler_->InvalidToken()) {
936 scheduler_->Deschedule(token_);
937 token_ = scheduler_->InvalidToken();
938 }
939}
940
Austin Schuh39788ff2019-12-01 18:22:57 -0800941SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800942 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
943 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800944 const monotonic_clock::duration offset)
945 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
946 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800947 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800948 scheduler_(scheduler),
949 token_(scheduler_->InvalidToken()) {}
950
Austin Schuh7d87b672019-12-01 20:23:49 -0800951SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
952 if (token_ != scheduler_->InvalidToken()) {
953 scheduler_->Deschedule(token_);
954 token_ = scheduler_->InvalidToken();
955 }
956 simulated_event_loop_->RemoveEvent(&event_);
957}
958
959void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800960 monotonic_clock::time_point monotonic_now =
961 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800962 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700963 if (simulated_event_loop_->log_impl_) {
964 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800965 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700966
967 {
968 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
969 Call([monotonic_now]() { return monotonic_now; },
970 [this](monotonic_clock::time_point sleep_time) {
971 Schedule(sleep_time);
972 });
973 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800974}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800975
Austin Schuh7d87b672019-12-01 20:23:49 -0800976void SimulatedPhasedLoopHandler::Schedule(
977 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800978 // The allocations in here are due to infrastructure and don't count in the no
979 // mallocs in RT code.
980 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700981 if (token_ != scheduler_->InvalidToken()) {
982 scheduler_->Deschedule(token_);
983 token_ = scheduler_->InvalidToken();
984 }
985 token_ = scheduler_->Schedule(sleep_time, [this]() {
986 DCHECK(token_ != scheduler_->InvalidToken());
987 token_ = scheduler_->InvalidToken();
988 simulated_event_loop_->HandleEvent();
989 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800990 event_.set_event_time(sleep_time);
991 simulated_event_loop_->AddEvent(&event_);
992}
993
Austin Schuhac0771c2020-01-07 18:36:30 -0800994NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800995 EventSchedulerScheduler *scheduler_scheduler,
996 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800997 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
998 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800999 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
1000 scheduler_scheduler->AddEventScheduler(&scheduler_);
1001}
Austin Schuhac0771c2020-01-07 18:36:30 -08001002
Alex Perrycb7da4b2019-08-28 19:35:56 -07001003SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1004 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001005 : configuration_(CHECK_NOTNULL(configuration)),
1006 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuh094d09b2020-11-20 23:26:52 -08001007 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuhac0771c2020-01-07 18:36:30 -08001008 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001009 node_factories_.emplace_back(new NodeEventLoopFactory(
1010 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001011 }
Austin Schuh898f4972020-01-11 17:21:25 -08001012
1013 if (configuration::MultiNode(configuration)) {
1014 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1015 }
Austin Schuh15649d62019-12-28 16:36:38 -08001016}
1017
Alex Perrycb7da4b2019-08-28 19:35:56 -07001018SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1019
Austin Schuhac0771c2020-01-07 18:36:30 -08001020NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1021 const Node *node) {
1022 auto result = std::find_if(
1023 node_factories_.begin(), node_factories_.end(),
1024 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1025 return node_factory->node() == node;
1026 });
1027
1028 CHECK(result != node_factories_.end())
1029 << ": Failed to find node " << FlatbufferToJson(node);
1030
1031 return result->get();
1032}
1033
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001034::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001035 std::string_view name, const Node *node) {
1036 if (node == nullptr) {
1037 CHECK(!configuration::MultiNode(configuration()))
1038 << ": Can't make a single node event loop in a multi-node world.";
1039 } else {
1040 CHECK(configuration::MultiNode(configuration()))
1041 << ": Can't make a multi-node event loop in a single-node world.";
1042 }
1043 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1044}
1045
1046::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001047 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001048 CHECK(!scheduler_.is_running())
1049 << ": Can't create an event loop while running";
1050
Austin Schuh39788ff2019-12-01 18:22:57 -08001051 pid_t tid = tid_;
1052 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001053 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001054 &scheduler_, this, &channels_, factory_->configuration(),
1055 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001056 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001057 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001058 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001059}
1060
1061void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1062 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1063 raw_event_loops_) {
1064 event_loop.second(true);
1065 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001066 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001067 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1068 raw_event_loops_) {
1069 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001070 }
1071}
1072
1073void SimulatedEventLoopFactory::Run() {
1074 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1075 raw_event_loops_) {
1076 event_loop.second(true);
1077 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001078 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001079 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1080 raw_event_loops_) {
1081 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001082 }
1083}
1084
Austin Schuh8fb315a2020-11-19 22:33:58 -08001085void SimulatedEventLoopFactory::Exit() {
1086 scheduler_scheduler_.Exit();
1087}
1088
Austin Schuh6f3babe2020-01-26 20:34:50 -08001089void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001090 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001091 bridge_->DisableForwarding(channel);
1092}
1093
Austin Schuh4c3b9702020-08-30 11:34:55 -07001094void SimulatedEventLoopFactory::DisableStatistics() {
1095 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1096 bridge_->DisableStatistics();
1097}
1098
Alex Perrycb7da4b2019-08-28 19:35:56 -07001099} // namespace aos