blob: ae053fb2aa2f3349e405bedc6e34d869f7fb6762 [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"
12#include "aos/util/phased_loop.h"
13
14namespace aos {
15
Brian Silverman661eb8d2020-08-12 19:41:01 -070016class SimulatedEventLoop;
17class SimulatedFetcher;
18class SimulatedChannel;
19
20namespace {
21
Alex Perrycb7da4b2019-08-28 19:35:56 -070022// Container for both a message, and the context for it for simulation. This
23// makes tracking the timestamps associated with the data easy.
Brian Silverman661eb8d2020-08-12 19:41:01 -070024struct SimulatedMessage final {
25 SimulatedMessage(const SimulatedMessage &) = delete;
26 SimulatedMessage &operator=(const SimulatedMessage &) = delete;
27
28 // Creates a SimulatedMessage with size bytes of storage.
29 // This is a shared_ptr so we don't have to implement refcounting or copying.
30 static std::shared_ptr<SimulatedMessage> Make(SimulatedChannel *channel);
31
Alex Perrycb7da4b2019-08-28 19:35:56 -070032 // Context for the data.
33 Context context;
34
Brian Silverman661eb8d2020-08-12 19:41:01 -070035 SimulatedChannel *const channel = nullptr;
36 int buffer_index;
37
Alex Perrycb7da4b2019-08-28 19:35:56 -070038 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080039 char *data(size_t buffer_size) {
40 return RoundChannelData(&actual_data[0], buffer_size);
41 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070042
Brian Silvermana1652f32020-01-29 20:41:44 -080043 // Then the data, including padding on the end so we can align the buffer we
44 // actually return from data().
45 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070046
47 private:
48 SimulatedMessage(SimulatedChannel *channel_in);
49 ~SimulatedMessage();
50
51 static void DestroyAndFree(SimulatedMessage *p) {
52 p->~SimulatedMessage();
53 free(p);
54 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070055};
56
Brian Silverman661eb8d2020-08-12 19:41:01 -070057} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080058
Brian Silverman661eb8d2020-08-12 19:41:01 -070059// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
60// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080061class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080062 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080063 SimulatedWatcher(
64 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
65 const Channel *channel,
66 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080067
Austin Schuh7d87b672019-12-01 20:23:49 -080068 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080069
70 void Startup(EventLoop * /*event_loop*/) override {}
71
Austin Schuh7d87b672019-12-01 20:23:49 -080072 void Schedule(std::shared_ptr<SimulatedMessage> message);
73
74 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080075
76 void SetSimulatedChannel(SimulatedChannel *channel) {
77 simulated_channel_ = channel;
78 }
79
80 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080081 void DoSchedule(monotonic_clock::time_point event_time);
82
83 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
84
85 SimulatedEventLoop *simulated_event_loop_;
86 EventHandler<SimulatedWatcher> event_;
87 EventScheduler *scheduler_;
88 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -080089 SimulatedChannel *simulated_channel_ = nullptr;
90};
Alex Perrycb7da4b2019-08-28 19:35:56 -070091
92class SimulatedChannel {
93 public:
Brian Silverman661eb8d2020-08-12 19:41:01 -070094 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler,
95 std::chrono::nanoseconds channel_storage_duration)
Austin Schuh39788ff2019-12-01 18:22:57 -080096 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070097 scheduler_(scheduler),
Brian Silverman661eb8d2020-08-12 19:41:01 -070098 channel_storage_duration_(channel_storage_duration),
99 next_queue_index_(ipc_lib::QueueIndex::Zero(number_buffers())) {
100 available_buffer_indices_.reserve(number_buffers());
101 for (int i = 0; i < number_buffers(); ++i) {
102 available_buffer_indices_.push_back(i);
103 }
104 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105
Brian Silverman661eb8d2020-08-12 19:41:01 -0700106 ~SimulatedChannel() {
107 latest_message_.reset();
108 CHECK_EQ(static_cast<size_t>(number_buffers()),
109 available_buffer_indices_.size());
110 CHECK_EQ(0u, fetchers_.size());
111 CHECK_EQ(0u, watchers_.size());
112 CHECK_EQ(0, sender_count_);
113 }
114
115 // The number of messages we pretend to have in the queue.
116 int queue_size() const {
117 return channel()->frequency() *
118 std::chrono::duration_cast<std::chrono::duration<double>>(
119 channel_storage_duration_)
120 .count();
121 }
122
123 // The number of extra buffers (beyond the queue) we pretend to have.
124 int number_scratch_buffers() const {
125 // We need to start creating messages before we know how many
126 // senders+readers we'll have, so we need to just pick something which is
127 // always big enough.
128 return 50;
129 }
130
131 int number_buffers() const { return queue_size() + number_scratch_buffers(); }
132
133 int GetBufferIndex() {
134 CHECK(!available_buffer_indices_.empty()) << ": This should be impossible";
135 const int result = available_buffer_indices_.back();
136 available_buffer_indices_.pop_back();
137 return result;
138 }
139
140 void FreeBufferIndex(int i) {
141 DCHECK(std::find(available_buffer_indices_.begin(),
142 available_buffer_indices_.end(),
143 i) == available_buffer_indices_.end())
144 << ": Buffer is not in use: " << i;
145 available_buffer_indices_.push_back(i);
146 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700147
148 // Makes a connected raw sender which calls Send below.
149 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
150
151 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800152 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700153
154 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -0800155 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -0800156
Austin Schuh7d87b672019-12-01 20:23:49 -0800157 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800158 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
159 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160
Austin Schuhad154822019-12-27 15:45:13 -0800161 // Sends the message to all the connected receivers and fetchers. Returns the
162 // sent queue index.
163 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164
165 // Unregisters a fetcher.
166 void UnregisterFetcher(SimulatedFetcher *fetcher);
167
168 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
169
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800172 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800173 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700174 }
175
Austin Schuh39788ff2019-12-01 18:22:57 -0800176 const Channel *channel() const { return channel_; }
177
Austin Schuhe516ab02020-05-06 21:37:04 -0700178 void CountSenderCreated() {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700179 CheckBufferCount();
Austin Schuhe516ab02020-05-06 21:37:04 -0700180 if (sender_count_ >= channel()->num_senders()) {
181 LOG(FATAL) << "Failed to create sender on "
182 << configuration::CleanedChannelToString(channel())
183 << ", too many senders.";
184 }
185 ++sender_count_;
186 }
Brian Silverman77162972020-08-12 19:52:40 -0700187
Austin Schuhe516ab02020-05-06 21:37:04 -0700188 void CountSenderDestroyed() {
189 --sender_count_;
190 CHECK_GE(sender_count_, 0);
191 }
192
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193 private:
Brian Silverman77162972020-08-12 19:52:40 -0700194 void CheckBufferCount() {
195 int reader_count = 0;
196 if (channel()->read_method() == ReadMethod::PIN) {
197 reader_count = watchers_.size() + fetchers_.size();
198 }
199 CHECK_LT(reader_count + sender_count_, number_scratch_buffers());
200 }
201
202 void CheckReaderCount() {
203 if (channel()->read_method() != ReadMethod::PIN) {
204 return;
205 }
206 CheckBufferCount();
207 const int reader_count = watchers_.size() + fetchers_.size();
208 if (reader_count >= channel()->num_readers()) {
209 LOG(FATAL) << "Failed to create reader on "
210 << configuration::CleanedChannelToString(channel())
211 << ", too many readers.";
212 }
213 }
Brian Silverman661eb8d2020-08-12 19:41:01 -0700214
215 const Channel *const channel_;
216 EventScheduler *const scheduler_;
217 const std::chrono::nanoseconds channel_storage_duration_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218
219 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800220 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221
222 // List of all fetchers.
223 ::std::vector<SimulatedFetcher *> fetchers_;
224 std::shared_ptr<SimulatedMessage> latest_message_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225
226 ipc_lib::QueueIndex next_queue_index_;
Austin Schuhe516ab02020-05-06 21:37:04 -0700227
228 int sender_count_ = 0;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700229
230 std::vector<uint16_t> available_buffer_indices_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231};
232
233namespace {
234
Brian Silverman661eb8d2020-08-12 19:41:01 -0700235std::shared_ptr<SimulatedMessage> SimulatedMessage::Make(
236 SimulatedChannel *channel) {
237 const size_t size = channel->max_size();
238 SimulatedMessage *const message = reinterpret_cast<SimulatedMessage *>(
Brian Silvermana1652f32020-01-29 20:41:44 -0800239 malloc(sizeof(SimulatedMessage) + size + kChannelDataAlignment - 1));
Brian Silverman661eb8d2020-08-12 19:41:01 -0700240 new (message) SimulatedMessage(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700241 message->context.size = size;
Brian Silvermana1652f32020-01-29 20:41:44 -0800242 message->context.data = message->data(size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243
Brian Silverman661eb8d2020-08-12 19:41:01 -0700244 return std::shared_ptr<SimulatedMessage>(message,
245 &SimulatedMessage::DestroyAndFree);
246}
247
248SimulatedMessage::SimulatedMessage(SimulatedChannel *channel_in)
249 : channel(channel_in) {
250 buffer_index = channel->GetBufferIndex();
251}
252
253SimulatedMessage::~SimulatedMessage() {
254 channel->FreeBufferIndex(buffer_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255}
256
257class SimulatedSender : public RawSender {
258 public:
259 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800260 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800261 simulated_channel_(simulated_channel),
Austin Schuhe516ab02020-05-06 21:37:04 -0700262 event_loop_(event_loop) {
263 simulated_channel_->CountSenderCreated();
264 }
265 ~SimulatedSender() { simulated_channel_->CountSenderDestroyed(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700266
267 void *data() override {
268 if (!message_) {
Brian Silverman661eb8d2020-08-12 19:41:01 -0700269 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800271 return message_->data(simulated_channel_->max_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700272 }
273
274 size_t size() override { return simulated_channel_->max_size(); }
275
Austin Schuhad154822019-12-27 15:45:13 -0800276 bool DoSend(size_t length,
277 aos::monotonic_clock::time_point monotonic_remote_time,
278 aos::realtime_clock::time_point realtime_remote_time,
279 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800281 message_->context.monotonic_event_time = event_loop_->monotonic_now();
282 message_->context.monotonic_remote_time = monotonic_remote_time;
283 message_->context.remote_queue_index = remote_queue_index;
284 message_->context.realtime_event_time = event_loop_->realtime_now();
285 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286 CHECK_LE(length, message_->context.size);
287 message_->context.size = length;
288
289 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800290 sent_queue_index_ = simulated_channel_->Send(message_);
291 monotonic_sent_time_ = event_loop_->monotonic_now();
292 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293
294 // Drop the reference to the message so that we allocate a new message for
295 // next time. Otherwise we will continue to reuse the same memory for all
296 // messages and corrupt it.
297 message_.reset();
298 return true;
299 }
300
Austin Schuhad154822019-12-27 15:45:13 -0800301 bool DoSend(const void *msg, size_t size,
302 aos::monotonic_clock::time_point monotonic_remote_time,
303 aos::realtime_clock::time_point realtime_remote_time,
304 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
306
307 // This is wasteful, but since flatbuffers fill from the back end of the
308 // queue, we need it to be full sized.
Brian Silverman661eb8d2020-08-12 19:41:01 -0700309 message_ = SimulatedMessage::Make(simulated_channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310
311 // Now fill in the message. size is already populated above, and
Austin Schuhac0771c2020-01-07 18:36:30 -0800312 // queue_index will be populated in simulated_channel_. Put this at the
313 // back of the data segment.
Brian Silvermana1652f32020-01-29 20:41:44 -0800314 memcpy(message_->data(simulated_channel_->max_size()) +
315 simulated_channel_->max_size() - size,
316 msg, size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700317
Austin Schuhac0771c2020-01-07 18:36:30 -0800318 return DoSend(size, monotonic_remote_time, realtime_remote_time,
319 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 }
321
Alex Perrycb7da4b2019-08-28 19:35:56 -0700322 private:
323 SimulatedChannel *simulated_channel_;
324 EventLoop *event_loop_;
325
326 std::shared_ptr<SimulatedMessage> message_;
327};
328} // namespace
329
330class SimulatedFetcher : public RawFetcher {
331 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800332 explicit SimulatedFetcher(EventLoop *event_loop,
333 SimulatedChannel *simulated_channel)
334 : RawFetcher(event_loop, simulated_channel->channel()),
335 simulated_channel_(simulated_channel) {}
336 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337
Austin Schuh39788ff2019-12-01 18:22:57 -0800338 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
339 if (msgs_.size() == 0) {
340 return std::make_pair(false, monotonic_clock::min_time);
341 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342
Brian Silverman661eb8d2020-08-12 19:41:01 -0700343 CHECK(!fell_behind_) << ": Got behind";
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 SetMsg(msgs_.front());
346 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800347 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348 }
349
Austin Schuh39788ff2019-12-01 18:22:57 -0800350 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800352 // TODO(austin): Can we just do this logic unconditionally? It is a lot
353 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800354 if (!msg_ && simulated_channel_->latest_message()) {
355 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800356 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800358 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359 }
360 }
361
362 // We've had a message enqueued, so we don't need to go looking for the
363 // latest message from before we started.
364 SetMsg(msgs_.back());
365 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700366 fell_behind_ = false;
Austin Schuha5e14192020-01-06 18:02:41 -0800367 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 }
369
370 private:
371 friend class SimulatedChannel;
372
373 // Updates the state inside RawFetcher to point to the data in msg_.
374 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
375 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 context_ = msg_->context;
Austin Schuhad154822019-12-27 15:45:13 -0800377 if (context_.remote_queue_index == 0xffffffffu) {
378 context_.remote_queue_index = context_.queue_index;
379 }
380 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
381 context_.monotonic_remote_time = context_.monotonic_event_time;
382 }
383 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
384 context_.realtime_remote_time = context_.realtime_event_time;
385 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700386 }
387
388 // Internal method for Simulation to add a message to the buffer.
389 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
390 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700391 if (fell_behind_ ||
392 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
393 fell_behind_ = true;
394 // Might as well empty out all the intermediate messages now.
395 while (msgs_.size() > 1) {
396 msgs_.pop_front();
397 }
398 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 }
400
Austin Schuhac0771c2020-01-07 18:36:30 -0800401 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 std::shared_ptr<SimulatedMessage> msg_;
403
404 // Messages queued up but not in use.
405 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700406
407 // Whether we're currently "behind", which means a FetchNext call will fail.
408 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409};
410
411class SimulatedTimerHandler : public TimerHandler {
412 public:
413 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800414 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800415 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800416 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417
418 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800419 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800421 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422
Austin Schuh7d87b672019-12-01 20:23:49 -0800423 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424
Alex Perrycb7da4b2019-08-28 19:35:56 -0700425 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800426 SimulatedEventLoop *simulated_event_loop_;
427 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428 EventScheduler *scheduler_;
429 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800430
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431 monotonic_clock::time_point base_;
432 monotonic_clock::duration repeat_offset_;
433};
434
435class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
436 public:
437 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800438 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700439 ::std::function<void(int)> fn,
440 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800441 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800442 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443
Austin Schuh7d87b672019-12-01 20:23:49 -0800444 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445
Austin Schuh7d87b672019-12-01 20:23:49 -0800446 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447
448 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800450 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451
Austin Schuh39788ff2019-12-01 18:22:57 -0800452 EventScheduler *scheduler_;
453 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454};
455
456class SimulatedEventLoop : public EventLoop {
457 public:
458 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700459 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
461 *channels,
462 const Configuration *configuration,
463 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800464 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800465 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800466 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800468 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800470 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800471 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800472 tid_(tid) {
473 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
474 if (!has_setup_) {
475 Setup();
476 has_setup_ = true;
477 }
478 set_is_running(value);
479 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 }
481 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800482 // Trigger any remaining senders or fetchers to be cleared before destroying
483 // the event loop so the book keeping matches.
484 timing_report_sender_.reset();
485
486 // Force everything with a registered fd with epoll to be destroyed now.
487 timers_.clear();
488 phased_loops_.clear();
489 watchers_.clear();
490
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
492 ++it) {
493 if (it->first == this) {
494 raw_event_loops_->erase(it);
495 break;
496 }
497 }
498 }
499
Austin Schuh7d87b672019-12-01 20:23:49 -0800500 std::chrono::nanoseconds send_delay() const { return send_delay_; }
501 void set_send_delay(std::chrono::nanoseconds send_delay) {
502 send_delay_ = send_delay;
503 }
504
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800506 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 }
508
509 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800510 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 }
512
513 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
514
515 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
516
517 void MakeRawWatcher(
518 const Channel *channel,
519 ::std::function<void(const Context &context, const void *message)>
520 watcher) override;
521
522 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800523 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800524 return NewTimer(::std::unique_ptr<TimerHandler>(
525 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 }
527
528 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
529 const monotonic_clock::duration interval,
530 const monotonic_clock::duration offset =
531 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800532 return NewPhasedLoop(
533 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
534 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535 }
536
537 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800538 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 }
540
Austin Schuh217a9782019-12-21 23:02:50 -0800541 const Node *node() const override { return node_; }
542
James Kuszmaul3ae42262019-11-08 12:33:41 -0800543 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 name_ = std::string(name);
545 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800546 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547
548 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
549
Austin Schuh39788ff2019-12-01 18:22:57 -0800550 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700551 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800552 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 }
554
Austin Schuh39788ff2019-12-01 18:22:57 -0800555 int priority() const override { return priority_; }
556
Brian Silverman6a54ff32020-04-28 16:41:39 -0700557 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
558 CHECK(!is_running()) << ": Cannot set affinity while running.";
559 }
560
Tyler Chatow67ddb032020-01-12 14:30:04 -0800561 void Setup() {
562 MaybeScheduleTimingReports();
563 if (!skip_logger_) {
564 logging::ScopedLogRestorer prev_logger;
565 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
566 log_impl_ = logging::GetImplementation();
567 }
568 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800569
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800571 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800572 friend class SimulatedPhasedLoopHandler;
573 friend class SimulatedWatcher;
574
575 void HandleEvent() {
576 while (true) {
577 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
578 break;
579 }
580
581 EventLoopEvent *event = PopEvent();
582 event->HandleEvent();
583 }
584 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800585
Austin Schuh39788ff2019-12-01 18:22:57 -0800586 pid_t GetTid() override { return tid_; }
587
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800589 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
591 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
592 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593
594 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800595
596 int priority_ = 0;
597
598 bool has_setup_ = false;
599
Austin Schuh7d87b672019-12-01 20:23:49 -0800600 std::chrono::nanoseconds send_delay_;
601
Austin Schuh217a9782019-12-21 23:02:50 -0800602 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800603 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800604
605 AosLogToFbs log_sender_;
606 logging::LogImplementation *log_impl_ = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607};
608
Austin Schuh7d87b672019-12-01 20:23:49 -0800609void SimulatedEventLoopFactory::set_send_delay(
610 std::chrono::nanoseconds send_delay) {
611 send_delay_ = send_delay;
612 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
613 raw_event_loops_) {
614 reinterpret_cast<SimulatedEventLoop *>(loop.first)
615 ->set_send_delay(send_delay_);
616 }
617}
618
Alex Perrycb7da4b2019-08-28 19:35:56 -0700619void SimulatedEventLoop::MakeRawWatcher(
620 const Channel *channel,
621 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800622 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800623
Austin Schuh8bd96322020-02-13 21:18:22 -0800624 std::unique_ptr<SimulatedWatcher> shm_watcher(
625 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800626
627 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
628 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700629}
630
631std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
632 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800633 TakeSender(channel);
634
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635 return GetSimulatedChannel(channel)->MakeRawSender(this);
636}
637
638std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
639 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800640 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800641
Austin Schuhca4828c2019-12-28 14:21:35 -0800642 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
643 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
644 << "\", \"type\": \"" << channel->type()->string_view()
645 << "\" } is not able to be fetched on this node. Check your "
646 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800647 }
648
Austin Schuh39788ff2019-12-01 18:22:57 -0800649 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650}
651
652SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
653 const Channel *channel) {
654 auto it = channels_->find(SimpleChannel(channel));
655 if (it == channels_->end()) {
656 it = channels_
657 ->emplace(SimpleChannel(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700658 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
659 channel, scheduler_,
660 std::chrono::nanoseconds(
661 configuration()->channel_storage_duration()))))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700662 .first;
663 }
664 return it->second.get();
665}
666
Austin Schuh7d87b672019-12-01 20:23:49 -0800667SimulatedWatcher::SimulatedWatcher(
668 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800669 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800670 std::function<void(const Context &context, const void *message)> fn)
671 : WatcherState(simulated_event_loop, channel, std::move(fn)),
672 simulated_event_loop_(simulated_event_loop),
673 event_(this),
674 scheduler_(scheduler),
675 token_(scheduler_->InvalidToken()) {}
676
677SimulatedWatcher::~SimulatedWatcher() {
678 simulated_event_loop_->RemoveEvent(&event_);
679 if (token_ != scheduler_->InvalidToken()) {
680 scheduler_->Deschedule(token_);
681 }
682 simulated_channel_->RemoveWatcher(this);
683}
684
685void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800686 monotonic_clock::time_point event_time =
687 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800688
689 // Messages are queued in order. If we are the first, add ourselves.
690 // Otherwise, don't.
691 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800692 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800693 simulated_event_loop_->AddEvent(&event_);
694
695 DoSchedule(event_time);
696 }
697
698 msgs_.emplace_back(message);
699}
700
701void SimulatedWatcher::HandleEvent() {
702 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
703
704 const monotonic_clock::time_point monotonic_now =
705 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800706 logging::ScopedLogRestorer prev_logger;
707 if (simulated_event_loop_->log_impl_ != nullptr) {
708 logging::SetImplementation(simulated_event_loop_->log_impl_);
709 }
Austin Schuhad154822019-12-27 15:45:13 -0800710 Context context = msgs_.front()->context;
711
712 if (context.remote_queue_index == 0xffffffffu) {
713 context.remote_queue_index = context.queue_index;
714 }
715 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
716 context.monotonic_remote_time = context.monotonic_event_time;
717 }
718 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
719 context.realtime_remote_time = context.realtime_event_time;
720 }
721
722 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800723
724 msgs_.pop_front();
725 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800726 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800727 simulated_event_loop_->AddEvent(&event_);
728
729 DoSchedule(event_.event_time());
730 } else {
731 token_ = scheduler_->InvalidToken();
732 }
733}
734
735void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800736 token_ =
737 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
738 [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800739}
740
741void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700742 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800743 watcher->SetSimulatedChannel(this);
744 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700745}
746
747::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
748 EventLoop *event_loop) {
749 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
750}
751
Austin Schuh39788ff2019-12-01 18:22:57 -0800752::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
753 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700754 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800755 ::std::unique_ptr<SimulatedFetcher> fetcher(
756 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700757 fetchers_.push_back(fetcher.get());
758 return ::std::move(fetcher);
759}
760
Austin Schuhad154822019-12-27 15:45:13 -0800761uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
762 const uint32_t queue_index = next_queue_index_.index();
763 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800764 message->context.data = message->data(channel()->max_size()) +
765 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700766 next_queue_index_ = next_queue_index_.Increment();
767
768 latest_message_ = message;
769 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800770 for (SimulatedWatcher *watcher : watchers_) {
771 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700772 }
773 }
774 for (auto &fetcher : fetchers_) {
775 fetcher->Enqueue(message);
776 }
Austin Schuhad154822019-12-27 15:45:13 -0800777
778 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779}
780
781void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
782 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
783}
784
Austin Schuh39788ff2019-12-01 18:22:57 -0800785SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800786 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
787 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800788 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800789 simulated_event_loop_(simulated_event_loop),
790 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800791 scheduler_(scheduler),
792 token_(scheduler_->InvalidToken()) {}
793
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800794void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
795 monotonic_clock::duration repeat_offset) {
796 Disable();
797 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800798 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800799 base_ = base;
800 repeat_offset_ = repeat_offset;
801 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800802 token_ = scheduler_->Schedule(
Austin Schuh8bd96322020-02-13 21:18:22 -0800803 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800804 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800805 token_ = scheduler_->Schedule(
Austin Schuh8bd96322020-02-13 21:18:22 -0800806 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800807 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800808 event_.set_event_time(base_);
809 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800810}
811
812void SimulatedTimerHandler::HandleEvent() {
813 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800814 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800815 logging::ScopedLogRestorer prev_logger;
816 if (simulated_event_loop_->log_impl_ != nullptr) {
817 logging::SetImplementation(simulated_event_loop_->log_impl_);
818 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800819 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
820 // Reschedule.
821 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800822 token_ = scheduler_->Schedule(
Austin Schuh8bd96322020-02-13 21:18:22 -0800823 base_, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800824 event_.set_event_time(base_);
825 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800826 } else {
827 token_ = scheduler_->InvalidToken();
828 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800829
Austin Schuh39788ff2019-12-01 18:22:57 -0800830 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800831}
832
Austin Schuh7d87b672019-12-01 20:23:49 -0800833void SimulatedTimerHandler::Disable() {
834 simulated_event_loop_->RemoveEvent(&event_);
835 if (token_ != scheduler_->InvalidToken()) {
836 scheduler_->Deschedule(token_);
837 token_ = scheduler_->InvalidToken();
838 }
839}
840
Austin Schuh39788ff2019-12-01 18:22:57 -0800841SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800842 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
843 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800844 const monotonic_clock::duration offset)
845 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
846 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800847 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800848 scheduler_(scheduler),
849 token_(scheduler_->InvalidToken()) {}
850
Austin Schuh7d87b672019-12-01 20:23:49 -0800851SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
852 if (token_ != scheduler_->InvalidToken()) {
853 scheduler_->Deschedule(token_);
854 token_ = scheduler_->InvalidToken();
855 }
856 simulated_event_loop_->RemoveEvent(&event_);
857}
858
859void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800860 monotonic_clock::time_point monotonic_now =
861 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800862 logging::ScopedLogRestorer prev_logger;
863 if (simulated_event_loop_->log_impl_ != nullptr) {
864 logging::SetImplementation(simulated_event_loop_->log_impl_);
865 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800866 Call(
867 [monotonic_now]() { return monotonic_now; },
868 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
869}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800870
Austin Schuh7d87b672019-12-01 20:23:49 -0800871void SimulatedPhasedLoopHandler::Schedule(
872 monotonic_clock::time_point sleep_time) {
873 token_ = scheduler_->Schedule(
Austin Schuh8bd96322020-02-13 21:18:22 -0800874 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuh7d87b672019-12-01 20:23:49 -0800875 event_.set_event_time(sleep_time);
876 simulated_event_loop_->AddEvent(&event_);
877}
878
Austin Schuhac0771c2020-01-07 18:36:30 -0800879NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800880 EventSchedulerScheduler *scheduler_scheduler,
881 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800882 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
883 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800884 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
885 scheduler_scheduler->AddEventScheduler(&scheduler_);
886}
Austin Schuhac0771c2020-01-07 18:36:30 -0800887
Alex Perrycb7da4b2019-08-28 19:35:56 -0700888SimulatedEventLoopFactory::SimulatedEventLoopFactory(
889 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800890 : configuration_(CHECK_NOTNULL(configuration)),
891 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800892 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800893 node_factories_.emplace_back(new NodeEventLoopFactory(
894 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800895 }
Austin Schuh898f4972020-01-11 17:21:25 -0800896
897 if (configuration::MultiNode(configuration)) {
898 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
899 }
Austin Schuh15649d62019-12-28 16:36:38 -0800900}
901
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
903
Austin Schuhac0771c2020-01-07 18:36:30 -0800904NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
905 const Node *node) {
906 auto result = std::find_if(
907 node_factories_.begin(), node_factories_.end(),
908 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
909 return node_factory->node() == node;
910 });
911
912 CHECK(result != node_factories_.end())
913 << ": Failed to find node " << FlatbufferToJson(node);
914
915 return result->get();
916}
917
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800918::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800919 std::string_view name, const Node *node) {
920 if (node == nullptr) {
921 CHECK(!configuration::MultiNode(configuration()))
922 << ": Can't make a single node event loop in a multi-node world.";
923 } else {
924 CHECK(configuration::MultiNode(configuration()))
925 << ": Can't make a multi-node event loop in a single-node world.";
926 }
927 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
928}
929
930::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800931 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800932 CHECK(!scheduler_.is_running())
933 << ": Can't create an event loop while running";
934
Austin Schuh39788ff2019-12-01 18:22:57 -0800935 pid_t tid = tid_;
936 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800937 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -0800938 &scheduler_, this, &channels_, factory_->configuration(),
939 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800940 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -0800941 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -0800942 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700943}
944
945void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
946 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
947 raw_event_loops_) {
948 event_loop.second(true);
949 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800950 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800951 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
952 raw_event_loops_) {
953 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700954 }
955}
956
957void SimulatedEventLoopFactory::Run() {
958 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
959 raw_event_loops_) {
960 event_loop.second(true);
961 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800962 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800963 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
964 raw_event_loops_) {
965 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700966 }
967}
968
Austin Schuh6f3babe2020-01-26 20:34:50 -0800969void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
970 bridge_->DisableForwarding(channel);
971}
972
Alex Perrycb7da4b2019-08-28 19:35:56 -0700973} // namespace aos