blob: 3daabb20cd7798eca6dade311b0a2bc391b360d8 [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
80 void Startup(EventLoop * /*event_loop*/) override {}
81
Austin Schuh7d87b672019-12-01 20:23:49 -080082 void Schedule(std::shared_ptr<SimulatedMessage> message);
83
84 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080085
86 void SetSimulatedChannel(SimulatedChannel *channel) {
87 simulated_channel_ = channel;
88 }
89
90 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080091 void DoSchedule(monotonic_clock::time_point event_time);
92
93 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
94
Brian Silverman4f4e0612020-08-12 19:54:41 -070095 SimulatedEventLoop *const simulated_event_loop_;
96 const Channel *const channel_;
97 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -080098 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -080099 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 SimulatedChannel *simulated_channel_ = nullptr;
101};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102
103class SimulatedChannel {
104 public:
Brian Silverman661eb8d2020-08-12 19:41:01 -0700105 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler,
106 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800107 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108 scheduler_(scheduler),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700109 channel_storage_duration_(channel_storage_duration),
110 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
111 available_buffer_indices_.reserve(number_buffers());
112 for (int i = 0; i < number_buffers(); ++i) {
113 available_buffer_indices_.push_back(i);
114 }
115 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116
Brian Silverman661eb8d2020-08-12 19:41:01 -0700117 ~SimulatedChannel() {
118 latest_message_.reset();
119 CHECK_EQ(static_cast<size_t>(number_buffers()),
120 available_buffer_indices_.size());
121 CHECK_EQ(0u, fetchers_.size());
122 CHECK_EQ(0u, watchers_.size());
123 CHECK_EQ(0, sender_count_);
124 }
125
126 // The number of messages we pretend to have in the queue.
127 int queue_size() const {
128 return channel()->frequency() *
129 std::chrono::duration_cast<std::chrono::duration<double>>(
130 channel_storage_duration_)
131 .count();
132 }
133
134 // The number of extra buffers (beyond the queue) we pretend to have.
135 int number_scratch_buffers() const {
136 // We need to start creating messages before we know how many
137 // senders+readers we'll have, so we need to just pick something which is
138 // always big enough.
139 return 50;
140 }
141
142 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
143
144 int GetBufferIndex() {
145 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
146 const int result = available_buffer_indices_.back();
147 available_buffer_indices_.pop_back();
148 return result;
149 }
150
151 void FreeBufferIndex(int i) {
152 DCHECK(std::find(available_buffer_indices_.begin(),
153 available_buffer_indices_.end(),
154 i) == available_buffer_indices_.end())
155 << ": Buffer is not in use: " << i;
156 available_buffer_indices_.push_back(i);
157 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700158
159 // Makes a connected raw sender which calls Send below.
160 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
161
162 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800163 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164
165 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800166 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800167
Austin Schuh7d87b672019-12-01 20:23:49 -0800168 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800169 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
170 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
Austin Schuhad154822019-12-27 15:45:13 -0800172 // Sends the message to all the connected receivers and fetchers. Returns the
173 // sent queue index.
174 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
176 // Unregisters a fetcher.
177 void UnregisterFetcher(SimulatedFetcher *fetcher);
178
179 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
180
Austin Schuh39788ff2019-12-01 18:22:57 -0800181 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800183 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800184 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185 }
186
Austin Schuh39788ff2019-12-01 18:22:57 -0800187 const Channel *channel() const { return channel_; }
188
Austin Schuhe516ab02020-05-06 21:37:04 -0700189 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700190 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700191 if (sender_count_ >= channel()->num_senders()) {
192 LOG(FATAL) << "Failed to create sender on "
193 << configuration::CleanedChannelToString(channel())
194 << ", too many senders.";
195 }
196 ++sender_count_;
197 }
Brian Silverman77162972020-08-12 19:52:40 -0700198
Austin Schuhe516ab02020-05-06 21:37:04 -0700199 void CountSenderDestroyed() {
200 --sender_count_;
201 CHECK_GE(sender_count_, 0);
202 }
203
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204 private:
Brian Silverman77162972020-08-12 19:52:40 -0700205 void CheckBufferCount() {
206 int reader_count = 0;
207 if (channel()->read_method() == ReadMethod::PIN) {
208 reader_count = watchers_.size() + fetchers_.size();
209 }
210 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
211 }
212
213 void CheckReaderCount() {
214 if (channel()->read_method() != ReadMethod::PIN) {
215 return;
216 }
217 CheckBufferCount();
218 const int reader_count = watchers_.size() + fetchers_.size();
219 if (reader_count >= channel()->num_readers()) {
220 LOG(FATAL) << "Failed to create reader on "
221 << configuration::CleanedChannelToString(channel())
222 << ", too many readers.";
223 }
224 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700225
226 const Channel *const channel_;
227 EventScheduler *const scheduler_;
228 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) {
248 const size_t size = channel->max_size();
249 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800250 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700251 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800253 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254
Brian Silverman661eb8d2020-08-12 19:41:01 -0700255 return std::shared_ptr<SimulatedMessage>(message,
256 &SimulatedMessage::DestroyAndFree);
257}
258
259SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
260 : channel(channel_in) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700261 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700262}
263
264SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700265 channel->FreeBufferIndex(context.buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700266}
267
268class SimulatedSender : public RawSender {
269 public:
270 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800271 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800272 simulated_channel_(simulated_channel),
Austin Schuhe516ab02020-05-06 21:37:04 -0700273 event_loop_(event_loop) {
274 simulated_channel_->CountSenderCreated();
275 }
276 ~SimulatedSender() { simulated_channel_->CountSenderDestroyed(); }
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,
290 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800292 message_->context.monotonic_event_time = event_loop_->monotonic_now();
293 message_->context.monotonic_remote_time = monotonic_remote_time;
294 message_->context.remote_queue_index = remote_queue_index;
295 message_->context.realtime_event_time = event_loop_->realtime_now();
296 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297 CHECK_LE(length, message_->context.size);
298 message_->context.size = length;
299
300 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800301 sent_queue_index_ = simulated_channel_->Send(message_);
302 monotonic_sent_time_ = event_loop_->monotonic_now();
303 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304
305 // Drop the reference to the message so that we allocate a new message for
306 // next time. Otherwise we will continue to reuse the same memory for all
307 // messages and corrupt it.
308 message_.reset();
309 return true;
310 }
311
Austin Schuhad154822019-12-27 15:45:13 -0800312 bool DoSend(const void *msg, size_t size,
313 aos::monotonic_clock::time_point monotonic_remote_time,
314 aos::realtime_clock::time_point realtime_remote_time,
315 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
317
318 // This is wasteful, but since flatbuffers fill from the back end of the
319 // queue, we need it to be full sized.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700320 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700321
322 // Now fill in the message. size is already populated above, and
Austin Schuhac0771c2020-01-07 18:36:30 -0800323 // queue_index will be populated in simulated_channel_. Put this at the
324 // back of the data segment.
Brian Silvermana1652f32020-01-29 20:41:44 -0800325 memcpy(message_->data(simulated_channel_->max_size()) +
326 simulated_channel_->max_size() - size,
327 msg, size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328
Austin Schuhac0771c2020-01-07 18:36:30 -0800329 return DoSend(size, monotonic_remote_time, realtime_remote_time,
330 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 }
332
Brian Silverman4f4e0612020-08-12 19:54:41 -0700333 int buffer_index() override {
334 // First, ensure message_ is allocated.
335 data();
336 return message_->context.buffer_index;
337 }
338
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 private:
340 SimulatedChannel *simulated_channel_;
341 EventLoop *event_loop_;
342
343 std::shared_ptr<SimulatedMessage> message_;
344};
345} // namespace
346
347class SimulatedFetcher : public RawFetcher {
348 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800349 explicit SimulatedFetcher(EventLoop *event_loop,
350 SimulatedChannel *simulated_channel)
351 : RawFetcher(event_loop, simulated_channel->channel()),
352 simulated_channel_(simulated_channel) {}
353 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
Austin Schuh39788ff2019-12-01 18:22:57 -0800355 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
356 if (msgs_.size() == 0) {
357 return std::make_pair(false, monotonic_clock::min_time);
358 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359
Brian Silverman661eb8d2020-08-12 19:41:01 -0700360 CHECK(!fell_behind_) << ": Got behind";
361
Alex Perrycb7da4b2019-08-28 19:35:56 -0700362 SetMsg(msgs_.front());
363 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800364 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 }
366
Austin Schuh39788ff2019-12-01 18:22:57 -0800367 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800369 // TODO(austin): Can we just do this logic unconditionally? It is a lot
370 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800371 if (!msg_ && simulated_channel_->latest_message()) {
372 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800373 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800375 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 }
377 }
378
379 // We've had a message enqueued, so we don't need to go looking for the
380 // latest message from before we started.
381 SetMsg(msgs_.back());
382 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700383 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800384 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385 }
386
387 private:
388 friend class SimulatedChannel;
389
390 // Updates the state inside RawFetcher to point to the data in msg_.
391 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
392 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700394 if (channel()->read_method() != ReadMethod::PIN) {
395 context_.buffer_index = -1;
396 }
Austin Schuhad154822019-12-27 15:45:13 -0800397 if (context_.remote_queue_index == 0xffffffffu) {
398 context_.remote_queue_index = context_.queue_index;
399 }
400 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
401 context_.monotonic_remote_time = context_.monotonic_event_time;
402 }
403 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
404 context_.realtime_remote_time = context_.realtime_event_time;
405 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406 }
407
408 // Internal method for Simulation to add a message to the buffer.
409 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
410 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700411 if (fell_behind_ ||
412 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
413 fell_behind_ = true;
414 // Might as well empty out all the intermediate messages now.
415 while (msgs_.size() > 1) {
416 msgs_.pop_front();
417 }
418 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419 }
420
Austin Schuhac0771c2020-01-07 18:36:30 -0800421 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422 std::shared_ptr<SimulatedMessage> msg_;
423
424 // Messages queued up but not in use.
425 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700426
427 // Whether we're currently "behind", which means a FetchNext call will fail.
428 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429};
430
431class SimulatedTimerHandler : public TimerHandler {
432 public:
433 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800434 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800435 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800436 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437
438 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800439 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800441 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
Austin Schuh7d87b672019-12-01 20:23:49 -0800443 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800446 SimulatedEventLoop *simulated_event_loop_;
447 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 EventScheduler *scheduler_;
449 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800450
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 monotonic_clock::time_point base_;
452 monotonic_clock::duration repeat_offset_;
453};
454
455class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
456 public:
457 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800458 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 ::std::function<void(int)> fn,
460 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800462 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463
Austin Schuh7d87b672019-12-01 20:23:49 -0800464 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465
Austin Schuh7d87b672019-12-01 20:23:49 -0800466 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467
468 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800469 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800470 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471
Austin Schuh39788ff2019-12-01 18:22:57 -0800472 EventScheduler *scheduler_;
473 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474};
475
476class SimulatedEventLoop : public EventLoop {
477 public:
478 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700479 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
481 *channels,
482 const Configuration *configuration,
483 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800484 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800485 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800486 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700487 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800488 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800490 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800491 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800492 tid_(tid) {
493 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
494 if (!has_setup_) {
495 Setup();
496 has_setup_ = true;
497 }
498 set_is_running(value);
499 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500 }
501 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800502 // Trigger any remaining senders or fetchers to be cleared before destroying
503 // the event loop so the book keeping matches.
504 timing_report_sender_.reset();
505
506 // Force everything with a registered fd with epoll to be destroyed now.
507 timers_.clear();
508 phased_loops_.clear();
509 watchers_.clear();
510
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
512 ++it) {
513 if (it->first == this) {
514 raw_event_loops_->erase(it);
515 break;
516 }
517 }
518 }
519
Austin Schuh7d87b672019-12-01 20:23:49 -0800520 std::chrono::nanoseconds send_delay() const { return send_delay_; }
521 void set_send_delay(std::chrono::nanoseconds send_delay) {
522 send_delay_ = send_delay;
523 }
524
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800526 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 }
528
529 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800530 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531 }
532
533 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
534
535 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
536
537 void MakeRawWatcher(
538 const Channel *channel,
539 ::std::function<void(const Context &context, const void *message)>
540 watcher) override;
541
542 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800543 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800544 return NewTimer(::std::unique_ptr<TimerHandler>(
545 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 }
547
548 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
549 const monotonic_clock::duration interval,
550 const monotonic_clock::duration offset =
551 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800552 return NewPhasedLoop(
553 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
554 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555 }
556
557 void OnRun(::std::function<void()> on_run) override {
Austin Schuhcc6070c2020-10-10 20:25:56 -0700558 scheduler_->ScheduleOnRun([this, on_run = std::move(on_run)]() {
559 ScopedMarkRealtimeRestorer rt(priority() > 0);
560 on_run();
561 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 }
563
Austin Schuh217a9782019-12-21 23:02:50 -0800564 const Node *node() const override { return node_; }
565
James Kuszmaul3ae42262019-11-08 12:33:41 -0800566 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 name_ = std::string(name);
568 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800569 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570
571 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
572
Austin Schuh39788ff2019-12-01 18:22:57 -0800573 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800575 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 }
577
Austin Schuh39788ff2019-12-01 18:22:57 -0800578 int priority() const override { return priority_; }
579
Brian Silverman6a54ff32020-04-28 16:41:39 -0700580 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
581 CHECK(!is_running()) << ": Cannot set affinity while running.";
582 }
583
Tyler Chatow67ddb032020-01-12 14:30:04 -0800584 void Setup() {
585 MaybeScheduleTimingReports();
586 if (!skip_logger_) {
Tyler Chatow67ddb032020-01-12 14:30:04 -0800587 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700588 log_impl_ = log_sender_.implementation();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800589 }
590 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800591
Brian Silverman4f4e0612020-08-12 19:54:41 -0700592 int NumberBuffers(const Channel *channel) override;
593
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800595 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800596 friend class SimulatedPhasedLoopHandler;
597 friend class SimulatedWatcher;
598
599 void HandleEvent() {
600 while (true) {
601 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
602 break;
603 }
604
605 EventLoopEvent *event = PopEvent();
606 event->HandleEvent();
607 }
608 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800609
Austin Schuh39788ff2019-12-01 18:22:57 -0800610 pid_t GetTid() override { return tid_; }
611
Alex Perrycb7da4b2019-08-28 19:35:56 -0700612 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800613 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
615 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
616 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617
618 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800619
620 int priority_ = 0;
621
622 bool has_setup_ = false;
623
Austin Schuh7d87b672019-12-01 20:23:49 -0800624 std::chrono::nanoseconds send_delay_;
625
Austin Schuh217a9782019-12-21 23:02:50 -0800626 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800627 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800628
629 AosLogToFbs log_sender_;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700630 std::shared_ptr<logging::LogImplementation> log_impl_ = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631};
632
Austin Schuh7d87b672019-12-01 20:23:49 -0800633void SimulatedEventLoopFactory::set_send_delay(
634 std::chrono::nanoseconds send_delay) {
635 send_delay_ = send_delay;
636 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
637 raw_event_loops_) {
638 reinterpret_cast<SimulatedEventLoop *>(loop.first)
639 ->set_send_delay(send_delay_);
640 }
641}
642
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643void SimulatedEventLoop::MakeRawWatcher(
644 const Channel *channel,
645 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800646 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800647
Austin Schuh8bd96322020-02-13 21:18:22 -0800648 std::unique_ptr<SimulatedWatcher> shm_watcher(
649 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800650
651 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
652 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700653}
654
655std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
656 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800657 TakeSender(channel);
658
Alex Perrycb7da4b2019-08-28 19:35:56 -0700659 return GetSimulatedChannel(channel)->MakeRawSender(this);
660}
661
662std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
663 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800664 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800665
Austin Schuhca4828c2019-12-28 14:21:35 -0800666 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
667 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
668 << "\", \"type\": \"" << channel->type()->string_view()
669 << "\" } is not able to be fetched on this node. Check your "
670 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800671 }
672
Austin Schuh39788ff2019-12-01 18:22:57 -0800673 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700674}
675
676SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
677 const Channel *channel) {
678 auto it = channels_->find(SimpleChannel(channel));
679 if (it == channels_->end()) {
680 it = channels_
681 ->emplace(SimpleChannel(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700682 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
683 channel, scheduler_,
684 std::chrono::nanoseconds(
685 configuration()->channel_storage_duration()))))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700686 .first;
687 }
688 return it->second.get();
689}
690
Brian Silverman4f4e0612020-08-12 19:54:41 -0700691int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
692 return GetSimulatedChannel(channel)->number_buffers();
693}
694
Austin Schuh7d87b672019-12-01 20:23:49 -0800695SimulatedWatcher::SimulatedWatcher(
696 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800697 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800698 std::function<void(const Context &context, const void *message)> fn)
699 : WatcherState(simulated_event_loop, channel, std::move(fn)),
700 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700701 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800702 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700703 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800704 token_(scheduler_->InvalidToken()) {}
705
706SimulatedWatcher::~SimulatedWatcher() {
707 simulated_event_loop_->RemoveEvent(&event_);
708 if (token_ != scheduler_->InvalidToken()) {
709 scheduler_->Deschedule(token_);
710 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700711 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800712}
713
714void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800715 monotonic_clock::time_point event_time =
716 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800717
718 // Messages are queued in order. If we are the first, add ourselves.
719 // Otherwise, don't.
720 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800721 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800722 simulated_event_loop_->AddEvent(&event_);
723
724 DoSchedule(event_time);
725 }
726
727 msgs_.emplace_back(message);
728}
729
730void SimulatedWatcher::HandleEvent() {
731 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
732
733 const monotonic_clock::time_point monotonic_now =
734 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800735 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700736 if (simulated_event_loop_->log_impl_) {
737 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800738 }
Austin Schuhad154822019-12-27 15:45:13 -0800739 Context context = msgs_.front()->context;
740
Brian Silverman4f4e0612020-08-12 19:54:41 -0700741 if (channel_->read_method() != ReadMethod::PIN) {
742 context.buffer_index = -1;
743 }
Austin Schuhad154822019-12-27 15:45:13 -0800744 if (context.remote_queue_index == 0xffffffffu) {
745 context.remote_queue_index = context.queue_index;
746 }
747 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
748 context.monotonic_remote_time = context.monotonic_event_time;
749 }
750 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
751 context.realtime_remote_time = context.realtime_event_time;
752 }
753
Austin Schuhcc6070c2020-10-10 20:25:56 -0700754 {
755 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
756 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
757 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800758
759 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700760 if (token_ != scheduler_->InvalidToken()) {
761 scheduler_->Deschedule(token_);
762 token_ = scheduler_->InvalidToken();
763 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800764 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800765 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800766 simulated_event_loop_->AddEvent(&event_);
767
768 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800769 }
770}
771
772void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700773 CHECK(token_ == scheduler_->InvalidToken())
774 << ": May not schedule multiple times";
775 token_ = scheduler_->Schedule(
776 event_time + simulated_event_loop_->send_delay(), [this]() {
777 DCHECK(token_ != scheduler_->InvalidToken());
778 token_ = scheduler_->InvalidToken();
779 simulated_event_loop_->HandleEvent();
780 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800781}
782
783void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700784 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800785 watcher->SetSimulatedChannel(this);
786 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700787}
788
789::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
790 EventLoop *event_loop) {
791 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
792}
793
Austin Schuh39788ff2019-12-01 18:22:57 -0800794::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
795 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700796 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800797 ::std::unique_ptr<SimulatedFetcher> fetcher(
798 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700799 fetchers_.push_back(fetcher.get());
800 return ::std::move(fetcher);
801}
802
Austin Schuhad154822019-12-27 15:45:13 -0800803uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
804 const uint32_t queue_index = next_queue_index_.index();
805 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800806 message->context.data = message->data(channel()->max_size()) +
807 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808 next_queue_index_ = next_queue_index_.Increment();
809
810 latest_message_ = message;
811 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800812 for (SimulatedWatcher *watcher : watchers_) {
813 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700814 }
815 }
816 for (auto &fetcher : fetchers_) {
817 fetcher->Enqueue(message);
818 }
Austin Schuhad154822019-12-27 15:45:13 -0800819
820 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700821}
822
823void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
824 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
825}
826
Austin Schuh39788ff2019-12-01 18:22:57 -0800827SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800828 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
829 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800830 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800831 simulated_event_loop_(simulated_event_loop),
832 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800833 scheduler_(scheduler),
834 token_(scheduler_->InvalidToken()) {}
835
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800836void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
837 monotonic_clock::duration repeat_offset) {
838 Disable();
839 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800840 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800841 base_ = base;
842 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700843 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
844 DCHECK(token_ != scheduler_->InvalidToken());
845 token_ = scheduler_->InvalidToken();
846 simulated_event_loop_->HandleEvent();
847 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800848 event_.set_event_time(base_);
849 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800850}
851
852void SimulatedTimerHandler::HandleEvent() {
853 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800854 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800855 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700856 if (simulated_event_loop_->log_impl_) {
857 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800858 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700859 if (token_ != scheduler_->InvalidToken()) {
860 scheduler_->Deschedule(token_);
861 token_ = scheduler_->InvalidToken();
862 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800863 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
864 // Reschedule.
865 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700866 token_ = scheduler_->Schedule(base_, [this]() {
867 DCHECK(token_ != scheduler_->InvalidToken());
868 token_ = scheduler_->InvalidToken();
869 simulated_event_loop_->HandleEvent();
870 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800871 event_.set_event_time(base_);
872 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800873 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800874
Austin Schuhcc6070c2020-10-10 20:25:56 -0700875 {
876 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
877 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
878 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800879}
880
Austin Schuh7d87b672019-12-01 20:23:49 -0800881void SimulatedTimerHandler::Disable() {
882 simulated_event_loop_->RemoveEvent(&event_);
883 if (token_ != scheduler_->InvalidToken()) {
884 scheduler_->Deschedule(token_);
885 token_ = scheduler_->InvalidToken();
886 }
887}
888
Austin Schuh39788ff2019-12-01 18:22:57 -0800889SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800890 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
891 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800892 const monotonic_clock::duration offset)
893 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
894 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800895 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800896 scheduler_(scheduler),
897 token_(scheduler_->InvalidToken()) {}
898
Austin Schuh7d87b672019-12-01 20:23:49 -0800899SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
900 if (token_ != scheduler_->InvalidToken()) {
901 scheduler_->Deschedule(token_);
902 token_ = scheduler_->InvalidToken();
903 }
904 simulated_event_loop_->RemoveEvent(&event_);
905}
906
907void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800908 monotonic_clock::time_point monotonic_now =
909 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800910 logging::ScopedLogRestorer prev_logger;
Austin Schuha0c41ba2020-09-10 22:59:14 -0700911 if (simulated_event_loop_->log_impl_) {
912 prev_logger.Swap(simulated_event_loop_->log_impl_);
Tyler Chatow67ddb032020-01-12 14:30:04 -0800913 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700914
915 {
916 ScopedMarkRealtimeRestorer rt(simulated_event_loop_->priority() > 0);
917 Call([monotonic_now]() { return monotonic_now; },
918 [this](monotonic_clock::time_point sleep_time) {
919 Schedule(sleep_time);
920 });
921 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800922}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800923
Austin Schuh7d87b672019-12-01 20:23:49 -0800924void SimulatedPhasedLoopHandler::Schedule(
925 monotonic_clock::time_point sleep_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700926 if (token_ != scheduler_->InvalidToken()) {
927 scheduler_->Deschedule(token_);
928 token_ = scheduler_->InvalidToken();
929 }
930 token_ = scheduler_->Schedule(sleep_time, [this]() {
931 DCHECK(token_ != scheduler_->InvalidToken());
932 token_ = scheduler_->InvalidToken();
933 simulated_event_loop_->HandleEvent();
934 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800935 event_.set_event_time(sleep_time);
936 simulated_event_loop_->AddEvent(&event_);
937}
938
Austin Schuhac0771c2020-01-07 18:36:30 -0800939NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800940 EventSchedulerScheduler *scheduler_scheduler,
941 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800942 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
943 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800944 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
945 scheduler_scheduler->AddEventScheduler(&scheduler_);
946}
Austin Schuhac0771c2020-01-07 18:36:30 -0800947
Alex Perrycb7da4b2019-08-28 19:35:56 -0700948SimulatedEventLoopFactory::SimulatedEventLoopFactory(
949 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800950 : configuration_(CHECK_NOTNULL(configuration)),
951 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800952 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800953 node_factories_.emplace_back(new NodeEventLoopFactory(
954 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800955 }
Austin Schuh898f4972020-01-11 17:21:25 -0800956
957 if (configuration::MultiNode(configuration)) {
958 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
959 }
Austin Schuh15649d62019-12-28 16:36:38 -0800960}
961
Alex Perrycb7da4b2019-08-28 19:35:56 -0700962SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
963
Austin Schuhac0771c2020-01-07 18:36:30 -0800964NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
965 const Node *node) {
966 auto result = std::find_if(
967 node_factories_.begin(), node_factories_.end(),
968 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
969 return node_factory->node() == node;
970 });
971
972 CHECK(result != node_factories_.end())
973 << ": Failed to find node " << FlatbufferToJson(node);
974
975 return result->get();
976}
977
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800978::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800979 std::string_view name, const Node *node) {
980 if (node == nullptr) {
981 CHECK(!configuration::MultiNode(configuration()))
982 << ": Can't make a single node event loop in a multi-node world.";
983 } else {
984 CHECK(configuration::MultiNode(configuration()))
985 << ": Can't make a multi-node event loop in a single-node world.";
986 }
987 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
988}
989
990::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800991 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800992 CHECK(!scheduler_.is_running())
993 << ": Can't create an event loop while running";
994
Austin Schuh39788ff2019-12-01 18:22:57 -0800995 pid_t tid = tid_;
996 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800997 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -0800998 &scheduler_, this, &channels_, factory_->configuration(),
999 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08001000 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -08001001 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -08001002 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001003}
1004
1005void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
1006 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1007 raw_event_loops_) {
1008 event_loop.second(true);
1009 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001010 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -08001011 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1012 raw_event_loops_) {
1013 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001014 }
1015}
1016
1017void SimulatedEventLoopFactory::Run() {
1018 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1019 raw_event_loops_) {
1020 event_loop.second(true);
1021 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001022 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -08001023 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1024 raw_event_loops_) {
1025 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001026 }
1027}
1028
Austin Schuh6f3babe2020-01-26 20:34:50 -08001029void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001030 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001031 bridge_->DisableForwarding(channel);
1032}
1033
Austin Schuh4c3b9702020-08-30 11:34:55 -07001034void SimulatedEventLoopFactory::DisableStatistics() {
1035 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1036 bridge_->DisableStatistics();
1037}
1038
Alex Perrycb7da4b2019-08-28 19:35:56 -07001039} // namespace aos