blob: e34a23feba2cad1dc39822c3e707cad92dc3a9b7 [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>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006
7#include "absl/container/btree_map.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "aos/json_to_flatbuffer.h"
9#include "aos/util/phased_loop.h"
10
11namespace aos {
12
13// Container for both a message, and the context for it for simulation. This
14// makes tracking the timestamps associated with the data easy.
15struct SimulatedMessage {
16 // Struct to let us force data to be well aligned.
17 struct OveralignedChar {
Brian Silverman0fc69932020-01-24 21:54:02 -080018 char data alignas(64);
Alex Perrycb7da4b2019-08-28 19:35:56 -070019 };
20
21 // Context for the data.
22 Context context;
23
24 // The data.
25 char *data() { return reinterpret_cast<char *>(&actual_data[0]); }
26
27 // Then the data.
28 OveralignedChar actual_data[];
29};
30
Austin Schuh7d87b672019-12-01 20:23:49 -080031class SimulatedEventLoop;
Alex Perrycb7da4b2019-08-28 19:35:56 -070032class SimulatedFetcher;
Austin Schuh39788ff2019-12-01 18:22:57 -080033class SimulatedChannel;
34
Austin Schuh7d87b672019-12-01 20:23:49 -080035class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080036 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080037 SimulatedWatcher(
38 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
39 const Channel *channel,
40 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080041
Austin Schuh7d87b672019-12-01 20:23:49 -080042 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080043
44 void Startup(EventLoop * /*event_loop*/) override {}
45
Austin Schuh7d87b672019-12-01 20:23:49 -080046 void Schedule(std::shared_ptr<SimulatedMessage> message);
47
48 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080049
50 void SetSimulatedChannel(SimulatedChannel *channel) {
51 simulated_channel_ = channel;
52 }
53
54 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080055 void DoSchedule(monotonic_clock::time_point event_time);
56
57 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
58
59 SimulatedEventLoop *simulated_event_loop_;
60 EventHandler<SimulatedWatcher> event_;
61 EventScheduler *scheduler_;
62 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -080063 SimulatedChannel *simulated_channel_ = nullptr;
64};
Alex Perrycb7da4b2019-08-28 19:35:56 -070065
66class SimulatedChannel {
67 public:
68 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -080069 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070070 scheduler_(scheduler),
71 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
72
73 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
74
75 // Makes a connected raw sender which calls Send below.
76 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
77
78 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -080079 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -070080
81 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -080082 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -080083
Austin Schuh7d87b672019-12-01 20:23:49 -080084 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -080085 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
86 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070087
Austin Schuhad154822019-12-27 15:45:13 -080088 // Sends the message to all the connected receivers and fetchers. Returns the
89 // sent queue index.
90 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -070091
92 // Unregisters a fetcher.
93 void UnregisterFetcher(SimulatedFetcher *fetcher);
94
95 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
96
Austin Schuh39788ff2019-12-01 18:22:57 -080097 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Austin Schuh5f1cc5c2019-12-01 18:01:11 -080099 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101 }
102
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 const Channel *channel() const { return channel_; }
104
105 ::aos::monotonic_clock::time_point monotonic_now() const {
106 return scheduler_->monotonic_now();
107 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108
109 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800110 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111
112 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800113 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700114
115 // List of all fetchers.
116 ::std::vector<SimulatedFetcher *> fetchers_;
117 std::shared_ptr<SimulatedMessage> latest_message_;
118 EventScheduler *scheduler_;
119
120 ipc_lib::QueueIndex next_queue_index_;
121};
122
123namespace {
124
125// Creates a SimulatedMessage with size bytes of storage.
126// This is a shared_ptr so we don't have to implement refcounting or copying.
127std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
128 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
129 malloc(sizeof(SimulatedMessage) + size));
130 message->context.size = size;
131 message->context.data = message->data();
132
133 return std::shared_ptr<SimulatedMessage>(message, free);
134}
135
136class SimulatedSender : public RawSender {
137 public:
138 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800139 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800140 simulated_channel_(simulated_channel),
141 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700142 ~SimulatedSender() {}
143
144 void *data() override {
145 if (!message_) {
146 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
147 }
148 return message_->data();
149 }
150
151 size_t size() override { return simulated_channel_->max_size(); }
152
Austin Schuhad154822019-12-27 15:45:13 -0800153 bool DoSend(size_t length,
154 aos::monotonic_clock::time_point monotonic_remote_time,
155 aos::realtime_clock::time_point realtime_remote_time,
156 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700157 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800158 message_->context.monotonic_event_time = event_loop_->monotonic_now();
159 message_->context.monotonic_remote_time = monotonic_remote_time;
160 message_->context.remote_queue_index = remote_queue_index;
161 message_->context.realtime_event_time = event_loop_->realtime_now();
162 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163 CHECK_LE(length, message_->context.size);
164 message_->context.size = length;
165
166 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800167 sent_queue_index_ = simulated_channel_->Send(message_);
168 monotonic_sent_time_ = event_loop_->monotonic_now();
169 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700170
171 // Drop the reference to the message so that we allocate a new message for
172 // next time. Otherwise we will continue to reuse the same memory for all
173 // messages and corrupt it.
174 message_.reset();
175 return true;
176 }
177
Austin Schuhad154822019-12-27 15:45:13 -0800178 bool DoSend(const void *msg, size_t size,
179 aos::monotonic_clock::time_point monotonic_remote_time,
180 aos::realtime_clock::time_point realtime_remote_time,
181 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
183
184 // This is wasteful, but since flatbuffers fill from the back end of the
185 // queue, we need it to be full sized.
186 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
187
188 // Now fill in the message. size is already populated above, and
189 // queue_index will be populated in queue_. Put this at the back of the
190 // data segment.
191 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
192
Austin Schuhad154822019-12-27 15:45:13 -0800193 return Send(size, monotonic_remote_time, realtime_remote_time,
194 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 }
196
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197 private:
198 SimulatedChannel *simulated_channel_;
199 EventLoop *event_loop_;
200
201 std::shared_ptr<SimulatedMessage> message_;
202};
203} // namespace
204
205class SimulatedFetcher : public RawFetcher {
206 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800207 explicit SimulatedFetcher(EventLoop *event_loop, SimulatedChannel *queue)
208 : RawFetcher(event_loop, queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
210
Austin Schuh39788ff2019-12-01 18:22:57 -0800211 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
212 if (msgs_.size() == 0) {
213 return std::make_pair(false, monotonic_clock::min_time);
214 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700215
216 SetMsg(msgs_.front());
217 msgs_.pop_front();
Austin Schuha5e14192020-01-06 18:02:41 -0800218 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700219 }
220
Austin Schuh39788ff2019-12-01 18:22:57 -0800221 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700222 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800223 // TODO(austin): Can we just do this logic unconditionally? It is a lot
224 // simpler. And call clear, obviously.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225 if (!msg_ && queue_->latest_message()) {
226 SetMsg(queue_->latest_message());
Austin Schuha5e14192020-01-06 18:02:41 -0800227 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700228 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800229 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230 }
231 }
232
233 // We've had a message enqueued, so we don't need to go looking for the
234 // latest message from before we started.
235 SetMsg(msgs_.back());
236 msgs_.clear();
Austin Schuha5e14192020-01-06 18:02:41 -0800237 return std::make_pair(true, event_loop()->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700238 }
239
240 private:
241 friend class SimulatedChannel;
242
243 // Updates the state inside RawFetcher to point to the data in msg_.
244 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
245 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700246 context_ = msg_->context;
Austin Schuhad154822019-12-27 15:45:13 -0800247 if (context_.remote_queue_index == 0xffffffffu) {
248 context_.remote_queue_index = context_.queue_index;
249 }
250 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
251 context_.monotonic_remote_time = context_.monotonic_event_time;
252 }
253 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
254 context_.realtime_remote_time = context_.realtime_event_time;
255 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 }
257
258 // Internal method for Simulation to add a message to the buffer.
259 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
260 msgs_.emplace_back(buffer);
261 }
262
263 SimulatedChannel *queue_;
264 std::shared_ptr<SimulatedMessage> msg_;
265
266 // Messages queued up but not in use.
267 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
268};
269
270class SimulatedTimerHandler : public TimerHandler {
271 public:
272 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800273 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800274 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800275 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700276
277 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800278 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800280 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281
Austin Schuh7d87b672019-12-01 20:23:49 -0800282 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800285 SimulatedEventLoop *simulated_event_loop_;
286 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287 EventScheduler *scheduler_;
288 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800289
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290 monotonic_clock::time_point base_;
291 monotonic_clock::duration repeat_offset_;
292};
293
294class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
295 public:
296 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800297 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298 ::std::function<void(int)> fn,
299 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800300 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800301 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700302
Austin Schuh7d87b672019-12-01 20:23:49 -0800303 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304
Austin Schuh7d87b672019-12-01 20:23:49 -0800305 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306
307 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800308 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800309 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310
Austin Schuh39788ff2019-12-01 18:22:57 -0800311 EventScheduler *scheduler_;
312 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313};
314
315class SimulatedEventLoop : public EventLoop {
316 public:
317 explicit SimulatedEventLoop(
318 EventScheduler *scheduler,
319 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
320 *channels,
321 const Configuration *configuration,
322 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800323 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800324 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800325 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700326 scheduler_(scheduler),
327 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800328 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800329 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800330 tid_(tid) {
331 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
332 if (!has_setup_) {
333 Setup();
334 has_setup_ = true;
335 }
336 set_is_running(value);
337 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338 }
339 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800340 // Trigger any remaining senders or fetchers to be cleared before destroying
341 // the event loop so the book keeping matches.
342 timing_report_sender_.reset();
343
344 // Force everything with a registered fd with epoll to be destroyed now.
345 timers_.clear();
346 phased_loops_.clear();
347 watchers_.clear();
348
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
350 ++it) {
351 if (it->first == this) {
352 raw_event_loops_->erase(it);
353 break;
354 }
355 }
356 }
357
Austin Schuh7d87b672019-12-01 20:23:49 -0800358 std::chrono::nanoseconds send_delay() const { return send_delay_; }
359 void set_send_delay(std::chrono::nanoseconds send_delay) {
360 send_delay_ = send_delay;
361 }
362
Alex Perrycb7da4b2019-08-28 19:35:56 -0700363 ::aos::monotonic_clock::time_point monotonic_now() override {
364 return scheduler_->monotonic_now();
365 }
366
367 ::aos::realtime_clock::time_point realtime_now() override {
368 return scheduler_->realtime_now();
369 }
370
371 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
372
373 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
374
375 void MakeRawWatcher(
376 const Channel *channel,
377 ::std::function<void(const Context &context, const void *message)>
378 watcher) override;
379
380 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800381 CHECK(!is_running());
382 return NewTimer(::std::unique_ptr<TimerHandler>(
383 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700384 }
385
386 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
387 const monotonic_clock::duration interval,
388 const monotonic_clock::duration offset =
389 ::std::chrono::seconds(0)) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800390 return NewPhasedLoop(
391 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
392 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 }
394
395 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800396 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700397 }
398
Austin Schuh217a9782019-12-21 23:02:50 -0800399 const Node *node() const override { return node_; }
400
James Kuszmaul3ae42262019-11-08 12:33:41 -0800401 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 name_ = std::string(name);
403 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800404 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700405
406 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
407
Austin Schuh39788ff2019-12-01 18:22:57 -0800408 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 }
412
Austin Schuh39788ff2019-12-01 18:22:57 -0800413 int priority() const override { return priority_; }
414
415 void Setup() { MaybeScheduleTimingReports(); }
416
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800418 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800419 friend class SimulatedPhasedLoopHandler;
420 friend class SimulatedWatcher;
421
422 void HandleEvent() {
423 while (true) {
424 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
425 break;
426 }
427
428 EventLoopEvent *event = PopEvent();
429 event->HandleEvent();
430 }
431 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800432
Austin Schuh39788ff2019-12-01 18:22:57 -0800433 pid_t GetTid() override { return tid_; }
434
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 EventScheduler *scheduler_;
436 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
437 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
438 *raw_event_loops_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700439
440 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800441
442 int priority_ = 0;
443
444 bool has_setup_ = false;
445
Austin Schuh7d87b672019-12-01 20:23:49 -0800446 std::chrono::nanoseconds send_delay_;
447
Austin Schuh217a9782019-12-21 23:02:50 -0800448 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450};
451
Austin Schuh7d87b672019-12-01 20:23:49 -0800452void SimulatedEventLoopFactory::set_send_delay(
453 std::chrono::nanoseconds send_delay) {
454 send_delay_ = send_delay;
455 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
456 raw_event_loops_) {
457 reinterpret_cast<SimulatedEventLoop *>(loop.first)
458 ->set_send_delay(send_delay_);
459 }
460}
461
James Kuszmaul314f1672020-01-03 20:02:08 -0800462std::chrono::nanoseconds SimulatedEventLoopFactory::send_delay() const {
463 return send_delay_;
464}
465
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466void SimulatedEventLoop::MakeRawWatcher(
467 const Channel *channel,
468 std::function<void(const Context &channel, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800469 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800470
Austin Schuh7d87b672019-12-01 20:23:49 -0800471 std::unique_ptr<SimulatedWatcher> shm_watcher(
472 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800473
474 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
475 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476}
477
478std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
479 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800480 TakeSender(channel);
481
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 return GetSimulatedChannel(channel)->MakeRawSender(this);
483}
484
485std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
486 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800487 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800488
Austin Schuhca4828c2019-12-28 14:21:35 -0800489 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
490 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
491 << "\", \"type\": \"" << channel->type()->string_view()
492 << "\" } is not able to be fetched on this node. Check your "
493 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800494 }
495
Austin Schuh39788ff2019-12-01 18:22:57 -0800496 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497}
498
499SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
500 const Channel *channel) {
501 auto it = channels_->find(SimpleChannel(channel));
502 if (it == channels_->end()) {
503 it = channels_
504 ->emplace(SimpleChannel(channel),
505 std::unique_ptr<SimulatedChannel>(
506 new SimulatedChannel(channel, scheduler_)))
507 .first;
508 }
509 return it->second.get();
510}
511
Austin Schuh7d87b672019-12-01 20:23:49 -0800512SimulatedWatcher::SimulatedWatcher(
513 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
514 const Channel *channel,
515 std::function<void(const Context &context, const void *message)> fn)
516 : WatcherState(simulated_event_loop, channel, std::move(fn)),
517 simulated_event_loop_(simulated_event_loop),
518 event_(this),
519 scheduler_(scheduler),
520 token_(scheduler_->InvalidToken()) {}
521
522SimulatedWatcher::~SimulatedWatcher() {
523 simulated_event_loop_->RemoveEvent(&event_);
524 if (token_ != scheduler_->InvalidToken()) {
525 scheduler_->Deschedule(token_);
526 }
527 simulated_channel_->RemoveWatcher(this);
528}
529
530void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
Austin Schuha5e14192020-01-06 18:02:41 -0800531 monotonic_clock::time_point event_time =
532 simulated_event_loop_->monotonic_now();
Austin Schuh7d87b672019-12-01 20:23:49 -0800533
534 // Messages are queued in order. If we are the first, add ourselves.
535 // Otherwise, don't.
536 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800537 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800538 simulated_event_loop_->AddEvent(&event_);
539
540 DoSchedule(event_time);
541 }
542
543 msgs_.emplace_back(message);
544}
545
546void SimulatedWatcher::HandleEvent() {
547 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
548
549 const monotonic_clock::time_point monotonic_now =
550 simulated_event_loop_->monotonic_now();
Austin Schuhad154822019-12-27 15:45:13 -0800551 Context context = msgs_.front()->context;
552
553 if (context.remote_queue_index == 0xffffffffu) {
554 context.remote_queue_index = context.queue_index;
555 }
556 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
557 context.monotonic_remote_time = context.monotonic_event_time;
558 }
559 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
560 context.realtime_remote_time = context.realtime_event_time;
561 }
562
563 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800564
565 msgs_.pop_front();
566 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800567 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800568 simulated_event_loop_->AddEvent(&event_);
569
570 DoSchedule(event_.event_time());
571 } else {
572 token_ = scheduler_->InvalidToken();
573 }
574}
575
576void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
577 token_ =
578 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
579 [this]() { simulated_event_loop_->HandleEvent(); });
580}
581
582void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800583 watcher->SetSimulatedChannel(this);
584 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585}
586
587::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
588 EventLoop *event_loop) {
589 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
590}
591
Austin Schuh39788ff2019-12-01 18:22:57 -0800592::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
593 EventLoop *event_loop) {
594 ::std::unique_ptr<SimulatedFetcher> fetcher(
595 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700596 fetchers_.push_back(fetcher.get());
597 return ::std::move(fetcher);
598}
599
Austin Schuhad154822019-12-27 15:45:13 -0800600uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
601 const uint32_t queue_index = next_queue_index_.index();
602 message->context.queue_index = queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 message->context.data =
604 message->data() + channel()->max_size() - message->context.size;
605 next_queue_index_ = next_queue_index_.Increment();
606
607 latest_message_ = message;
608 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800609 for (SimulatedWatcher *watcher : watchers_) {
610 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700611 }
612 }
613 for (auto &fetcher : fetchers_) {
614 fetcher->Enqueue(message);
615 }
Austin Schuhad154822019-12-27 15:45:13 -0800616
617 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618}
619
620void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
621 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
622}
623
Austin Schuh39788ff2019-12-01 18:22:57 -0800624SimulatedTimerHandler::SimulatedTimerHandler(
625 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
626 ::std::function<void()> fn)
627 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800628 simulated_event_loop_(simulated_event_loop),
629 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800630 scheduler_(scheduler),
631 token_(scheduler_->InvalidToken()) {}
632
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800633void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
634 monotonic_clock::duration repeat_offset) {
635 Disable();
636 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800637 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800638 base_ = base;
639 repeat_offset_ = repeat_offset;
640 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800641 token_ = scheduler_->Schedule(
642 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800643 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800644 token_ = scheduler_->Schedule(
645 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800646 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800647 event_.set_event_time(base_);
648 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800649}
650
651void SimulatedTimerHandler::HandleEvent() {
652 const ::aos::monotonic_clock::time_point monotonic_now =
Austin Schuha5e14192020-01-06 18:02:41 -0800653 simulated_event_loop_->monotonic_now();
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800654 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
655 // Reschedule.
656 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800657 token_ = scheduler_->Schedule(
658 base_, [this]() { simulated_event_loop_->HandleEvent(); });
659 event_.set_event_time(base_);
660 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800661 } else {
662 token_ = scheduler_->InvalidToken();
663 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800664
Austin Schuh39788ff2019-12-01 18:22:57 -0800665 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800666}
667
Austin Schuh7d87b672019-12-01 20:23:49 -0800668void SimulatedTimerHandler::Disable() {
669 simulated_event_loop_->RemoveEvent(&event_);
670 if (token_ != scheduler_->InvalidToken()) {
671 scheduler_->Deschedule(token_);
672 token_ = scheduler_->InvalidToken();
673 }
674}
675
Austin Schuh39788ff2019-12-01 18:22:57 -0800676SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
677 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
678 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
679 const monotonic_clock::duration offset)
680 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
681 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800682 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800683 scheduler_(scheduler),
684 token_(scheduler_->InvalidToken()) {}
685
Austin Schuh7d87b672019-12-01 20:23:49 -0800686SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
687 if (token_ != scheduler_->InvalidToken()) {
688 scheduler_->Deschedule(token_);
689 token_ = scheduler_->InvalidToken();
690 }
691 simulated_event_loop_->RemoveEvent(&event_);
692}
693
694void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800695 monotonic_clock::time_point monotonic_now =
696 simulated_event_loop_->monotonic_now();
697 Call(
698 [monotonic_now]() { return monotonic_now; },
699 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
700}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800701
Austin Schuh7d87b672019-12-01 20:23:49 -0800702void SimulatedPhasedLoopHandler::Schedule(
703 monotonic_clock::time_point sleep_time) {
704 token_ = scheduler_->Schedule(
705 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
706 event_.set_event_time(sleep_time);
707 simulated_event_loop_->AddEvent(&event_);
708}
709
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710SimulatedEventLoopFactory::SimulatedEventLoopFactory(
711 const Configuration *configuration)
Austin Schuh217a9782019-12-21 23:02:50 -0800712 : configuration_(CHECK_NOTNULL(configuration)), node_(nullptr) {
713 CHECK(!configuration_->has_nodes())
714 << ": Got a configuration with multiple nodes and no node was selected.";
715}
716
717SimulatedEventLoopFactory::SimulatedEventLoopFactory(
718 const Configuration *configuration, std::string_view node_name)
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800719 : SimulatedEventLoopFactory(
720 configuration, configuration::GetNode(configuration, node_name)) {}
Austin Schuh217a9782019-12-21 23:02:50 -0800721
Austin Schuh15649d62019-12-28 16:36:38 -0800722SimulatedEventLoopFactory::SimulatedEventLoopFactory(
723 const Configuration *configuration, const Node *node)
724 : configuration_(CHECK_NOTNULL(configuration)), node_(node) {
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800725 if (node != nullptr) {
726 CHECK(configuration_->has_nodes())
727 << ": Got a configuration with no nodes and node \""
728 << node->name()->string_view() << "\" was selected.";
729 bool found = false;
730 for (const Node *node : *configuration_->nodes()) {
731 if (node == node_) {
732 found = true;
733 break;
734 }
Austin Schuh15649d62019-12-28 16:36:38 -0800735 }
Austin Schuh0bf5b9e2019-12-30 18:16:09 -0800736 CHECK(found) << ": node must be a pointer in the configuration.";
Austin Schuh15649d62019-12-28 16:36:38 -0800737 }
Austin Schuh15649d62019-12-28 16:36:38 -0800738}
739
Alex Perrycb7da4b2019-08-28 19:35:56 -0700740SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
741
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800742::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
743 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800744 pid_t tid = tid_;
745 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800746 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh217a9782019-12-21 23:02:50 -0800747 &scheduler_, &channels_, configuration_, &raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800748 result->set_name(name);
Austin Schuh7d87b672019-12-01 20:23:49 -0800749 result->set_send_delay(send_delay_);
750 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700751}
752
753void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
754 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
755 raw_event_loops_) {
756 event_loop.second(true);
757 }
758 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800759 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
760 raw_event_loops_) {
761 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762 }
763}
764
765void SimulatedEventLoopFactory::Run() {
766 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
767 raw_event_loops_) {
768 event_loop.second(true);
769 }
770 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800771 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
772 raw_event_loops_) {
773 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700774 }
775}
776
777} // namespace aos