blob: a2740e4cb660e872807257cc1a675575af672bd9 [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
Austin Schuhca4828c2019-12-28 14:21:35 -0800476 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
477 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
478 << "\", \"type\": \"" << channel->type()->string_view()
479 << "\" } is not able to be watched on this node. Check your "
480 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800481 }
482
Austin Schuh7d87b672019-12-01 20:23:49 -0800483 std::unique_ptr<SimulatedWatcher> shm_watcher(
484 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800485
486 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
487 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488}
489
490std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
491 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800492 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 Take(channel);
494 return GetSimulatedChannel(channel)->MakeRawSender(this);
495}
496
497std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
498 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800499 ChannelIndex(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800500
Austin Schuhca4828c2019-12-28 14:21:35 -0800501 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
502 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
503 << "\", \"type\": \"" << channel->type()->string_view()
504 << "\" } is not able to be fetched on this node. Check your "
505 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800506 }
507
Austin Schuh39788ff2019-12-01 18:22:57 -0800508 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509}
510
511SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
512 const Channel *channel) {
513 auto it = channels_->find(SimpleChannel(channel));
514 if (it == channels_->end()) {
515 it = channels_
516 ->emplace(SimpleChannel(channel),
517 std::unique_ptr<SimulatedChannel>(
518 new SimulatedChannel(channel, scheduler_)))
519 .first;
520 }
521 return it->second.get();
522}
523
Austin Schuh7d87b672019-12-01 20:23:49 -0800524SimulatedWatcher::SimulatedWatcher(
525 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
526 const Channel *channel,
527 std::function<void(const Context &context, const void *message)> fn)
528 : WatcherState(simulated_event_loop, channel, std::move(fn)),
529 simulated_event_loop_(simulated_event_loop),
530 event_(this),
531 scheduler_(scheduler),
532 token_(scheduler_->InvalidToken()) {}
533
534SimulatedWatcher::~SimulatedWatcher() {
535 simulated_event_loop_->RemoveEvent(&event_);
536 if (token_ != scheduler_->InvalidToken()) {
537 scheduler_->Deschedule(token_);
538 }
539 simulated_channel_->RemoveWatcher(this);
540}
541
542void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
543 monotonic_clock::time_point event_time = scheduler_->monotonic_now();
544
545 // Messages are queued in order. If we are the first, add ourselves.
546 // Otherwise, don't.
547 if (msgs_.size() == 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800548 event_.set_event_time(message->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800549 simulated_event_loop_->AddEvent(&event_);
550
551 DoSchedule(event_time);
552 }
553
554 msgs_.emplace_back(message);
555}
556
557void SimulatedWatcher::HandleEvent() {
558 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
559
560 const monotonic_clock::time_point monotonic_now =
561 simulated_event_loop_->monotonic_now();
Austin Schuhad154822019-12-27 15:45:13 -0800562 Context context = msgs_.front()->context;
563
564 if (context.remote_queue_index == 0xffffffffu) {
565 context.remote_queue_index = context.queue_index;
566 }
567 if (context.monotonic_remote_time == aos::monotonic_clock::min_time) {
568 context.monotonic_remote_time = context.monotonic_event_time;
569 }
570 if (context.realtime_remote_time == aos::realtime_clock::min_time) {
571 context.realtime_remote_time = context.realtime_event_time;
572 }
573
574 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
Austin Schuh7d87b672019-12-01 20:23:49 -0800575
576 msgs_.pop_front();
577 if (msgs_.size() != 0) {
Austin Schuhad154822019-12-27 15:45:13 -0800578 event_.set_event_time(msgs_.front()->context.monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800579 simulated_event_loop_->AddEvent(&event_);
580
581 DoSchedule(event_.event_time());
582 } else {
583 token_ = scheduler_->InvalidToken();
584 }
585}
586
587void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
588 token_ =
589 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
590 [this]() { simulated_event_loop_->HandleEvent(); });
591}
592
593void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800594 watcher->SetSimulatedChannel(this);
595 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700596}
597
598::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
599 EventLoop *event_loop) {
600 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
601}
602
Austin Schuh39788ff2019-12-01 18:22:57 -0800603::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
604 EventLoop *event_loop) {
605 ::std::unique_ptr<SimulatedFetcher> fetcher(
606 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607 fetchers_.push_back(fetcher.get());
608 return ::std::move(fetcher);
609}
610
Austin Schuhad154822019-12-27 15:45:13 -0800611uint32_t SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
612 const uint32_t queue_index = next_queue_index_.index();
613 message->context.queue_index = queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614 message->context.data =
615 message->data() + channel()->max_size() - message->context.size;
616 next_queue_index_ = next_queue_index_.Increment();
617
618 latest_message_ = message;
619 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800620 for (SimulatedWatcher *watcher : watchers_) {
621 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700622 }
623 }
624 for (auto &fetcher : fetchers_) {
625 fetcher->Enqueue(message);
626 }
Austin Schuhad154822019-12-27 15:45:13 -0800627
628 return queue_index;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700629}
630
631void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
632 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
633}
634
635SimpleChannel::SimpleChannel(const Channel *channel)
636 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
637 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
638
Austin Schuh39788ff2019-12-01 18:22:57 -0800639SimulatedTimerHandler::SimulatedTimerHandler(
640 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
641 ::std::function<void()> fn)
642 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800643 simulated_event_loop_(simulated_event_loop),
644 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800645 scheduler_(scheduler),
646 token_(scheduler_->InvalidToken()) {}
647
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800648void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
649 monotonic_clock::duration repeat_offset) {
650 Disable();
651 const ::aos::monotonic_clock::time_point monotonic_now =
652 scheduler_->monotonic_now();
653 base_ = base;
654 repeat_offset_ = repeat_offset;
655 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800656 token_ = scheduler_->Schedule(
657 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800658 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800659 token_ = scheduler_->Schedule(
660 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800661 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800662 event_.set_event_time(base_);
663 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800664}
665
666void SimulatedTimerHandler::HandleEvent() {
667 const ::aos::monotonic_clock::time_point monotonic_now =
668 scheduler_->monotonic_now();
669 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
670 // Reschedule.
671 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800672 token_ = scheduler_->Schedule(
673 base_, [this]() { simulated_event_loop_->HandleEvent(); });
674 event_.set_event_time(base_);
675 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800676 } else {
677 token_ = scheduler_->InvalidToken();
678 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800679
Austin Schuh39788ff2019-12-01 18:22:57 -0800680 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800681}
682
Austin Schuh7d87b672019-12-01 20:23:49 -0800683void SimulatedTimerHandler::Disable() {
684 simulated_event_loop_->RemoveEvent(&event_);
685 if (token_ != scheduler_->InvalidToken()) {
686 scheduler_->Deschedule(token_);
687 token_ = scheduler_->InvalidToken();
688 }
689}
690
Austin Schuh39788ff2019-12-01 18:22:57 -0800691SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
692 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
693 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
694 const monotonic_clock::duration offset)
695 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
696 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800697 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800698 scheduler_(scheduler),
699 token_(scheduler_->InvalidToken()) {}
700
Austin Schuh7d87b672019-12-01 20:23:49 -0800701SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
702 if (token_ != scheduler_->InvalidToken()) {
703 scheduler_->Deschedule(token_);
704 token_ = scheduler_->InvalidToken();
705 }
706 simulated_event_loop_->RemoveEvent(&event_);
707}
708
709void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800710 monotonic_clock::time_point monotonic_now =
711 simulated_event_loop_->monotonic_now();
712 Call(
713 [monotonic_now]() { return monotonic_now; },
714 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
715}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800716
Austin Schuh7d87b672019-12-01 20:23:49 -0800717void SimulatedPhasedLoopHandler::Schedule(
718 monotonic_clock::time_point sleep_time) {
719 token_ = scheduler_->Schedule(
720 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
721 event_.set_event_time(sleep_time);
722 simulated_event_loop_->AddEvent(&event_);
723}
724
Alex Perrycb7da4b2019-08-28 19:35:56 -0700725void SimulatedEventLoop::Take(const Channel *channel) {
726 CHECK(!is_running()) << ": Cannot add new objects while running.";
727
728 auto result = taken_.insert(SimpleChannel(channel));
729 CHECK(result.second) << ": " << FlatbufferToJson(channel)
730 << " is already being used.";
731}
732
733SimulatedEventLoopFactory::SimulatedEventLoopFactory(
734 const Configuration *configuration)
Austin Schuh217a9782019-12-21 23:02:50 -0800735 : configuration_(CHECK_NOTNULL(configuration)), node_(nullptr) {
736 CHECK(!configuration_->has_nodes())
737 << ": Got a configuration with multiple nodes and no node was selected.";
738}
739
740SimulatedEventLoopFactory::SimulatedEventLoopFactory(
741 const Configuration *configuration, std::string_view node_name)
742 : configuration_(CHECK_NOTNULL(configuration)),
743 node_(configuration::GetNode(configuration, node_name)) {
744 CHECK(configuration_->has_nodes())
745 << ": Got a configuration with no nodes and node \"" << node_name
746 << "\" was selected.";
747 CHECK(node_ != nullptr) << ": Can't find node \"" << node_name
748 << "\" in the configuration.";
749}
750
Alex Perrycb7da4b2019-08-28 19:35:56 -0700751SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
752
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800753::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
754 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800755 pid_t tid = tid_;
756 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800757 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh217a9782019-12-21 23:02:50 -0800758 &scheduler_, &channels_, configuration_, &raw_event_loops_, node_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800759 result->set_name(name);
Austin Schuh7d87b672019-12-01 20:23:49 -0800760 result->set_send_delay(send_delay_);
761 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762}
763
764void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
765 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
766 raw_event_loops_) {
767 event_loop.second(true);
768 }
769 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800770 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
771 raw_event_loops_) {
772 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700773 }
774}
775
776void SimulatedEventLoopFactory::Run() {
777 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
778 raw_event_loops_) {
779 event_loop.second(true);
780 }
781 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800782 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
783 raw_event_loops_) {
784 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700785 }
786}
787
788} // namespace aos