blob: 578e1510bf6d276c28812daa3c03dbea9c1ad33d [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"
8#include "absl/container/btree_set.h"
9#include "aos/json_to_flatbuffer.h"
10#include "aos/util/phased_loop.h"
11
12namespace aos {
13
14// Container for both a message, and the context for it for simulation. This
15// makes tracking the timestamps associated with the data easy.
16struct SimulatedMessage {
17 // Struct to let us force data to be well aligned.
18 struct OveralignedChar {
19 char data alignas(32);
20 };
21
22 // Context for the data.
23 Context context;
24
25 // The data.
26 char *data() { return reinterpret_cast<char *>(&actual_data[0]); }
27
28 // Then the data.
29 OveralignedChar actual_data[];
30};
31
Austin Schuh7d87b672019-12-01 20:23:49 -080032class SimulatedEventLoop;
Alex Perrycb7da4b2019-08-28 19:35:56 -070033class SimulatedFetcher;
Austin Schuh39788ff2019-12-01 18:22:57 -080034class SimulatedChannel;
35
Austin Schuh7d87b672019-12-01 20:23:49 -080036class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080037 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080038 SimulatedWatcher(
39 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
40 const Channel *channel,
41 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080042
Austin Schuh7d87b672019-12-01 20:23:49 -080043 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080044
45 void Startup(EventLoop * /*event_loop*/) override {}
46
Austin Schuh7d87b672019-12-01 20:23:49 -080047 void Schedule(std::shared_ptr<SimulatedMessage> message);
48
49 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080050
51 void SetSimulatedChannel(SimulatedChannel *channel) {
52 simulated_channel_ = channel;
53 }
54
55 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080056 void DoSchedule(monotonic_clock::time_point event_time);
57
58 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
59
60 SimulatedEventLoop *simulated_event_loop_;
61 EventHandler<SimulatedWatcher> event_;
62 EventScheduler *scheduler_;
63 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -080064 SimulatedChannel *simulated_channel_ = nullptr;
65};
Alex Perrycb7da4b2019-08-28 19:35:56 -070066
67class SimulatedChannel {
68 public:
69 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -080070 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070071 scheduler_(scheduler),
72 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
73
74 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
75
76 // Makes a connected raw sender which calls Send below.
77 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
78
79 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -080080 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -070081
82 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -080083 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -080084
Austin Schuh7d87b672019-12-01 20:23:49 -080085 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -080086 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
87 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070088
Austin Schuhad154822019-12-27 15:45:13 -080089 // Sends the message to all the connected receivers and fetchers. Returns the
90 // sent queue index.
91 uint32_t Send(std::shared_ptr<SimulatedMessage> message);
Alex Perrycb7da4b2019-08-28 19:35:56 -070092
93 // Unregisters a fetcher.
94 void UnregisterFetcher(SimulatedFetcher *fetcher);
95
96 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
97
Austin Schuh39788ff2019-12-01 18:22:57 -080098 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -070099
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800100 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800101 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102 }
103
Austin Schuh39788ff2019-12-01 18:22:57 -0800104 const Channel *channel() const { return channel_; }
105
106 ::aos::monotonic_clock::time_point monotonic_now() const {
107 return scheduler_->monotonic_now();
108 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109
110 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800111 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112
113 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800114 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700115
116 // List of all fetchers.
117 ::std::vector<SimulatedFetcher *> fetchers_;
118 std::shared_ptr<SimulatedMessage> latest_message_;
119 EventScheduler *scheduler_;
120
121 ipc_lib::QueueIndex next_queue_index_;
122};
123
124namespace {
125
126// Creates a SimulatedMessage with size bytes of storage.
127// This is a shared_ptr so we don't have to implement refcounting or copying.
128std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
129 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
130 malloc(sizeof(SimulatedMessage) + size));
131 message->context.size = size;
132 message->context.data = message->data();
133
134 return std::shared_ptr<SimulatedMessage>(message, free);
135}
136
137class SimulatedSender : public RawSender {
138 public:
139 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800140 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800141 simulated_channel_(simulated_channel),
142 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143 ~SimulatedSender() {}
144
145 void *data() override {
146 if (!message_) {
147 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
148 }
149 return message_->data();
150 }
151
152 size_t size() override { return simulated_channel_->max_size(); }
153
Austin Schuhad154822019-12-27 15:45:13 -0800154 bool DoSend(size_t length,
155 aos::monotonic_clock::time_point monotonic_remote_time,
156 aos::realtime_clock::time_point realtime_remote_time,
157 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700158 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
Austin Schuhad154822019-12-27 15:45:13 -0800159 message_->context.monotonic_event_time = event_loop_->monotonic_now();
160 message_->context.monotonic_remote_time = monotonic_remote_time;
161 message_->context.remote_queue_index = remote_queue_index;
162 message_->context.realtime_event_time = event_loop_->realtime_now();
163 message_->context.realtime_remote_time = realtime_remote_time;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164 CHECK_LE(length, message_->context.size);
165 message_->context.size = length;
166
167 // TODO(austin): Track sending too fast.
Austin Schuhad154822019-12-27 15:45:13 -0800168 sent_queue_index_ = simulated_channel_->Send(message_);
169 monotonic_sent_time_ = event_loop_->monotonic_now();
170 realtime_sent_time_ = event_loop_->realtime_now();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
172 // Drop the reference to the message so that we allocate a new message for
173 // next time. Otherwise we will continue to reuse the same memory for all
174 // messages and corrupt it.
175 message_.reset();
176 return true;
177 }
178
Austin Schuhad154822019-12-27 15:45:13 -0800179 bool DoSend(const void *msg, size_t size,
180 aos::monotonic_clock::time_point monotonic_remote_time,
181 aos::realtime_clock::time_point realtime_remote_time,
182 uint32_t remote_queue_index) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
184
185 // This is wasteful, but since flatbuffers fill from the back end of the
186 // queue, we need it to be full sized.
187 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
188
189 // Now fill in the message. size is already populated above, and
190 // queue_index will be populated in queue_. Put this at the back of the
191 // data segment.
192 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
193
Austin Schuhad154822019-12-27 15:45:13 -0800194 return Send(size, monotonic_remote_time, realtime_remote_time,
195 remote_queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700196 }
197
Alex Perrycb7da4b2019-08-28 19:35:56 -0700198 private:
199 SimulatedChannel *simulated_channel_;
200 EventLoop *event_loop_;
201
202 std::shared_ptr<SimulatedMessage> message_;
203};
204} // namespace
205
206class SimulatedFetcher : public RawFetcher {
207 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800208 explicit SimulatedFetcher(EventLoop *event_loop, SimulatedChannel *queue)
209 : RawFetcher(event_loop, queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
211
Austin Schuh39788ff2019-12-01 18:22:57 -0800212 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
213 if (msgs_.size() == 0) {
214 return std::make_pair(false, monotonic_clock::min_time);
215 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700216
217 SetMsg(msgs_.front());
218 msgs_.pop_front();
Austin Schuh39788ff2019-12-01 18:22:57 -0800219 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700220 }
221
Austin Schuh39788ff2019-12-01 18:22:57 -0800222 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700223 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800224 // TODO(austin): Can we just do this logic unconditionally? It is a lot
225 // simpler. And call clear, obviously.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700226 if (!msg_ && queue_->latest_message()) {
227 SetMsg(queue_->latest_message());
Austin Schuh39788ff2019-12-01 18:22:57 -0800228 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800230 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231 }
232 }
233
234 // We've had a message enqueued, so we don't need to go looking for the
235 // latest message from before we started.
236 SetMsg(msgs_.back());
237 msgs_.clear();
Austin Schuh39788ff2019-12-01 18:22:57 -0800238 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239 }
240
241 private:
242 friend class SimulatedChannel;
243
244 // Updates the state inside RawFetcher to point to the data in msg_.
245 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
246 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700247 context_ = msg_->context;
Austin Schuhad154822019-12-27 15:45:13 -0800248 if (context_.remote_queue_index == 0xffffffffu) {
249 context_.remote_queue_index = context_.queue_index;
250 }
251 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
252 context_.monotonic_remote_time = context_.monotonic_event_time;
253 }
254 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
255 context_.realtime_remote_time = context_.realtime_event_time;
256 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700257 }
258
259 // Internal method for Simulation to add a message to the buffer.
260 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
261 msgs_.emplace_back(buffer);
262 }
263
264 SimulatedChannel *queue_;
265 std::shared_ptr<SimulatedMessage> msg_;
266
267 // Messages queued up but not in use.
268 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
269};
270
271class SimulatedTimerHandler : public TimerHandler {
272 public:
273 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800274 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800275 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800276 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277
278 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800279 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800281 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700282
Austin Schuh7d87b672019-12-01 20:23:49 -0800283 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284
285 ::aos::monotonic_clock::time_point monotonic_now() const {
286 return scheduler_->monotonic_now();
287 }
288
289 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800290 SimulatedEventLoop *simulated_event_loop_;
291 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292 EventScheduler *scheduler_;
293 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800294
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295 monotonic_clock::time_point base_;
296 monotonic_clock::duration repeat_offset_;
297};
298
299class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
300 public:
301 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800302 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 ::std::function<void(int)> fn,
304 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800305 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800306 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
Austin Schuh7d87b672019-12-01 20:23:49 -0800308 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309
Austin Schuh7d87b672019-12-01 20:23:49 -0800310 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311
312 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800313 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800314 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
Austin Schuh39788ff2019-12-01 18:22:57 -0800316 EventScheduler *scheduler_;
317 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700318};
319
320class SimulatedEventLoop : public EventLoop {
321 public:
322 explicit SimulatedEventLoop(
323 EventScheduler *scheduler,
324 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
325 *channels,
326 const Configuration *configuration,
327 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800328 *raw_event_loops,
Austin Schuh217a9782019-12-21 23:02:50 -0800329 const Node *node, pid_t tid)
Austin Schuh39788ff2019-12-01 18:22:57 -0800330 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 scheduler_(scheduler),
332 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800333 raw_event_loops_(raw_event_loops),
Austin Schuh217a9782019-12-21 23:02:50 -0800334 node_(node),
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 tid_(tid) {
336 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
337 if (!has_setup_) {
338 Setup();
339 has_setup_ = true;
340 }
341 set_is_running(value);
342 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 }
344 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800345 // Trigger any remaining senders or fetchers to be cleared before destroying
346 // the event loop so the book keeping matches.
347 timing_report_sender_.reset();
348
349 // Force everything with a registered fd with epoll to be destroyed now.
350 timers_.clear();
351 phased_loops_.clear();
352 watchers_.clear();
353
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
355 ++it) {
356 if (it->first == this) {
357 raw_event_loops_->erase(it);
358 break;
359 }
360 }
361 }
362
Austin Schuh7d87b672019-12-01 20:23:49 -0800363 std::chrono::nanoseconds send_delay() const { return send_delay_; }
364 void set_send_delay(std::chrono::nanoseconds send_delay) {
365 send_delay_ = send_delay;
366 }
367
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 ::aos::monotonic_clock::time_point monotonic_now() override {
369 return scheduler_->monotonic_now();
370 }
371
372 ::aos::realtime_clock::time_point realtime_now() override {
373 return scheduler_->realtime_now();
374 }
375
376 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
377
378 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
379
380 void MakeRawWatcher(
381 const Channel *channel,
382 ::std::function<void(const Context &context, const void *message)>
383 watcher) override;
384
385 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800386 CHECK(!is_running());
387 return NewTimer(::std::unique_ptr<TimerHandler>(
388 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389 }
390
391 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
392 const monotonic_clock::duration interval,
393 const monotonic_clock::duration offset =
394 ::std::chrono::seconds(0)) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 return NewPhasedLoop(
396 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
397 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700398 }
399
400 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 }
403
Austin Schuh217a9782019-12-21 23:02:50 -0800404 const Node *node() const override { return node_; }
405
James Kuszmaul3ae42262019-11-08 12:33:41 -0800406 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 name_ = std::string(name);
408 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800409 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700410
411 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
412
413 void Take(const Channel *channel);
414
Austin Schuh39788ff2019-12-01 18:22:57 -0800415 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800417 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418 }
419
Austin Schuh39788ff2019-12-01 18:22:57 -0800420 int priority() const override { return priority_; }
421
422 void Setup() { MaybeScheduleTimingReports(); }
423
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800425 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800426 friend class SimulatedPhasedLoopHandler;
427 friend class SimulatedWatcher;
428
429 void HandleEvent() {
430 while (true) {
431 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
432 break;
433 }
434
435 EventLoopEvent *event = PopEvent();
436 event->HandleEvent();
437 }
438 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800439
Austin Schuh39788ff2019-12-01 18:22:57 -0800440 pid_t GetTid() override { return tid_; }
441
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442 EventScheduler *scheduler_;
443 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
444 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
445 *raw_event_loops_;
446 absl::btree_set<SimpleChannel> taken_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447
448 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800449
450 int priority_ = 0;
451
452 bool has_setup_ = false;
453
Austin Schuh7d87b672019-12-01 20:23:49 -0800454 std::chrono::nanoseconds send_delay_;
455
Austin Schuh217a9782019-12-21 23:02:50 -0800456 const Node *const node_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800457 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458};
459
Austin Schuh7d87b672019-12-01 20:23:49 -0800460void SimulatedEventLoopFactory::set_send_delay(
461 std::chrono::nanoseconds send_delay) {
462 send_delay_ = send_delay;
463 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
464 raw_event_loops_) {
465 reinterpret_cast<SimulatedEventLoop *>(loop.first)
466 ->set_send_delay(send_delay_);
467 }
468}
469
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470void SimulatedEventLoop::MakeRawWatcher(
471 const Channel *channel,
472 std::function<void(const Context &channel, const void *message)> watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800473 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474 Take(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800475
476 if (node() != nullptr) {
477 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
478 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
479 << "\", \"type\": \"" << channel->type()->string_view()
480 << "\" } is not able to be watched on this node. Check your "
481 "configuration.";
482 }
483 }
484
Austin Schuh7d87b672019-12-01 20:23:49 -0800485 std::unique_ptr<SimulatedWatcher> shm_watcher(
486 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800487
488 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
489 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700490}
491
492std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
493 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800494 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495 Take(channel);
496 return GetSimulatedChannel(channel)->MakeRawSender(this);
497}
498
499std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
500 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800501 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800502
503 if (node() != nullptr) {
504 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
505 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
506 << "\", \"type\": \"" << channel->type()->string_view()
507 << "\" } is not able to be fetched on this node. Check your "
508 "configuration.";
509 }
510 }
511
Austin Schuh39788ff2019-12-01 18:22:57 -0800512 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700513}
514
515SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
516 const Channel *channel) {
517 auto it = channels_->find(SimpleChannel(channel));
518 if (it == channels_->end()) {
519 it = channels_
520 ->emplace(SimpleChannel(channel),
521 std::unique_ptr<SimulatedChannel>(
522 new SimulatedChannel(channel, scheduler_)))
523 .first;
524 }
525 return it->second.get();
526}
527
Austin Schuh7d87b672019-12-01 20:23:49 -0800528SimulatedWatcher::SimulatedWatcher(
529 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
530 const Channel *channel,
531 std::function<void(const Context &context, const void *message)> fn)
532 : WatcherState(simulated_event_loop, channel, std::move(fn)),
533 simulated_event_loop_(simulated_event_loop),
534 event_(this),
535 scheduler_(scheduler),
536 token_(scheduler_->InvalidToken()) {}
537
538SimulatedWatcher::~SimulatedWatcher() {
539 simulated_event_loop_->RemoveEvent(&event_);
540 if (token_ != scheduler_->InvalidToken()) {
541 scheduler_->Deschedule(token_);
542 }
543 simulated_channel_->RemoveWatcher(this);
544}
545
546void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
547 monotonic_clock::time_point event_time = scheduler_->monotonic_now();
548
549 // Messages are queued in order. If we are the first, add ourselves.
550 // Otherwise, don't.
551 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800552 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800553 simulated_event_loop_->AddEvent(&event_);
554
555 DoSchedule(event_time);
556 }
557
558 msgs_.emplace_back(message);
559}
560
561void SimulatedWatcher::HandleEvent() {
562 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
563
564 const monotonic_clock::time_point monotonic_now =
565 simulated_event_loop_->monotonic_now();
Austin Schuhad154822019-12-27 15:45:13 -0800566 Context context = msgs_.front()->context;
567
568 if (context.remote_queue_index == 0xffffffffu) {
569 context.remote_queue_index = context.queue_index;
570 }
571 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
572 context.monotonic_remote_time = context.monotonic_event_time;
573 }
574 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
575 context.realtime_remote_time = context.realtime_event_time;
576 }
577
578 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800579
580 msgs_.pop_front();
581 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800582 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800583 simulated_event_loop_->AddEvent(&event_);
584
585 DoSchedule(event_.event_time());
586 } else {
587 token_ = scheduler_->InvalidToken();
588 }
589}
590
591void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
592 token_ =
593 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
594 [this]() { simulated_event_loop_->HandleEvent(); });
595}
596
597void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800598 watcher->SetSimulatedChannel(this);
599 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700600}
601
602::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
603 EventLoop *event_loop) {
604 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
605}
606
Austin Schuh39788ff2019-12-01 18:22:57 -0800607::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
608 EventLoop *event_loop) {
609 ::std::unique_ptr<SimulatedFetcher> fetcher(
610 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700611 fetchers_.push_back(fetcher.get());
612 return ::std::move(fetcher);
613}
614
Austin Schuhad154822019-12-27 15:45:13 -0800615uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
616 const uint32_t queue_index = next_queue_index_.index();
617 message->context.queue_index = queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 message->context.data =
619 message->data() + channel()->max_size() - message->context.size;
620 next_queue_index_ = next_queue_index_.Increment();
621
622 latest_message_ = message;
623 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800624 for (SimulatedWatcher *watcher : watchers_) {
625 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700626 }
627 }
628 for (auto &fetcher : fetchers_) {
629 fetcher->Enqueue(message);
630 }
Austin Schuhad154822019-12-27 15:45:13 -0800631
632 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700633}
634
635void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
636 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
637}
638
639SimpleChannel::SimpleChannel(const Channel *channel)
640 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
641 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
642
Austin Schuh39788ff2019-12-01 18:22:57 -0800643SimulatedTimerHandler::SimulatedTimerHandler(
644 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
645 ::std::function<void()> fn)
646 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800647 simulated_event_loop_(simulated_event_loop),
648 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800649 scheduler_(scheduler),
650 token_(scheduler_->InvalidToken()) {}
651
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800652void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
653 monotonic_clock::duration repeat_offset) {
654 Disable();
655 const ::aos::monotonic_clock::time_point monotonic_now =
656 scheduler_->monotonic_now();
657 base_ = base;
658 repeat_offset_ = repeat_offset;
659 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800660 token_ = scheduler_->Schedule(
661 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800662 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800663 token_ = scheduler_->Schedule(
664 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800665 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800666 event_.set_event_time(base_);
667 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800668}
669
670void SimulatedTimerHandler::HandleEvent() {
671 const ::aos::monotonic_clock::time_point monotonic_now =
672 scheduler_->monotonic_now();
673 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
674 // Reschedule.
675 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800676 token_ = scheduler_->Schedule(
677 base_, [this]() { simulated_event_loop_->HandleEvent(); });
678 event_.set_event_time(base_);
679 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800680 } else {
681 token_ = scheduler_->InvalidToken();
682 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800683
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800685}
686
Austin Schuh7d87b672019-12-01 20:23:49 -0800687void SimulatedTimerHandler::Disable() {
688 simulated_event_loop_->RemoveEvent(&event_);
689 if (token_ != scheduler_->InvalidToken()) {
690 scheduler_->Deschedule(token_);
691 token_ = scheduler_->InvalidToken();
692 }
693}
694
Austin Schuh39788ff2019-12-01 18:22:57 -0800695SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
696 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
697 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
698 const monotonic_clock::duration offset)
699 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
700 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800701 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800702 scheduler_(scheduler),
703 token_(scheduler_->InvalidToken()) {}
704
Austin Schuh7d87b672019-12-01 20:23:49 -0800705SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
706 if (token_ != scheduler_->InvalidToken()) {
707 scheduler_->Deschedule(token_);
708 token_ = scheduler_->InvalidToken();
709 }
710 simulated_event_loop_->RemoveEvent(&event_);
711}
712
713void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800714 monotonic_clock::time_point monotonic_now =
715 simulated_event_loop_->monotonic_now();
716 Call(
717 [monotonic_now]() { return monotonic_now; },
718 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
719}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800720
Austin Schuh7d87b672019-12-01 20:23:49 -0800721void SimulatedPhasedLoopHandler::Schedule(
722 monotonic_clock::time_point sleep_time) {
723 token_ = scheduler_->Schedule(
724 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
725 event_.set_event_time(sleep_time);
726 simulated_event_loop_->AddEvent(&event_);
727}
728
Alex Perrycb7da4b2019-08-28 19:35:56 -0700729void SimulatedEventLoop::Take(const Channel *channel) {
730 CHECK(!is_running()) << ": Cannot add new objects while running.";
731
732 auto result = taken_.insert(SimpleChannel(channel));
733 CHECK(result.second) << ": " << FlatbufferToJson(channel)
734 << " is already being used.";
735}
736
737SimulatedEventLoopFactory::SimulatedEventLoopFactory(
738 const Configuration *configuration)
Austin Schuh217a9782019-12-21 23:02:50 -0800739 : configuration_(CHECK_NOTNULL(configuration)), node_(nullptr) {
740 CHECK(!configuration_->has_nodes())
741 << ": Got a configuration with multiple nodes and no node was selected.";
742}
743
744SimulatedEventLoopFactory::SimulatedEventLoopFactory(
745 const Configuration *configuration, std::string_view node_name)
746 : configuration_(CHECK_NOTNULL(configuration)),
747 node_(configuration::GetNode(configuration, node_name)) {
748 CHECK(configuration_->has_nodes())
749 << ": Got a configuration with no nodes and node \"" << node_name
750 << "\" was selected.";
751 CHECK(node_ != nullptr) << ": Can't find node \"" << node_name
752 << "\" in the configuration.";
753}
754
Alex Perrycb7da4b2019-08-28 19:35:56 -0700755SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
756
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800757::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
758 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800759 pid_t tid = tid_;
760 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800761 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh217a9782019-12-21 23:02:50 -0800762 &scheduler_, &channels_, configuration_, &raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800763 result->set_name(name);
Austin Schuh7d87b672019-12-01 20:23:49 -0800764 result->set_send_delay(send_delay_);
765 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700766}
767
768void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
769 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
770 raw_event_loops_) {
771 event_loop.second(true);
772 }
773 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800774 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
775 raw_event_loops_) {
776 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700777 }
778}
779
780void SimulatedEventLoopFactory::Run() {
781 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
782 raw_event_loops_) {
783 event_loop.second(true);
784 }
785 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800786 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
787 raw_event_loops_) {
788 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700789 }
790}
791
792} // namespace aos