blob: a7301bf4932d2e63cf1f66719e26e328fbd233ce [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;
Brian Silverman661eb8d2020-08-12 19:41:01 -070036
Alex Perrycb7da4b2019-08-28 19:35:56 -070037 // The data.
Brian Silvermana1652f32020-01-29 20:41:44 -080038 char *data(size_t buffer_size) {
39 return RoundChannelData(&actual_data[0], buffer_size);
40 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070041
Brian Silvermana1652f32020-01-29 20:41:44 -080042 // Then the data, including padding on the end so we can align the buffer we
43 // actually return from data().
44 char actual_data[];
Brian Silverman661eb8d2020-08-12 19:41:01 -070045
46 private:
47 SimulatedMessage(SimulatedChannel *channel_in);
48 ~SimulatedMessage();
49
50 static void DestroyAndFree(SimulatedMessage *p) {
51 p->~SimulatedMessage();
52 free(p);
53 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070054};
55
Brian Silverman661eb8d2020-08-12 19:41:01 -070056} // namespace
Austin Schuh39788ff2019-12-01 18:22:57 -080057
Brian Silverman661eb8d2020-08-12 19:41:01 -070058// TODO(Brian): This should be in the anonymous namespace, but that annoys GCC
59// for some reason...
Austin Schuh7d87b672019-12-01 20:23:49 -080060class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080061 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080062 SimulatedWatcher(
63 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
64 const Channel *channel,
65 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080066
Austin Schuh7d87b672019-12-01 20:23:49 -080067 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080068
69 void Startup(EventLoop * /*event_loop*/) override {}
70
Austin Schuh7d87b672019-12-01 20:23:49 -080071 void Schedule(std::shared_ptr<SimulatedMessage> message);
72
73 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080074
75 void SetSimulatedChannel(SimulatedChannel *channel) {
76 simulated_channel_ = channel;
77 }
78
79 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080080 void DoSchedule(monotonic_clock::time_point event_time);
81
82 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
83
Brian Silverman4f4e0612020-08-12 19:54:41 -070084 SimulatedEventLoop *const simulated_event_loop_;
85 const Channel *const channel_;
86 EventScheduler *const scheduler_;
Austin Schuh7d87b672019-12-01 20:23:49 -080087 EventHandler<SimulatedWatcher> event_;
Austin Schuh7d87b672019-12-01 20:23:49 -080088 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) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700250 context.buffer_index = channel->GetBufferIndex();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700251}
252
253SimulatedMessage::~SimulatedMessage() {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700254 channel->FreeBufferIndex(context.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
Brian Silverman4f4e0612020-08-12 19:54:41 -0700322 int buffer_index() override {
323 // First, ensure message_ is allocated.
324 data();
325 return message_->context.buffer_index;
326 }
327
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328 private:
329 SimulatedChannel *simulated_channel_;
330 EventLoop *event_loop_;
331
332 std::shared_ptr<SimulatedMessage> message_;
333};
334} // namespace
335
336class SimulatedFetcher : public RawFetcher {
337 public:
Austin Schuhac0771c2020-01-07 18:36:30 -0800338 explicit SimulatedFetcher(EventLoop *event_loop,
339 SimulatedChannel *simulated_channel)
340 : RawFetcher(event_loop, simulated_channel->channel()),
341 simulated_channel_(simulated_channel) {}
342 ~SimulatedFetcher() { simulated_channel_->UnregisterFetcher(this); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343
Austin Schuh39788ff2019-12-01 18:22:57 -0800344 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
345 if (msgs_.size() == 0) {
346 return std::make_pair(false, monotonic_clock::min_time);
347 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348
Brian Silverman661eb8d2020-08-12 19:41:01 -0700349 CHECK(!fell_behind_) << ": Got behind";
350
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351 SetMsg(msgs_.front());
352 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800353 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354 }
355
Austin Schuh39788ff2019-12-01 18:22:57 -0800356 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800358 // TODO(austin): Can we just do this logic unconditionally? It is a lot
359 // simpler. And call clear, obviously.
Austin Schuhac0771c2020-01-07 18:36:30 -0800360 if (!msg_ && simulated_channel_->latest_message()) {
361 SetMsg(simulated_channel_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800362 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700363 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800364 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 }
366 }
367
368 // We've had a message enqueued, so we don't need to go looking for the
369 // latest message from before we started.
370 SetMsg(msgs_.back());
371 msgs_.clear();
Brian Silverman661eb8d2020-08-12 19:41:01 -0700372 fell_behind_ = false;
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 }
375
376 private:
377 friend class SimulatedChannel;
378
379 // Updates the state inside RawFetcher to point to the data in msg_.
380 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
381 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382 context_ = msg_->context;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700383 if (channel()->read_method() != ReadMethod::PIN) {
384 context_.buffer_index = -1;
385 }
Austin Schuhad154822019-12-27 15:45:13 -0800386 if (context_.remote_queue_index == 0xffffffffu) {
387 context_.remote_queue_index = context_.queue_index;
388 }
389 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
390 context_.monotonic_remote_time = context_.monotonic_event_time;
391 }
392 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
393 context_.realtime_remote_time = context_.realtime_event_time;
394 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 }
396
397 // Internal method for Simulation to add a message to the buffer.
398 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
399 msgs_.emplace_back(buffer);
Brian Silverman661eb8d2020-08-12 19:41:01 -0700400 if (fell_behind_ ||
401 msgs_.size() > static_cast<size_t>(simulated_channel_->queue_size())) {
402 fell_behind_ = true;
403 // Might as well empty out all the intermediate messages now.
404 while (msgs_.size() > 1) {
405 msgs_.pop_front();
406 }
407 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 }
409
Austin Schuhac0771c2020-01-07 18:36:30 -0800410 SimulatedChannel *simulated_channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 std::shared_ptr<SimulatedMessage> msg_;
412
413 // Messages queued up but not in use.
414 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
Brian Silverman661eb8d2020-08-12 19:41:01 -0700415
416 // Whether we're currently "behind", which means a FetchNext call will fail.
417 bool fell_behind_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418};
419
420class SimulatedTimerHandler : public TimerHandler {
421 public:
422 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800423 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800424 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800425 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426
427 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800428 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800430 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431
Austin Schuh7d87b672019-12-01 20:23:49 -0800432 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800435 SimulatedEventLoop *simulated_event_loop_;
436 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700437 EventScheduler *scheduler_;
438 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800439
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 monotonic_clock::time_point base_;
441 monotonic_clock::duration repeat_offset_;
442};
443
444class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
445 public:
446 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800447 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 ::std::function<void(int)> fn,
449 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800450 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800451 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452
Austin Schuh7d87b672019-12-01 20:23:49 -0800453 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454
Austin Schuh7d87b672019-12-01 20:23:49 -0800455 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456
457 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800458 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800459 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 EventScheduler *scheduler_;
462 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463};
464
465class SimulatedEventLoop : public EventLoop {
466 public:
467 explicit SimulatedEventLoop(
Brian Silverman661eb8d2020-08-12 19:41:01 -0700468 EventScheduler *scheduler, NodeEventLoopFactory *node_event_loop_factory,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
470 *channels,
471 const Configuration *configuration,
472 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800473 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800474 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800475 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476 scheduler_(scheduler),
Austin Schuhac0771c2020-01-07 18:36:30 -0800477 node_event_loop_factory_(node_event_loop_factory),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800479 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800480 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800481 tid_(tid) {
482 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
483 if (!has_setup_) {
484 Setup();
485 has_setup_ = true;
486 }
487 set_is_running(value);
488 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489 }
490 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800491 // Trigger any remaining senders or fetchers to be cleared before destroying
492 // the event loop so the book keeping matches.
493 timing_report_sender_.reset();
494
495 // Force everything with a registered fd with epoll to be destroyed now.
496 timers_.clear();
497 phased_loops_.clear();
498 watchers_.clear();
499
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
501 ++it) {
502 if (it->first == this) {
503 raw_event_loops_->erase(it);
504 break;
505 }
506 }
507 }
508
Austin Schuh7d87b672019-12-01 20:23:49 -0800509 std::chrono::nanoseconds send_delay() const { return send_delay_; }
510 void set_send_delay(std::chrono::nanoseconds send_delay) {
511 send_delay_ = send_delay;
512 }
513
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514 ::aos::monotonic_clock::time_point monotonic_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800515 return node_event_loop_factory_->monotonic_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516 }
517
518 ::aos::realtime_clock::time_point realtime_now() override {
Austin Schuhac0771c2020-01-07 18:36:30 -0800519 return node_event_loop_factory_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520 }
521
522 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
523
524 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
525
526 void MakeRawWatcher(
527 const Channel *channel,
528 ::std::function<void(const Context &context, const void *message)>
529 watcher) override;
530
531 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800532 CHECK(!is_running());
Austin Schuh8bd96322020-02-13 21:18:22 -0800533 return NewTimer(::std::unique_ptr<TimerHandler>(
534 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535 }
536
537 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
538 const monotonic_clock::duration interval,
539 const monotonic_clock::duration offset =
540 ::std::chrono::seconds(0)) override {
Austin Schuh8bd96322020-02-13 21:18:22 -0800541 return NewPhasedLoop(
542 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
543 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 }
545
546 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800547 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548 }
549
Austin Schuh217a9782019-12-21 23:02:50 -0800550 const Node *node() const override { return node_; }
551
James Kuszmaul3ae42262019-11-08 12:33:41 -0800552 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 name_ = std::string(name);
554 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800555 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556
557 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
558
Austin Schuh39788ff2019-12-01 18:22:57 -0800559 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 }
563
Austin Schuh39788ff2019-12-01 18:22:57 -0800564 int priority() const override { return priority_; }
565
Brian Silverman6a54ff32020-04-28 16:41:39 -0700566 void SetRuntimeAffinity(const cpu_set_t & /*cpuset*/) override {
567 CHECK(!is_running()) << ": Cannot set affinity while running.";
568 }
569
Tyler Chatow67ddb032020-01-12 14:30:04 -0800570 void Setup() {
571 MaybeScheduleTimingReports();
572 if (!skip_logger_) {
573 logging::ScopedLogRestorer prev_logger;
574 log_sender_.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
575 log_impl_ = logging::GetImplementation();
576 }
577 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800578
Brian Silverman4f4e0612020-08-12 19:54:41 -0700579 int NumberBuffers(const Channel *channel) override;
580
Alex Perrycb7da4b2019-08-28 19:35:56 -0700581 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800582 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800583 friend class SimulatedPhasedLoopHandler;
584 friend class SimulatedWatcher;
585
586 void HandleEvent() {
587 while (true) {
588 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
589 break;
590 }
591
592 EventLoopEvent *event = PopEvent();
593 event->HandleEvent();
594 }
595 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597 pid_t GetTid() override { return tid_; }
598
Alex Perrycb7da4b2019-08-28 19:35:56 -0700599 EventScheduler *scheduler_;
Austin Schuhac0771c2020-01-07 18:36:30 -0800600 NodeEventLoopFactory *node_event_loop_factory_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700601 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
602 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
603 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604
605 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800606
607 int priority_ = 0;
608
609 bool has_setup_ = false;
610
Austin Schuh7d87b672019-12-01 20:23:49 -0800611 std::chrono::nanoseconds send_delay_;
612
Austin Schuh217a9782019-12-21 23:02:50 -0800613 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800614 const pid_t tid_;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800615
616 AosLogToFbs log_sender_;
617 logging::LogImplementation *log_impl_ = nullptr;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618};
619
Austin Schuh7d87b672019-12-01 20:23:49 -0800620void SimulatedEventLoopFactory::set_send_delay(
621 std::chrono::nanoseconds send_delay) {
622 send_delay_ = send_delay;
623 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
624 raw_event_loops_) {
625 reinterpret_cast<SimulatedEventLoop *>(loop.first)
626 ->set_send_delay(send_delay_);
627 }
628}
629
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630void SimulatedEventLoop::MakeRawWatcher(
631 const Channel *channel,
632 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800633 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800634
Austin Schuh8bd96322020-02-13 21:18:22 -0800635 std::unique_ptr<SimulatedWatcher> shm_watcher(
636 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800637
638 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
639 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700640}
641
642std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
643 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800644 TakeSender(channel);
645
Alex Perrycb7da4b2019-08-28 19:35:56 -0700646 return GetSimulatedChannel(channel)->MakeRawSender(this);
647}
648
649std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
650 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800651 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800652
Austin Schuhca4828c2019-12-28 14:21:35 -0800653 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
654 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
655 << "\", \"type\": \"" << channel->type()->string_view()
656 << "\" } is not able to be fetched on this node. Check your "
657 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800658 }
659
Austin Schuh39788ff2019-12-01 18:22:57 -0800660 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661}
662
663SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
664 const Channel *channel) {
665 auto it = channels_->find(SimpleChannel(channel));
666 if (it == channels_->end()) {
667 it = channels_
668 ->emplace(SimpleChannel(channel),
Brian Silverman661eb8d2020-08-12 19:41:01 -0700669 std::unique_ptr<SimulatedChannel>(new SimulatedChannel(
670 channel, scheduler_,
671 std::chrono::nanoseconds(
672 configuration()->channel_storage_duration()))))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673 .first;
674 }
675 return it->second.get();
676}
677
Brian Silverman4f4e0612020-08-12 19:54:41 -0700678int SimulatedEventLoop::NumberBuffers(const Channel *channel) {
679 return GetSimulatedChannel(channel)->number_buffers();
680}
681
Austin Schuh7d87b672019-12-01 20:23:49 -0800682SimulatedWatcher::SimulatedWatcher(
683 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
Austin Schuh8bd96322020-02-13 21:18:22 -0800684 const Channel *channel,
Austin Schuh7d87b672019-12-01 20:23:49 -0800685 std::function<void(const Context &context, const void *message)> fn)
686 : WatcherState(simulated_event_loop, channel, std::move(fn)),
687 simulated_event_loop_(simulated_event_loop),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700688 channel_(channel),
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 scheduler_(scheduler),
Brian Silverman4f4e0612020-08-12 19:54:41 -0700690 event_(this),
Austin Schuh7d87b672019-12-01 20:23:49 -0800691 token_(scheduler_->InvalidToken()) {}
692
693SimulatedWatcher::~SimulatedWatcher() {
694 simulated_event_loop_->RemoveEvent(&event_);
695 if (token_ != scheduler_->InvalidToken()) {
696 scheduler_->Deschedule(token_);
697 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700698 CHECK_NOTNULL(simulated_channel_)->RemoveWatcher(this);
Austin Schuh7d87b672019-12-01 20:23:49 -0800699}
700
701void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800702 monotonic_clock::time_point event_time =
703 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800704
705 // Messages are queued in order. If we are the first, add ourselves.
706 // Otherwise, don't.
707 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800708 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800709 simulated_event_loop_->AddEvent(&event_);
710
711 DoSchedule(event_time);
712 }
713
714 msgs_.emplace_back(message);
715}
716
717void SimulatedWatcher::HandleEvent() {
718 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
719
720 const monotonic_clock::time_point monotonic_now =
721 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800722 logging::ScopedLogRestorer prev_logger;
723 if (simulated_event_loop_->log_impl_ != nullptr) {
724 logging::SetImplementation(simulated_event_loop_->log_impl_);
725 }
Austin Schuhad154822019-12-27 15:45:13 -0800726 Context context = msgs_.front()->context;
727
Brian Silverman4f4e0612020-08-12 19:54:41 -0700728 if (channel_->read_method() != ReadMethod::PIN) {
729 context.buffer_index = -1;
730 }
Austin Schuhad154822019-12-27 15:45:13 -0800731 if (context.remote_queue_index == 0xffffffffu) {
732 context.remote_queue_index = context.queue_index;
733 }
734 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
735 context.monotonic_remote_time = context.monotonic_event_time;
736 }
737 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
738 context.realtime_remote_time = context.realtime_event_time;
739 }
740
741 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800742
743 msgs_.pop_front();
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700744 if (token_ != scheduler_->InvalidToken()) {
745 scheduler_->Deschedule(token_);
746 token_ = scheduler_->InvalidToken();
747 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800748 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800749 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800750 simulated_event_loop_->AddEvent(&event_);
751
752 DoSchedule(event_.event_time());
Austin Schuh7d87b672019-12-01 20:23:49 -0800753 }
754}
755
756void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700757 CHECK(token_ == scheduler_->InvalidToken())
758 << ": May not schedule multiple times";
759 token_ = scheduler_->Schedule(
760 event_time + simulated_event_loop_->send_delay(), [this]() {
761 DCHECK(token_ != scheduler_->InvalidToken());
762 token_ = scheduler_->InvalidToken();
763 simulated_event_loop_->HandleEvent();
764 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800765}
766
767void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Brian Silverman77162972020-08-12 19:52:40 -0700768 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800769 watcher->SetSimulatedChannel(this);
770 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771}
772
773::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
774 EventLoop *event_loop) {
775 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
776}
777
Austin Schuh39788ff2019-12-01 18:22:57 -0800778::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
779 EventLoop *event_loop) {
Brian Silverman77162972020-08-12 19:52:40 -0700780 CheckReaderCount();
Austin Schuh39788ff2019-12-01 18:22:57 -0800781 ::std::unique_ptr<SimulatedFetcher> fetcher(
782 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700783 fetchers_.push_back(fetcher.get());
784 return ::std::move(fetcher);
785}
786
Austin Schuhad154822019-12-27 15:45:13 -0800787uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
788 const uint32_t queue_index = next_queue_index_.index();
789 message->context.queue_index = queue_index;
Brian Silvermana1652f32020-01-29 20:41:44 -0800790 message->context.data = message->data(channel()->max_size()) +
791 channel()->max_size() - message->context.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700792 next_queue_index_ = next_queue_index_.Increment();
793
794 latest_message_ = message;
795 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800796 for (SimulatedWatcher *watcher : watchers_) {
797 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700798 }
799 }
800 for (auto &fetcher : fetchers_) {
801 fetcher->Enqueue(message);
802 }
Austin Schuhad154822019-12-27 15:45:13 -0800803
804 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700805}
806
807void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
808 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
809}
810
Austin Schuh39788ff2019-12-01 18:22:57 -0800811SimulatedTimerHandler::SimulatedTimerHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800812 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
813 ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800814 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800815 simulated_event_loop_(simulated_event_loop),
816 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800817 scheduler_(scheduler),
818 token_(scheduler_->InvalidToken()) {}
819
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800820void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
821 monotonic_clock::duration repeat_offset) {
822 Disable();
823 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800824 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800825 base_ = base;
826 repeat_offset_ = repeat_offset;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700827 token_ = scheduler_->Schedule(std::max(base, monotonic_now), [this]() {
828 DCHECK(token_ != scheduler_->InvalidToken());
829 token_ = scheduler_->InvalidToken();
830 simulated_event_loop_->HandleEvent();
831 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800832 event_.set_event_time(base_);
833 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800834}
835
836void SimulatedTimerHandler::HandleEvent() {
837 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800838 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800839 logging::ScopedLogRestorer prev_logger;
840 if (simulated_event_loop_->log_impl_ != nullptr) {
841 logging::SetImplementation(simulated_event_loop_->log_impl_);
842 }
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700843 if (token_ != scheduler_->InvalidToken()) {
844 scheduler_->Deschedule(token_);
845 token_ = scheduler_->InvalidToken();
846 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800847 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
848 // Reschedule.
849 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700850 token_ = scheduler_->Schedule(base_, [this]() {
851 DCHECK(token_ != scheduler_->InvalidToken());
852 token_ = scheduler_->InvalidToken();
853 simulated_event_loop_->HandleEvent();
854 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800855 event_.set_event_time(base_);
856 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800857 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800858
Austin Schuh39788ff2019-12-01 18:22:57 -0800859 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800860}
861
Austin Schuh7d87b672019-12-01 20:23:49 -0800862void SimulatedTimerHandler::Disable() {
863 simulated_event_loop_->RemoveEvent(&event_);
864 if (token_ != scheduler_->InvalidToken()) {
865 scheduler_->Deschedule(token_);
866 token_ = scheduler_->InvalidToken();
867 }
868}
869
Austin Schuh39788ff2019-12-01 18:22:57 -0800870SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
Austin Schuh8bd96322020-02-13 21:18:22 -0800871 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
872 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800873 const monotonic_clock::duration offset)
874 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
875 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800876 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800877 scheduler_(scheduler),
878 token_(scheduler_->InvalidToken()) {}
879
Austin Schuh7d87b672019-12-01 20:23:49 -0800880SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
881 if (token_ != scheduler_->InvalidToken()) {
882 scheduler_->Deschedule(token_);
883 token_ = scheduler_->InvalidToken();
884 }
885 simulated_event_loop_->RemoveEvent(&event_);
886}
887
888void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800889 monotonic_clock::time_point monotonic_now =
890 simulated_event_loop_->monotonic_now();
Tyler Chatow67ddb032020-01-12 14:30:04 -0800891 logging::ScopedLogRestorer prev_logger;
892 if (simulated_event_loop_->log_impl_ != nullptr) {
893 logging::SetImplementation(simulated_event_loop_->log_impl_);
894 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800895 Call(
896 [monotonic_now]() { return monotonic_now; },
897 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
898}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800899
Austin Schuh7d87b672019-12-01 20:23:49 -0800900void SimulatedPhasedLoopHandler::Schedule(
901 monotonic_clock::time_point sleep_time) {
Austin Schuheb4e4ce2020-09-10 23:04:18 -0700902 if (token_ != scheduler_->InvalidToken()) {
903 scheduler_->Deschedule(token_);
904 token_ = scheduler_->InvalidToken();
905 }
906 token_ = scheduler_->Schedule(sleep_time, [this]() {
907 DCHECK(token_ != scheduler_->InvalidToken());
908 token_ = scheduler_->InvalidToken();
909 simulated_event_loop_->HandleEvent();
910 });
Austin Schuh7d87b672019-12-01 20:23:49 -0800911 event_.set_event_time(sleep_time);
912 simulated_event_loop_->AddEvent(&event_);
913}
914
Austin Schuhac0771c2020-01-07 18:36:30 -0800915NodeEventLoopFactory::NodeEventLoopFactory(
Austin Schuh8bd96322020-02-13 21:18:22 -0800916 EventSchedulerScheduler *scheduler_scheduler,
917 SimulatedEventLoopFactory *factory, const Node *node,
Austin Schuhac0771c2020-01-07 18:36:30 -0800918 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
919 *raw_event_loops)
Austin Schuh8bd96322020-02-13 21:18:22 -0800920 : factory_(factory), node_(node), raw_event_loops_(raw_event_loops) {
921 scheduler_scheduler->AddEventScheduler(&scheduler_);
922}
Austin Schuhac0771c2020-01-07 18:36:30 -0800923
Alex Perrycb7da4b2019-08-28 19:35:56 -0700924SimulatedEventLoopFactory::SimulatedEventLoopFactory(
925 const Configuration *configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800926 : configuration_(CHECK_NOTNULL(configuration)),
927 nodes_(configuration::GetNodes(configuration_)) {
Austin Schuhac0771c2020-01-07 18:36:30 -0800928 for (const Node *node : nodes_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800929 node_factories_.emplace_back(new NodeEventLoopFactory(
930 &scheduler_scheduler_, this, node, &raw_event_loops_));
Austin Schuh15649d62019-12-28 16:36:38 -0800931 }
Austin Schuh898f4972020-01-11 17:21:25 -0800932
933 if (configuration::MultiNode(configuration)) {
934 bridge_ = std::make_unique<message_bridge::SimulatedMessageBridge>(this);
935 }
Austin Schuh15649d62019-12-28 16:36:38 -0800936}
937
Alex Perrycb7da4b2019-08-28 19:35:56 -0700938SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
939
Austin Schuhac0771c2020-01-07 18:36:30 -0800940NodeEventLoopFactory *SimulatedEventLoopFactory::GetNodeEventLoopFactory(
941 const Node *node) {
942 auto result = std::find_if(
943 node_factories_.begin(), node_factories_.end(),
944 [node](const std::unique_ptr<NodeEventLoopFactory> &node_factory) {
945 return node_factory->node() == node;
946 });
947
948 CHECK(result != node_factories_.end())
949 << ": Failed to find node " << FlatbufferToJson(node);
950
951 return result->get();
952}
953
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800954::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
Austin Schuhac0771c2020-01-07 18:36:30 -0800955 std::string_view name, const Node *node) {
956 if (node == nullptr) {
957 CHECK(!configuration::MultiNode(configuration()))
958 << ": Can't make a single node event loop in a multi-node world.";
959 } else {
960 CHECK(configuration::MultiNode(configuration()))
961 << ": Can't make a multi-node event loop in a single-node world.";
962 }
963 return GetNodeEventLoopFactory(node)->MakeEventLoop(name);
964}
965
966::std::unique_ptr<EventLoop> NodeEventLoopFactory::MakeEventLoop(
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800967 std::string_view name) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800968 CHECK(!scheduler_.is_running())
969 << ": Can't create an event loop while running";
970
Austin Schuh39788ff2019-12-01 18:22:57 -0800971 pid_t tid = tid_;
972 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800973 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh8bd96322020-02-13 21:18:22 -0800974 &scheduler_, this, &channels_, factory_->configuration(),
975 raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800976 result->set_name(name);
Austin Schuhac0771c2020-01-07 18:36:30 -0800977 result->set_send_delay(factory_->send_delay());
Austin Schuh7d87b672019-12-01 20:23:49 -0800978 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700979}
980
981void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
982 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
983 raw_event_loops_) {
984 event_loop.second(true);
985 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800986 scheduler_scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800987 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
988 raw_event_loops_) {
989 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700990 }
991}
992
993void SimulatedEventLoopFactory::Run() {
994 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
995 raw_event_loops_) {
996 event_loop.second(true);
997 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800998 scheduler_scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800999 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
1000 raw_event_loops_) {
1001 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001002 }
1003}
1004
Austin Schuh6f3babe2020-01-26 20:34:50 -08001005void SimulatedEventLoopFactory::DisableForwarding(const Channel *channel) {
Austin Schuh4c3b9702020-08-30 11:34:55 -07001006 CHECK(bridge_) << ": Can't disable forwarding without a message bridge.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001007 bridge_->DisableForwarding(channel);
1008}
1009
Austin Schuh4c3b9702020-08-30 11:34:55 -07001010void SimulatedEventLoopFactory::DisableStatistics() {
1011 CHECK(bridge_) << ": Can't disable statistics without a message bridge.";
1012 bridge_->DisableStatistics();
1013}
1014
Alex Perrycb7da4b2019-08-28 19:35:56 -07001015} // namespace aos