blob: 313eb2ac6df82c55e5b11fd0685336298777f7d5 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/simulated_event_loop.h"
2
3#include <algorithm>
4#include <deque>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08005#include <string_view>
Brian Silverman661eb8d2020-08-12 19:41:01 -07006#include <vector>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
8#include "absl/container/btree_map.h"
Brian Silverman661eb8d2020-08-12 19:41:01 -07009#include "aos/events/aos_logging.h"
Austin Schuh898f4972020-01-11 17:21:25 -080010#include "aos/events/simulated_network_bridge.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include "aos/json_to_flatbuffer.h"
Austin Schuhcc6070c2020-10-10 20:25:56 -070012#include "aos/realtime.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/util/phased_loop.h"
14
15namespace aos {
16
Brian Silverman661eb8d2020-08-12 19:41:01 -070017class SimulatedEventLoop;
18class SimulatedFetcher;
19class SimulatedChannel;
20
21namespace {
22
Austin Schuhcc6070c2020-10-10 20:25:56 -070023class ScopedMarkRealtimeRestorer {
24 public:
25 ScopedMarkRealtimeRestorer(bool rt) : rt_(rt), prior_(MarkRealtime(rt)) {}
26 ~ScopedMarkRealtimeRestorer() { CHECK_EQ(rt_, MarkRealtime(prior_)); }
27
28 private:
29 const bool rt_;
30 const bool prior_;
31};
32
Alex Perrycb7da4b2019-08-28 19:35:56 -070033// Container for both a message, and the context for it for simulation. This
34// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070035struct SimulatedMessage final {
36 SimulatedMessage(const SimulatedMessage &) = delete;
37 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
38
39 // Creates a SimulatedMessage with size bytes of storage.
40 // This is a shared_ptr so we don't have to implement refcounting or copying.
41 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
42
Alex Perrycb7da4b2019-08-28 19:35:56 -070043 // Context for the data.
44 Context context;
45
Brian Silverman661eb8d2020-08-12 19:41:01 -070046 SimulatedChannel *const channel = nullptr;
Brian Silverman661eb8d2020-08-12 19:41:01 -070047
Alex Perrycb7da4b2019-08-28 19:35:56 -070048 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080049 char *data(size_t buffer_size) {
50 return RoundChannelData(&actual_data[0], buffer_size);
51 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070052
Brian Silvermana1652f32020-01-29 20:41:44 -080053 // Then the data, including padding on the end so we can align the buffer we
54 // actually return from data().
55 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070056
57 private:
58 SimulatedMessage(SimulatedChannel *channel_in);
59 ~SimulatedMessage();
60
61 static void DestroyAndFree(SimulatedMessage *p) {
62 p->~SimulatedMessage();
63 free(p);
64 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070065};
66
Brian Silverman661eb8d2020-08-12 19:41:01 -070067} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080068
Brian Silverman661eb8d2020-08-12 19:41:01 -070069// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
70// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080071class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080072 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080073 SimulatedWatcher(
74 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
75 const Channel *channel,
76 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080077
Austin Schuh7d87b672019-12-01 20:23:49 -080078 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080079
Austin Schuh8fb315a2020-11-19 22:33:58 -080080 bool has_run() const;
81
Austin Schuh39788ff2019-12-01 18:22:57 -080082 void Startup(EventLoop * /*event_loop*/) override {}
83
Austin Schuh7d87b672019-12-01 20:23:49 -080084 void Schedule(std::shared_ptr<SimulatedMessage> message);
85
86 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080087
88 void SetSimulatedChannel(SimulatedChannel *channel) {
89 simulated_channel_ = channel;
90 }
91
92 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080093 void DoSchedule(monotonic_clock::time_point event_time);
94
95 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
96
Brian Silverman4f4e0612020-08-12 19:54:41 -070097 SimulatedEventLoop *const simulated_event_loop_;
98 const Channel *const channel_;
99 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800100 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800101 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 SimulatedChannel *simulated_channel_ = nullptr;
103};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104
105class SimulatedChannel {
106 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800107 explicit SimulatedChannel(const Channel *channel,
Brian Silverman661eb8d2020-08-12 19:41:01 -0700108 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800109 : channel_(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700110 channel_storage_duration_(channel_storage_duration),
111 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
112 available_buffer_indices_.reserve(number_buffers());
113 for (int i = 0; i < number_buffers(); ++i) {
114 available_buffer_indices_.push_back(i);
115 }
116 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
Brian Silverman661eb8d2020-08-12 19:41:01 -0700118 ~SimulatedChannel() {
119 latest_message_.reset();
120 CHECK_EQ(static_cast<size_t>(number_buffers()),
121 available_buffer_indices_.size());
122 CHECK_EQ(0u, fetchers_.size());
123 CHECK_EQ(0u, watchers_.size());
124 CHECK_EQ(0, sender_count_);
125 }
126
127 // The number of messages we pretend to have in the queue.
128 int queue_size() const {
129 return channel()->frequency() *
130 std::chrono::duration_cast<std::chrono::duration<double>>(
131 channel_storage_duration_)
132 .count();
133 }
134
135 // The number of extra buffers (beyond the queue) we pretend to have.
136 int number_scratch_buffers() const {
137 // We need to start creating messages before we know how many
138 // senders+readers we'll have, so we need to just pick something which is
139 // always big enough.
140 return 50;
141 }
142
143 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
144
145 int GetBufferIndex() {
146 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
147 const int result = available_buffer_indices_.back();
148 available_buffer_indices_.pop_back();
149 return result;
150 }
151
152 void FreeBufferIndex(int i) {
153 DCHECK(std::find(available_buffer_indices_.begin(),
154 available_buffer_indices_.end(),
155 i) == available_buffer_indices_.end())
156 << ": Buffer is not in use: " << i;
157 available_buffer_indices_.push_back(i);
158 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159
160 // Makes a connected raw sender which calls Send below.
Austin Schuh8fb315a2020-11-19 22:33:58 -0800161 ::std::unique_ptr<RawSender> MakeRawSender(SimulatedEventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700162
163 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800164 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700165
166 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800167 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800168
Austin Schuh7d87b672019-12-01 20:23:49 -0800169 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
171 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700172
Austin Schuhad154822019-12-27 15:45:13 -0800173 // Sends the message to all the connected receivers and fetchers. Returns the
174 // sent queue index.
175 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176
177 // Unregisters a fetcher.
178 void UnregisterFetcher(SimulatedFetcher *fetcher);
179
180 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
181
Austin Schuh39788ff2019-12-01 18:22:57 -0800182 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800184 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800185 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700186 }
187
Austin Schuh39788ff2019-12-01 18:22:57 -0800188 const Channel *channel() const { return channel_; }
189
Austin Schuhe516ab02020-05-06 21:37:04 -0700190 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700191 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700192 if (sender_count_ >= channel()->num_senders()) {
193 LOG(FATAL) << "Failed to create sender on "
194 << configuration::CleanedChannelToString(channel())
195 << ", too many senders.";
196 }
197 ++sender_count_;
198 }
Brian Silverman77162972020-08-12 19:52:40 -0700199
Austin Schuhe516ab02020-05-06 21:37:04 -0700200 void CountSenderDestroyed() {
201 --sender_count_;
202 CHECK_GE(sender_count_, 0);
203 }
204
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205 private:
Brian Silverman77162972020-08-12 19:52:40 -0700206 void CheckBufferCount() {
207 int reader_count = 0;
208 if (channel()->read_method() == ReadMethod::PIN) {
209 reader_count = watchers_.size() + fetchers_.size();
210 }
211 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
212 }
213
214 void CheckReaderCount() {
215 if (channel()->read_method() != ReadMethod::PIN) {
216 return;
217 }
218 CheckBufferCount();
219 const int reader_count = watchers_.size() + fetchers_.size();
220 if (reader_count >= channel()->num_readers()) {
221 LOG(FATAL) << "Failed to create reader on "
222 << configuration::CleanedChannelToString(channel())
223 << ", too many readers.";
224 }
225 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700226
227 const Channel *const channel_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700228 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229
230 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800231 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232
233 // List of all fetchers.
234 ::std::vector<SimulatedFetcher *> fetchers_;
235 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700236
237 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700238
239 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700240
241 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242};
243
244namespace {
245
Brian Silverman661eb8d2020-08-12 19:41:01 -0700246std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
247 SimulatedChannel *channel) {
Austin Schuh62288252020-11-18 23:26:04 -0800248 // The allocations in here are due to infrastructure and don't count in the no
249 // mallocs in RT code.
250 ScopedNotRealtime nrt;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700251 const size_t size = channel->max_size();
252 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800253 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700254 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800256 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700257
Brian Silverman661eb8d2020-08-12 19:41:01 -0700258 return std::shared_ptr<SimulatedMessage>(message,
259 &SimulatedMessage::DestroyAndFree);
260}
261
262SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
263 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700264 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700265}
266
267SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700268 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700269}
270
271class SimulatedSender : public RawSender {
272 public:
Austin Schuh8fb315a2020-11-19 22:33:58 -0800273 SimulatedSender(SimulatedChannel *simulated_channel,
274 SimulatedEventLoop *event_loop);
275 ~SimulatedSender() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700276
277 void *data() override {
278 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700279 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800281 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700282 }
283
284 size_t size() override { return simulated_channel_->max_size(); }
285
Austin Schuhad154822019-12-27 15:45:13 -0800286 bool DoSend(size_t length,
287 aos::monotonic_clock::time_point monotonic_remote_time,
288 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800289 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290
Austin Schuhad154822019-12-27 15:45:13 -0800291 bool DoSend(const void *msg, size_t size,
292 aos::monotonic_clock::time_point monotonic_remote_time,
293 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuh8fb315a2020-11-19 22:33:58 -0800294 uint32_t remote_queue_index) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295
Brian Silverman4f4e0612020-08-12 19:54:41 -0700296 int buffer_index() override {
297 // First, ensure message_ is allocated.
298 data();
299 return message_->context.buffer_index;
300 }
301
Alex Perrycb7da4b2019-08-28 19:35:56 -0700302 private:
303 SimulatedChannel *simulated_channel_;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800304 SimulatedEventLoop *event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305
306 std::shared_ptr<SimulatedMessage> message_;
307};
308} // namespace
309
310class SimulatedFetcher : public RawFetcher {
311 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800312 explicit SimulatedFetcher(EventLoop *event_loop,
313 SimulatedChannel *simulated_channel)
314 : RawFetcher(event_loop, simulated_channel->channel()),
315 simulated_channel_(simulated_channel) {}
316 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700317
Austin Schuh39788ff2019-12-01 18:22:57 -0800318 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh62288252020-11-18 23:26:04 -0800319 // The allocations in here are due to infrastructure and don't count in the
320 // no mallocs in RT code.
321 ScopedNotRealtime nrt;
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 if (msgs_.size() == 0) {
323 return std::make_pair(false, monotonic_clock::min_time);
324 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325
James Kuszmaulbcd96fc2020-10-12 20:29:32 -0700326 CHECK(!fell_behind_) << ": Got behind on "
327 << configuration::StrippedChannelToString(
328 simulated_channel_->channel());
Brian Silverman661eb8d2020-08-12 19:41:01 -0700329
Alex Perrycb7da4b2019-08-28 19:35:56 -0700330 SetMsg(msgs_.front());
331 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800332 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700333 }
334
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh62288252020-11-18 23:26:04 -0800336 // The allocations in here are due to infrastructure and don't count in the
337 // no mallocs in RT code.
338 ScopedNotRealtime nrt;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800340 // TODO(austin): Can we just do this logic unconditionally? It is a lot
341 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800342 if (!msg_ && simulated_channel_->latest_message()) {
343 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800344 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800346 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347 }
348 }
349
350 // We've had a message enqueued, so we don't need to go looking for the
351 // latest message from before we started.
352 SetMsg(msgs_.back());
353 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700354 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800355 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700356 }
357
358 private:
359 friend class SimulatedChannel;
360
361 // Updates the state inside RawFetcher to point to the data in msg_.
362 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
363 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700365 if (channel()->read_method() != ReadMethod::PIN) {
366 context_.buffer_index = -1;
367 }
Austin Schuhad154822019-12-27 15:45:13 -0800368 if (context_.remote_queue_index == 0xffffffffu) {
369 context_.remote_queue_index = context_.queue_index;
370 }
371 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
372 context_.monotonic_remote_time = context_.monotonic_event_time;
373 }
374 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
375 context_.realtime_remote_time = context_.realtime_event_time;
376 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700377 }
378
379 // Internal method for Simulation to add a message to the buffer.
380 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
381 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700382 if (fell_behind_ ||
383 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
384 fell_behind_ = true;
385 // Might as well empty out all the intermediate messages now.
386 while (msgs_.size() > 1) {
387 msgs_.pop_front();
388 }
389 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 }
391
Austin Schuhac0771c2020-01-07 18:36:30 -0800392 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 std::shared_ptr<SimulatedMessage> msg_;
394
395 // Messages queued up but not in use.
396 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700397
398 // Whether we're currently "behind", which means a FetchNext call will fail.
399 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400};
401
402class SimulatedTimerHandler : public TimerHandler {
403 public:
404 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800405 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800406 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800407 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408
409 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800410 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800412 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413
Austin Schuh7d87b672019-12-01 20:23:49 -0800414 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800417 SimulatedEventLoop *simulated_event_loop_;
418 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419 EventScheduler *scheduler_;
420 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800421
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422 monotonic_clock::time_point base_;
423 monotonic_clock::duration repeat_offset_;
424};
425
426class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
427 public:
428 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800429 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700430 ::std::function<void(int)> fn,
431 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800432 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800433 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434
Austin Schuh7d87b672019-12-01 20:23:49 -0800435 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436
Austin Schuh7d87b672019-12-01 20:23:49 -0800437 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438
439 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800440 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800441 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
Austin Schuh39788ff2019-12-01 18:22:57 -0800443 EventScheduler *scheduler_;
444 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445};
446
447class SimulatedEventLoop : public EventLoop {
448 public:
449 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700450 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
452 *channels,
453 const Configuration *configuration,
454 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800455 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800456 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800457 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800459 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800462 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800463 tid_(tid) {
464 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
465 if (!has_setup_) {
466 Setup();
467 has_setup_ = true;
468 }
469 set_is_running(value);
Austin Schuh8fb315a2020-11-19 22:33:58 -0800470 has_run_ = true;
Austin Schuh39788ff2019-12-01 18:22:57 -0800471 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700472 }
473 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800474 // Trigger any remaining senders or fetchers to be cleared before destroying
475 // the event loop so the book keeping matches.
476 timing_report_sender_.reset();
477
478 // Force everything with a registered fd with epoll to be destroyed now.
479 timers_.clear();
480 phased_loops_.clear();
481 watchers_.clear();
482
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
484 ++it) {
485 if (it->first == this) {
486 raw_event_loops_->erase(it);
487 break;
488 }
489 }
490 }
491
Austin Schuh8fb315a2020-11-19 22:33:58 -0800492 bool has_run() const { return has_run_; }
493
Austin Schuh7d87b672019-12-01 20:23:49 -0800494 std::chrono::nanoseconds send_delay() const { return send_delay_; }
495 void set_send_delay(std::chrono::nanoseconds send_delay) {
496 send_delay_ = send_delay;
497 }
498
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800500 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501 }
502
503 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800504 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 }
506
507 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
508
509 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
510
511 void MakeRawWatcher(
512 const Channel *channel,
513 ::std::function<void(const Context &context, const void *message)>
514 watcher) override;
515
516 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800517 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800518 return NewTimer(::std::unique_ptr<TimerHandler>(
519 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520 }
521
522 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
523 const monotonic_clock::duration interval,
524 const monotonic_clock::duration offset =
525 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800526 return NewPhasedLoop(
527 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
528 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700529 }
530
531 void OnRun(::std::function<void()> on_run) override {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800532 CHECK(!is_running()) << ": Cannot register OnRun callback while running.";
Austin Schuhcc6070c2020-10-10 20:25:56 -0700533 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
534 ScopedMarkRealtimeRestorer rt(priority() > 0);
535 on_run();
536 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 }
538
Austin Schuh217a9782019-12-21 23:02:50 -0800539 const Node *node() const override { return node_; }
540
James Kuszmaul3ae42262019-11-08 12:33:41 -0800541 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 name_ = std::string(name);
543 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800544 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545
546 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
547
Austin Schuh39788ff2019-12-01 18:22:57 -0800548 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800550 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700551 }
552
Austin Schuh39788ff2019-12-01 18:22:57 -0800553 int priority() const override { return priority_; }
554
Brian Silverman6a54ff32020-04-28 16:41:39 -0700555 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
556 CHECK(!is_running()) << ": Cannot set affinity while running.";
557 }
558
Tyler Chatow67ddb032020-01-12 14:30:04 -0800559 void Setup() {
560 MaybeScheduleTimingReports();
561 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800562 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700563 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800564 }
565 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800566
Brian Silverman4f4e0612020-08-12 19:54:41 -0700567 int NumberBuffers(const Channel *channel) override;
568
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800570 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800571 friend class SimulatedPhasedLoopHandler;
572 friend class SimulatedWatcher;
573
574 void HandleEvent() {
575 while (true) {
576 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
577 break;
578 }
579
580 EventLoopEvent *event = PopEvent();
581 event->HandleEvent();
582 }
583 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800584
Austin Schuh39788ff2019-12-01 18:22:57 -0800585 pid_t GetTid() override { return tid_; }
586
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800588 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
590 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
591 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700592
593 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800594
595 int priority_ = 0;
596
597 bool has_setup_ = false;
598
Austin Schuh7d87b672019-12-01 20:23:49 -0800599 std::chrono::nanoseconds send_delay_;
600
Austin Schuh217a9782019-12-21 23:02:50 -0800601 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800602 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800603
604 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700605 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800606
607 bool has_run_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608};
609
Austin Schuh7d87b672019-12-01 20:23:49 -0800610void SimulatedEventLoopFactory::set_send_delay(
611 std::chrono::nanoseconds send_delay) {
612 send_delay_ = send_delay;
613 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
614 raw_event_loops_) {
615 reinterpret_cast<SimulatedEventLoop *>(loop.first)
616 ->set_send_delay(send_delay_);
617 }
618}
619
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620void SimulatedEventLoop::MakeRawWatcher(
621 const Channel *channel,
622 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800623 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800624
Austin Schuh8bd96322020-02-13 21:18:22 -0800625 std::unique_ptr<SimulatedWatcher> shm_watcher(
626 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800627
628 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
629 NewWatcher(std::move(shm_watcher));
Austin Schuh8fb315a2020-11-19 22:33:58 -0800630
631 // Order of operations gets kinda wonky if we let people make watchers after
632 // running once. If someone has a valid use case, we can reconsider.
633 CHECK(!has_run()) << ": Can't add a watcher after running.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634}
635
636std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
637 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800638 TakeSender(channel);
639
Alex Perrycb7da4b2019-08-28 19:35:56 -0700640 return GetSimulatedChannel(channel)->MakeRawSender(this);
641}
642
643std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
644 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800645 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800646
Austin Schuhca4828c2019-12-28 14:21:35 -0800647 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
648 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
649 << "\", \"type\": \"" << channel->type()->string_view()
650 << "\" } is not able to be fetched on this node. Check your "
651 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800652 }
653
Austin Schuh39788ff2019-12-01 18:22:57 -0800654 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655}
656
657SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
658 const Channel *channel) {
659 auto it = channels_->find(SimpleChannel(channel));
660 if (it == channels_->end()) {
Austin Schuh8fb315a2020-11-19 22:33:58 -0800661 it =
662 channels_
663 ->emplace(
664 SimpleChannel(channel),
665 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
666 channel, std::chrono::nanoseconds(
667 configuration()->channel_storage_duration()))))
668 .first;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700669 }
670 return it->second.get();
671}
672
Brian Silverman4f4e0612020-08-12 19:54:41 -0700673int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
674 return GetSimulatedChannel(channel)->number_buffers();
675}
676
Austin Schuh7d87b672019-12-01 20:23:49 -0800677SimulatedWatcher::SimulatedWatcher(
678 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800679 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800680 std::function<void(const Context &context, const void *message)> fn)
681 : WatcherState(simulated_event_loop, channel, std::move(fn)),
682 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700683 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800684 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700685 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800686 token_(scheduler_->InvalidToken()) {}
687
688SimulatedWatcher::~SimulatedWatcher() {
689 simulated_event_loop_->RemoveEvent(&event_);
690 if (token_ != scheduler_->InvalidToken()) {
691 scheduler_->Deschedule(token_);
692 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700693 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800694}
695
Austin Schuh8fb315a2020-11-19 22:33:58 -0800696bool SimulatedWatcher::has_run() const {
697 return simulated_event_loop_->has_run();
698}
699
Austin Schuh7d87b672019-12-01 20:23:49 -0800700void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800701 monotonic_clock::time_point event_time =
702 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800703
704 // Messages are queued in order. If we are the first, add ourselves.
705 // Otherwise, don't.
706 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800707 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800708 simulated_event_loop_->AddEvent(&event_);
709
710 DoSchedule(event_time);
711 }
712
713 msgs_.emplace_back(message);
714}
715
716void SimulatedWatcher::HandleEvent() {
717 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
718
719 const monotonic_clock::time_point monotonic_now =
720 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800721 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700722 if (simulated_event_loop_->log_impl_) {
723 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800724 }
Austin Schuhad154822019-12-27 15:45:13 -0800725 Context context = msgs_.front()->context;
726
Brian Silverman4f4e0612020-08-12 19:54:41 -0700727 if (channel_->read_method() != ReadMethod::PIN) {
728 context.buffer_index = -1;
729 }
Austin Schuhad154822019-12-27 15:45:13 -0800730 if (context.remote_queue_index == 0xffffffffu) {
731 context.remote_queue_index = context.queue_index;
732 }
733 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
734 context.monotonic_remote_time = context.monotonic_event_time;
735 }
736 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
737 context.realtime_remote_time = context.realtime_event_time;
738 }
739
Austin Schuhcc6070c2020-10-10 20:25:56 -0700740 {
741 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
742 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
743 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800744
745 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700746 if (token_ != scheduler_->InvalidToken()) {
747 scheduler_->Deschedule(token_);
748 token_ = scheduler_->InvalidToken();
749 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800750 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800751 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800752 simulated_event_loop_->AddEvent(&event_);
753
754 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800755 }
756}
757
758void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700759 CHECK(token_ == scheduler_->InvalidToken())
760 << ": May not schedule multiple times";
761 token_ = scheduler_->Schedule(
762 event_time + simulated_event_loop_->send_delay(), [this]() {
763 DCHECK(token_ != scheduler_->InvalidToken());
764 token_ = scheduler_->InvalidToken();
765 simulated_event_loop_->HandleEvent();
766 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800767}
768
769void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700770 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800771 watcher->SetSimulatedChannel(this);
772 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700773}
774
775::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
Austin Schuh8fb315a2020-11-19 22:33:58 -0800776 SimulatedEventLoop *event_loop) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700777 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
778}
779
Austin Schuh39788ff2019-12-01 18:22:57 -0800780::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
781 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700782 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800783 ::std::unique_ptr<SimulatedFetcher> fetcher(
784 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785 fetchers_.push_back(fetcher.get());
786 return ::std::move(fetcher);
787}
788
Austin Schuhad154822019-12-27 15:45:13 -0800789uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
790 const uint32_t queue_index = next_queue_index_.index();
791 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800792 message->context.data = message->data(channel()->max_size()) +
793 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700794 next_queue_index_ = next_queue_index_.Increment();
795
796 latest_message_ = message;
Austin Schuh8fb315a2020-11-19 22:33:58 -0800797 for (SimulatedWatcher *watcher : watchers_) {
798 if (watcher->has_run()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800799 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700800 }
801 }
802 for (auto &fetcher : fetchers_) {
803 fetcher->Enqueue(message);
804 }
Austin Schuhad154822019-12-27 15:45:13 -0800805
806 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700807}
808
809void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
810 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
811}
812
Austin Schuh8fb315a2020-11-19 22:33:58 -0800813SimulatedSender::SimulatedSender(SimulatedChannel *simulated_channel,
814 SimulatedEventLoop *event_loop)
815 : RawSender(event_loop, simulated_channel->channel()),
816 simulated_channel_(simulated_channel),
817 event_loop_(event_loop) {
818 simulated_channel_->CountSenderCreated();
819}
820
821SimulatedSender::~SimulatedSender() {
822 simulated_channel_->CountSenderDestroyed();
823}
824
825bool SimulatedSender::DoSend(
826 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
827 aos::realtime_clock::time_point realtime_remote_time,
828 uint32_t remote_queue_index) {
829 // The allocations in here are due to infrastructure and don't count in the
830 // no mallocs in RT code.
831 ScopedNotRealtime nrt;
832 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
833 message_->context.monotonic_event_time = event_loop_->monotonic_now();
834 message_->context.monotonic_remote_time = monotonic_remote_time;
835 message_->context.remote_queue_index = remote_queue_index;
836 message_->context.realtime_event_time = event_loop_->realtime_now();
837 message_->context.realtime_remote_time = realtime_remote_time;
838 CHECK_LE(length, message_->context.size);
839 message_->context.size = length;
840
841 // TODO(austin): Track sending too fast.
842 sent_queue_index_ = simulated_channel_->Send(message_);
843 monotonic_sent_time_ = event_loop_->monotonic_now();
844 realtime_sent_time_ = event_loop_->realtime_now();
845
846 // Drop the reference to the message so that we allocate a new message for
847 // next time. Otherwise we will continue to reuse the same memory for all
848 // messages and corrupt it.
849 message_.reset();
850 return true;
851}
852
853bool SimulatedSender::DoSend(
854 const void *msg, size_t size,
855 aos::monotonic_clock::time_point monotonic_remote_time,
856 aos::realtime_clock::time_point realtime_remote_time,
857 uint32_t remote_queue_index) {
858 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
859
860 // This is wasteful, but since flatbuffers fill from the back end of the
861 // queue, we need it to be full sized.
862 message_ = SimulatedMessage::Make(simulated_channel_);
863
864 // Now fill in the message. size is already populated above, and
865 // queue_index will be populated in simulated_channel_. Put this at the
866 // back of the data segment.
867 memcpy(message_->data(simulated_channel_->max_size()) +
868 simulated_channel_->max_size() - size,
869 msg, size);
870
871 return DoSend(size, monotonic_remote_time, realtime_remote_time,
872 remote_queue_index);
873}
874
Austin Schuh39788ff2019-12-01 18:22:57 -0800875SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800876 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
877 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800878 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800879 simulated_event_loop_(simulated_event_loop),
880 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800881 scheduler_(scheduler),
882 token_(scheduler_->InvalidToken()) {}
883
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800884void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
885 monotonic_clock::duration repeat_offset) {
Austin Schuh62288252020-11-18 23:26:04 -0800886 // The allocations in here are due to infrastructure and don't count in the no
887 // mallocs in RT code.
888 ScopedNotRealtime nrt;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800889 Disable();
890 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800891 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800892 base_ = base;
893 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700894 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
895 DCHECK(token_ != scheduler_->InvalidToken());
896 token_ = scheduler_->InvalidToken();
897 simulated_event_loop_->HandleEvent();
898 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800899 event_.set_event_time(base_);
900 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800901}
902
903void SimulatedTimerHandler::HandleEvent() {
904 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800905 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800906 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700907 if (simulated_event_loop_->log_impl_) {
908 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800909 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700910 if (token_ != scheduler_->InvalidToken()) {
911 scheduler_->Deschedule(token_);
912 token_ = scheduler_->InvalidToken();
913 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800914 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
915 // Reschedule.
916 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700917 token_ = scheduler_->Schedule(base_, [this]() {
918 DCHECK(token_ != scheduler_->InvalidToken());
919 token_ = scheduler_->InvalidToken();
920 simulated_event_loop_->HandleEvent();
921 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800922 event_.set_event_time(base_);
923 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800924 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800925
Austin Schuhcc6070c2020-10-10 20:25:56 -0700926 {
927 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
928 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
929 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800930}
931
Austin Schuh7d87b672019-12-01 20:23:49 -0800932void SimulatedTimerHandler::Disable() {
933 simulated_event_loop_->RemoveEvent(&event_);
934 if (token_ != scheduler_->InvalidToken()) {
935 scheduler_->Deschedule(token_);
936 token_ = scheduler_->InvalidToken();
937 }
938}
939
Austin Schuh39788ff2019-12-01 18:22:57 -0800940SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800941 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
942 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800943 const monotonic_clock::duration offset)
944 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
945 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800946 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800947 scheduler_(scheduler),
948 token_(scheduler_->InvalidToken()) {}
949
Austin Schuh7d87b672019-12-01 20:23:49 -0800950SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
951 if (token_ != scheduler_->InvalidToken()) {
952 scheduler_->Deschedule(token_);
953 token_ = scheduler_->InvalidToken();
954 }
955 simulated_event_loop_->RemoveEvent(&event_);
956}
957
958void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800959 monotonic_clock::time_point monotonic_now =
960 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800961 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700962 if (simulated_event_loop_->log_impl_) {
963 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800964 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700965
966 {
967 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
968 Call([monotonic_now]() { return monotonic_now; },
969 [this](monotonic_clock::time_point sleep_time) {
970 Schedule(sleep_time);
971 });
972 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800973}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800974
Austin Schuh7d87b672019-12-01 20:23:49 -0800975void SimulatedPhasedLoopHandler::Schedule(
976 monotonic_clock::time_point sleep_time) {
Austin Schuh62288252020-11-18 23:26:04 -0800977 // The allocations in here are due to infrastructure and don't count in the no
978 // mallocs in RT code.
979 ScopedNotRealtime nrt;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700980 if (token_ != scheduler_->InvalidToken()) {
981 scheduler_->Deschedule(token_);
982 token_ = scheduler_->InvalidToken();
983 }
984 token_ = scheduler_->Schedule(sleep_time, [this]() {
985 DCHECK(token_ != scheduler_->InvalidToken());
986 token_ = scheduler_->InvalidToken();
987 simulated_event_loop_->HandleEvent();
988 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800989 event_.set_event_time(sleep_time);
990 simulated_event_loop_->AddEvent(&event_);
991}
992
Austin Schuhac0771c2020-01-07 18:36:30 -0800993NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800994 EventSchedulerScheduler *scheduler_scheduler,
995 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800996 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
997 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800998 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
999 scheduler_scheduler->AddEventScheduler(&scheduler_);
1000}
Austin Schuhac0771c2020-01-07 18:36:30 -08001001
Alex Perrycb7da4b2019-08-28 19:35:56 -07001002SimulatedEventLoopFactory::SimulatedEventLoopFactory(
1003 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -08001004 : configuration_(CHECK_NOTNULL(configuration)),
1005 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuhac0771c2020-01-07 18:36:30 -08001006 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001007 node_factories_.emplace_back(new NodeEventLoopFactory(
1008 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -08001009 }
Austin Schuh898f4972020-01-11 17:21:25 -08001010
1011 if (configuration::MultiNode(configuration)) {
1012 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
1013 }
Austin Schuh15649d62019-12-28 16:36:38 -08001014}
1015
Alex Perrycb7da4b2019-08-28 19:35:56 -07001016SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
1017
Austin Schuhac0771c2020-01-07 18:36:30 -08001018NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
1019 const Node *node) {
1020 auto result = std::find_if(
1021 node_factories_.begin(), node_factories_.end(),
1022 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
1023 return node_factory->node() == node;
1024 });
1025
1026 CHECK(result != node_factories_.end())
1027 << ": Failed to find node " << FlatbufferToJson(node);
1028
1029 return result->get();
1030}
1031
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001032::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -08001033 std::string_view name, const Node *node) {
1034 if (node == nullptr) {
1035 CHECK(!configuration::MultiNode(configuration()))
1036 << ": Can't make a single node event loop in a multi-node world.";
1037 } else {
1038 CHECK(configuration::MultiNode(configuration()))
1039 << ": Can't make a multi-node event loop in a single-node world.";
1040 }
1041 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
1042}
1043
1044::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001045 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001046 CHECK(!scheduler_.is_running())
1047 << ": Can't create an event loop while running";
1048
Austin Schuh39788ff2019-12-01 18:22:57 -08001049 pid_t tid = tid_;
1050 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -08001051 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -08001052 &scheduler_, this, &channels_, factory_->configuration(),
1053 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001054 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001055 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001056 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001057}
1058
1059void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1060 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1061 raw_event_loops_) {
1062 event_loop.second(true);
1063 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001064 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001065 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1066 raw_event_loops_) {
1067 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001068 }
1069}
1070
1071void SimulatedEventLoopFactory::Run() {
1072 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1073 raw_event_loops_) {
1074 event_loop.second(true);
1075 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001076 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001077 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1078 raw_event_loops_) {
1079 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001080 }
1081}
1082
Austin Schuh8fb315a2020-11-19 22:33:58 -08001083void SimulatedEventLoopFactory::Exit() {
1084 scheduler_scheduler_.Exit();
1085}
1086
Austin Schuh6f3babe2020-01-26 20:34:50 -08001087void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001088 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001089 bridge_->DisableForwarding(channel);
1090}
1091
Austin Schuh4c3b9702020-08-30 11:34:55 -07001092void SimulatedEventLoopFactory::DisableStatistics() {
1093 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1094 bridge_->DisableStatistics();
1095}
1096
Alex Perrycb7da4b2019-08-28 19:35:56 -07001097} // namespace aos